title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Work with ZIP archives in Python (zipfile)
|
The ZIP is one of the most popular file formats used for archiving and compression. It has been in use since the days of MSDOS and PC and has been used by famous PKZIP application.
The zipfile module in Python’s standard library provides classes that facilitate the tools for creating, extracting, reading and writing to ZIP archives.
This function returns a ZipFile object from a file parameter which can be a string or file object as created by built-in open() function. The function needs a mode parameter whose default value is ‘r’ although it can take ‘w’ or ‘a’ value for opening the archive in read, write or append mode respectively.
The archive by default is uncompressed. To specify the type of compression algorithm to be used, one of the constants has to be assigned to compression parameter.
The ZipFile object uses following mehods.
This method given file to the archive represented by ZipFile object.
>>> import zipfile
>>> newzip=zipfile.ZipFile('newdir/newzip.zip','w')
>>> newzip.write('zen.txt')
>>> newzip.close()
Additional file can be added to already existing archive by opening it in append mode (‘a’ as the mode)
>>> newzip=zipfile.ZipFile('newdir/newzip.zip','a')
>>> newzip.write('zen.txt')
>>> newzip.close()
This method reads data from a particular file in the archive.
>>> newzip=zipfile.ZipFile('newdir/newzip.zip','r')
>>> data=newzip.read('json.txt')
>>> data
b'["Rakesh", {"marks": [50, 60, 70]}]'
This method lists all file in given archive.
>>> newzip.printdir()
File Name Modified Size
json.txt 2018-11-2717:04:40 35
zen.txt 2018-11-2523:13:44 878
This method extracts a specified file from archive by default to current directory or to one given as second parameter to it.
>>> newzip.extract('json.txt','newdir')
'newdir\\json.txt'
This method extracts all files in the archive to current directory by default. Specify alternate directory if required as parameter.
>>> newzip.extractall('newdir')
This method returns ZipInfo object corresponding to the given file. The ZipInfo object contains different metadata information of the file.
Following code obtains ZipInfo object of ‘zen.txt’ from the archive and retrieves filename, size and date-time information from it.
>>> inf = newzip.getinfo('zen.txt')
>>> inf.filename,inf.file_size, inf.date_time
('zen.txt', 878, (2018, 11, 25, 23, 13, 45))
This method returns a list of ZipInfo objects of all file in the archive.
>>> newzip.infolist()
[<ZipInfo filename = 'json.txt' filemode='-rw-rw-rw-' file_size=35>, <ZipInfo filename = 'zen.txt' filemode='-rw-rw-rw-' file_size=878>]
As mentioned earlier, compression algorithm to be applied while constructing ZIP archive is specified in compression parameter. In following code, ZIP-DEFLATED constant builds the archive using zlib compression.
>>> zipobj = zipfile.ZipFile('txtzip.zip',mode='w', compression=zipfile.ZIP_DEFLATED)
>>> files=glob.glob("*.txt")
>>> for file in files:
zipobj.write(file)
>>> zipobj.close()
This method of ZipFile object returns a list of all files in the archive.
>>> zipobj = zipfile.ZipFile('txtzip.zip',mode='r')
>>> zipobj.namelist()
['a!.txt', 'data().txt', 'dict.txt', 'json.txt', 'LICENSE.txt', 'lines.txt', 'msg.txt', 'NEWS.txt', 'test.txt/', 'zen.txt', 'zen1.txt', 'zenbak.txt']
This method sets password parameter which must be provided at the time of extracting the archive.
This function in zipfile module returns PyZipFile object. The PyZipFile object can construct a module containing files with .py extension. This archive can be added in sys.path environment variable so that the module can be imported using zipimport module.
The writepy() method adds a .py file in the archive after compiling it in respective .pyc file.
files=glob.glob("*.py")
>>> pyzipobj = zipfile.PyZipFile('pyfiles/pyzip.zip', mode='w', compression=zipfile.ZIP_LZMA)
>>> for file in files:
pyzipobj.writepy(file)
>>> pyzipobj.close()
In this article classes and functions in zipfile module has been discussed.
|
[
{
"code": null,
"e": 1368,
"s": 1187,
"text": "The ZIP is one of the most popular file formats used for archiving and compression. It has been in use since the days of MSDOS and PC and has been used by famous PKZIP application."
},
{
"code": null,
"e": 1522,
"s": 1368,
"text": "The zipfile module in Python’s standard library provides classes that facilitate the tools for creating, extracting, reading and writing to ZIP archives."
},
{
"code": null,
"e": 1829,
"s": 1522,
"text": "This function returns a ZipFile object from a file parameter which can be a string or file object as created by built-in open() function. The function needs a mode parameter whose default value is ‘r’ although it can take ‘w’ or ‘a’ value for opening the archive in read, write or append mode respectively."
},
{
"code": null,
"e": 1992,
"s": 1829,
"text": "The archive by default is uncompressed. To specify the type of compression algorithm to be used, one of the constants has to be assigned to compression parameter."
},
{
"code": null,
"e": 2034,
"s": 1992,
"text": "The ZipFile object uses following mehods."
},
{
"code": null,
"e": 2103,
"s": 2034,
"text": "This method given file to the archive represented by ZipFile object."
},
{
"code": null,
"e": 2221,
"s": 2103,
"text": ">>> import zipfile\n>>> newzip=zipfile.ZipFile('newdir/newzip.zip','w')\n>>> newzip.write('zen.txt')\n>>> newzip.close()"
},
{
"code": null,
"e": 2325,
"s": 2221,
"text": "Additional file can be added to already existing archive by opening it in append mode (‘a’ as the mode)"
},
{
"code": null,
"e": 2424,
"s": 2325,
"text": ">>> newzip=zipfile.ZipFile('newdir/newzip.zip','a')\n>>> newzip.write('zen.txt')\n>>> newzip.close()"
},
{
"code": null,
"e": 2486,
"s": 2424,
"text": "This method reads data from a particular file in the archive."
},
{
"code": null,
"e": 2619,
"s": 2486,
"text": ">>> newzip=zipfile.ZipFile('newdir/newzip.zip','r')\n>>> data=newzip.read('json.txt')\n>>> data\nb'[\"Rakesh\", {\"marks\": [50, 60, 70]}]'"
},
{
"code": null,
"e": 2664,
"s": 2619,
"text": "This method lists all file in given archive."
},
{
"code": null,
"e": 2772,
"s": 2664,
"text": ">>> newzip.printdir()\nFile Name Modified Size\njson.txt 2018-11-2717:04:40 35\nzen.txt 2018-11-2523:13:44 878"
},
{
"code": null,
"e": 2898,
"s": 2772,
"text": "This method extracts a specified file from archive by default to current directory or to one given as second parameter to it."
},
{
"code": null,
"e": 2957,
"s": 2898,
"text": ">>> newzip.extract('json.txt','newdir')\n'newdir\\\\json.txt'"
},
{
"code": null,
"e": 3090,
"s": 2957,
"text": "This method extracts all files in the archive to current directory by default. Specify alternate directory if required as parameter."
},
{
"code": null,
"e": 3122,
"s": 3090,
"text": ">>> newzip.extractall('newdir')"
},
{
"code": null,
"e": 3262,
"s": 3122,
"text": "This method returns ZipInfo object corresponding to the given file. The ZipInfo object contains different metadata information of the file."
},
{
"code": null,
"e": 3394,
"s": 3262,
"text": "Following code obtains ZipInfo object of ‘zen.txt’ from the archive and retrieves filename, size and date-time information from it."
},
{
"code": null,
"e": 3521,
"s": 3394,
"text": ">>> inf = newzip.getinfo('zen.txt')\n>>> inf.filename,inf.file_size, inf.date_time\n('zen.txt', 878, (2018, 11, 25, 23, 13, 45))"
},
{
"code": null,
"e": 3595,
"s": 3521,
"text": "This method returns a list of ZipInfo objects of all file in the archive."
},
{
"code": null,
"e": 3754,
"s": 3595,
"text": ">>> newzip.infolist()\n[<ZipInfo filename = 'json.txt' filemode='-rw-rw-rw-' file_size=35>, <ZipInfo filename = 'zen.txt' filemode='-rw-rw-rw-' file_size=878>]"
},
{
"code": null,
"e": 3966,
"s": 3754,
"text": "As mentioned earlier, compression algorithm to be applied while constructing ZIP archive is specified in compression parameter. In following code, ZIP-DEFLATED constant builds the archive using zlib compression."
},
{
"code": null,
"e": 4142,
"s": 3966,
"text": ">>> zipobj = zipfile.ZipFile('txtzip.zip',mode='w', compression=zipfile.ZIP_DEFLATED)\n>>> files=glob.glob(\"*.txt\")\n>>> for file in files:\nzipobj.write(file)\n>>> zipobj.close()"
},
{
"code": null,
"e": 4216,
"s": 4142,
"text": "This method of ZipFile object returns a list of all files in the archive."
},
{
"code": null,
"e": 4440,
"s": 4216,
"text": ">>> zipobj = zipfile.ZipFile('txtzip.zip',mode='r')\n>>> zipobj.namelist()\n['a!.txt', 'data().txt', 'dict.txt', 'json.txt', 'LICENSE.txt', 'lines.txt', 'msg.txt', 'NEWS.txt', 'test.txt/', 'zen.txt', 'zen1.txt', 'zenbak.txt']"
},
{
"code": null,
"e": 4538,
"s": 4440,
"text": "This method sets password parameter which must be provided at the time of extracting the archive."
},
{
"code": null,
"e": 4795,
"s": 4538,
"text": "This function in zipfile module returns PyZipFile object. The PyZipFile object can construct a module containing files with .py extension. This archive can be added in sys.path environment variable so that the module can be imported using zipimport module."
},
{
"code": null,
"e": 4891,
"s": 4795,
"text": "The writepy() method adds a .py file in the archive after compiling it in respective .pyc file."
},
{
"code": null,
"e": 5076,
"s": 4891,
"text": "files=glob.glob(\"*.py\")\n>>> pyzipobj = zipfile.PyZipFile('pyfiles/pyzip.zip', mode='w', compression=zipfile.ZIP_LZMA)\n>>> for file in files:\npyzipobj.writepy(file)\n>>> pyzipobj.close()"
},
{
"code": null,
"e": 5152,
"s": 5076,
"text": "In this article classes and functions in zipfile module has been discussed."
}
] |
Scrape Tables From any website using Python
|
06 Aug, 2021
Scraping is a very essential skill for everyone to get data from any website. Scraping and parsing a table can be very tedious work if we use standard Beautiful soup parser to do so. Therefore, here we will be describing a library with the help of which any table can be scraped from any website easily. With this method you don’t even have to inspect element of a website, you only have to provide the URL of the website. That’s it and the work will be done within seconds.
You can use pip to install this library:
pip install html-table-parser-python3
Step 1: Import the necessary libraries required for the task
# Library for opening url and creating
# requests
import urllib.request
# pretty-print python data structures
from pprint import pprint
# for parsing all the tables present
# on the website
from html_table_parser.parser import HTMLTableParser
# for converting the parsed data in a
# pandas dataframe
import pandas as pd
Step 2 : Defining a function to get contents of the website
# Opens a website and read its
# binary contents (HTTP Response Body)
def url_get_contents(url):
# Opens a website and read its
# binary contents (HTTP Response Body)
#making request to the website
req = urllib.request.Request(url=url)
f = urllib.request.urlopen(req)
#reading contents of the website
return f.read()
Now, our function is ready so we have to specify the url of the website from which we need to parse tables.
Note: Here we will be taking the example of moneycontrol.com website since it has many tables and will give you a better understanding. You can view the website here .
Step 3 : Parsing tables
# defining the html contents of a URL.
xhtml = url_get_contents('Link').decode('utf-8')
# Defining the HTMLTableParser object
p = HTMLTableParser()
# feeding the html contents in the
# HTMLTableParser object
p.feed(xhtml)
# Now finally obtaining the data of
# the table required
pprint(p.tables[1])
Each row of the table is stored in an array. This can be converted into a pandas dataframe easily and can be used to perform any analysis.
Complete Code:
Python3
# Library for opening url and creating# requestsimport urllib.request # pretty-print python data structuresfrom pprint import pprint # for parsing all the tables present# on the websitefrom html_table_parser.parser import HTMLTableParser # for converting the parsed data in a# pandas dataframeimport pandas as pd # Opens a website and read its# binary contents (HTTP Response Body)def url_get_contents(url): # Opens a website and read its # binary contents (HTTP Response Body) #making request to the website req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) #reading contents of the website return f.read() # defining the html contents of a URL.xhtml = url_get_contents('https://www.moneycontrol.com/india\/stockpricequote/refineries/relianceindustries/RI').decode('utf-8') # Defining the HTMLTableParser objectp = HTMLTableParser() # feeding the html contents in the# HTMLTableParser objectp.feed(xhtml) # Now finally obtaining the data of# the table requiredpprint(p.tables[1]) # converting the parsed data to# dataframeprint("\n\nPANDAS DATAFRAME\n")print(pd.DataFrame(p.tables[1]))
Output:
rohitxsh
adnanirshad158
Python web-scraping-exercises
python-modules
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 529,
"s": 54,
"text": "Scraping is a very essential skill for everyone to get data from any website. Scraping and parsing a table can be very tedious work if we use standard Beautiful soup parser to do so. Therefore, here we will be describing a library with the help of which any table can be scraped from any website easily. With this method you don’t even have to inspect element of a website, you only have to provide the URL of the website. That’s it and the work will be done within seconds."
},
{
"code": null,
"e": 570,
"s": 529,
"text": "You can use pip to install this library:"
},
{
"code": null,
"e": 608,
"s": 570,
"text": "pip install html-table-parser-python3"
},
{
"code": null,
"e": 669,
"s": 608,
"text": "Step 1: Import the necessary libraries required for the task"
},
{
"code": null,
"e": 994,
"s": 669,
"text": "# Library for opening url and creating \n# requests\nimport urllib.request\n\n# pretty-print python data structures\nfrom pprint import pprint\n\n# for parsing all the tables present \n# on the website\nfrom html_table_parser.parser import HTMLTableParser\n\n# for converting the parsed data in a\n# pandas dataframe\nimport pandas as pd"
},
{
"code": null,
"e": 1054,
"s": 994,
"text": "Step 2 : Defining a function to get contents of the website"
},
{
"code": null,
"e": 1402,
"s": 1054,
"text": "# Opens a website and read its\n# binary contents (HTTP Response Body)\ndef url_get_contents(url):\n\n # Opens a website and read its\n # binary contents (HTTP Response Body)\n\n #making request to the website\n req = urllib.request.Request(url=url)\n f = urllib.request.urlopen(req)\n\n #reading contents of the website\n return f.read()"
},
{
"code": null,
"e": 1510,
"s": 1402,
"text": "Now, our function is ready so we have to specify the url of the website from which we need to parse tables."
},
{
"code": null,
"e": 1679,
"s": 1510,
"text": "Note: Here we will be taking the example of moneycontrol.com website since it has many tables and will give you a better understanding. You can view the website here . "
},
{
"code": null,
"e": 1703,
"s": 1679,
"text": "Step 3 : Parsing tables"
},
{
"code": null,
"e": 2005,
"s": 1703,
"text": "# defining the html contents of a URL.\nxhtml = url_get_contents('Link').decode('utf-8')\n\n# Defining the HTMLTableParser object\np = HTMLTableParser()\n\n# feeding the html contents in the\n# HTMLTableParser object\np.feed(xhtml)\n\n# Now finally obtaining the data of\n# the table required\npprint(p.tables[1])"
},
{
"code": null,
"e": 2145,
"s": 2005,
"text": "Each row of the table is stored in an array. This can be converted into a pandas dataframe easily and can be used to perform any analysis. "
},
{
"code": null,
"e": 2160,
"s": 2145,
"text": "Complete Code:"
},
{
"code": null,
"e": 2168,
"s": 2160,
"text": "Python3"
},
{
"code": "# Library for opening url and creating# requestsimport urllib.request # pretty-print python data structuresfrom pprint import pprint # for parsing all the tables present# on the websitefrom html_table_parser.parser import HTMLTableParser # for converting the parsed data in a# pandas dataframeimport pandas as pd # Opens a website and read its# binary contents (HTTP Response Body)def url_get_contents(url): # Opens a website and read its # binary contents (HTTP Response Body) #making request to the website req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) #reading contents of the website return f.read() # defining the html contents of a URL.xhtml = url_get_contents('https://www.moneycontrol.com/india\\/stockpricequote/refineries/relianceindustries/RI').decode('utf-8') # Defining the HTMLTableParser objectp = HTMLTableParser() # feeding the html contents in the# HTMLTableParser objectp.feed(xhtml) # Now finally obtaining the data of# the table requiredpprint(p.tables[1]) # converting the parsed data to# dataframeprint(\"\\n\\nPANDAS DATAFRAME\\n\")print(pd.DataFrame(p.tables[1]))",
"e": 3300,
"s": 2168,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3300,
"text": "Output:"
},
{
"code": null,
"e": 3321,
"s": 3312,
"text": "rohitxsh"
},
{
"code": null,
"e": 3336,
"s": 3321,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3366,
"s": 3336,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 3381,
"s": 3366,
"text": "python-modules"
},
{
"code": null,
"e": 3394,
"s": 3381,
"text": "Web-scraping"
},
{
"code": null,
"e": 3401,
"s": 3394,
"text": "Python"
}
] |
Services in Android with Example
|
15 Sep, 2020
Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at the same time. A user-interface is not desirable for android services as it is designed to operate long-running processes without any user intervention. A service can run continuously in the background even if the application is closed or the user switches to another application. Further, application components can bind itself to service to carry out inter-process communication(IPC). There is a major difference between android services and threads, one must not be confused between the two. Thread is a feature provided by the Operating system to allow the user to perform operations in the background. While service is an android component that performs a long-running operation about which the user might not be aware of as it does not have UI.
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground Services. Users can interact with the service by the notifications provided about the ongoing task. Such as in downloading a file, the user can keep track of the progress in downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not notify the user about ongoing background tasks and users also cannot access them. The process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to bound themselves with it. Bound services perform their task as long as any application component is bound to it. More than one component is allowed to bind themselves with a service at a time. In order to bind an application component with a service bindService() method is used.
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
By following this path, a service will initiate when an application component calls the startService() method. Once initiated, the service can run continuously in the background even if the component is destroyed which was responsible for the start of the service. Two option are available to stop the execution of service:
By calling stopService() method,
The service can stop itself by using stopSelf() method.
It can be treated as a server in a client-server interface. By following this path, android application components can send requests to the service and can fetch results. A service is termed as bounded when an application component binds itself with a service by calling bindService() method. To stop the execution of this service, all the components must unbind themselves from the service by using unbindService() method.
To carry out a downloading task in the background, the startService() method will be called. Whereas to get information regarding the download progress and to pause or resume the process while the application is still in the background, the service must be bounded with a component which can perform these tasks.
A user-defined service can be created through a normal class which is extending the class Service. Further, to carry out the operations of service on applications, there are certain callback methods which are needed to be overridden. The following are some of the important methods of Android Services:
Methods
Description
The Android service calls this method when a component(eg: activity)
requests to start a service using startService(). Once the service is started,
it can be stopped explicitly using stopService() or stopSelf() methods.
This method is mandatory to implement in android service and is invoked
whenever an application component calls the bindService() method in order to
bind itself with a service. User-interface is also provided to communicate
with the service effectively by returning an IBinder object.
If the binding of service is not required then the method must return null.
The Android system invokes this method when all the clients
get disconnected from a particular service interface.
Once all clients are disconnected from the particular interface of service and
there is a need to connect the service with new clients, the system calls this method.
Whenever a service is created either using onStartCommand() or onBind(),
the android system calls this method. This method is necessary to perform
a one-time-set-up.
When a service is no longer in use, the system invokes this method
just before the service destroys as a final clean up call. Services must
implement this method in order to clean up resources like registered listeners,
threads, receivers, etc.
Playing music in the background is a very common example of services in android. From the time when a user starts the service, music play continuously in the background even if the user switches to another application. The user has to stop the service explicitly in order to pause the music. Below is the complete step-by-step implementation of this android service using a few callback methods.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need.
Click on File, then New => New Project.
Choose Empty activity
Select language as Java/Kotlin
Select the minimum SDK as per your need.
Step 2: Modify strings.xml file
All the strings which are used in the activity are listed in this file.
XML
<resources> <string name="app_name">Services_In_Android</string> <string name="heading">Services In Android</string> <string name="startButtonText">Start the Service</string> <string name="stopButtonText">Stop the Service</string></resources>
Step 3: Working with the activity_main.xml file
Open the activity_main.xml file and add 2 Buttons in it which will start and stop the service. Below is the code for designing a proper activity layout.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="1.0" tools:ignore="MissingConstraints"> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="170dp" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" /> <Button android:id="@+id/startButton" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:text="@string/startButtonText" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="#FFFFFF" android:textStyle="bold" /> <Button android:id="@+id/stopButton" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:text="@string/stopButtonText" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="#FFFFFF" android:textStyle="bold" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="80dp" app:srcCompat="@drawable/banner" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Creating the custom service class
A custom service class will be created in the same directory where the MainActivity class resides and this class will extend the Service class. The callback methods are used to initiate and destroy the services. To play music, the MediaPlayer object is used. Below is the code to carry out this task.
Java
Kotlin
import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.provider.Settings;import androidx.annotation.Nullable; public class NewService extends Service { // declaring object of MediaPlayer private MediaPlayer player; @Override // execution of service will start // on calling this method public int onStartCommand(Intent intent, int flags, int startId) { // creating a media player which // will play the audio of Default // ringtone in android device player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); // providing the boolean // value as true to play // the audio on loop player.setLooping( true ); // starting the process player.start(); // returns the status // of the program return START_STICKY; } @Override // execution of the service will // stop on calling this method public void onDestroy() { super.onDestroy(); // stopping the process player.stop(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; }}
import android.app.Serviceimport android.content.Intentimport android.media.MediaPlayerimport android.os.IBinderimport android.provider.Settings class NewService : Service() { // declaring object of MediaPlayer private lateinit var player:MediaPlayer // execution of service will start // on calling this method override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { // creating a media player which // will play the audio of Default // ringtone in android device player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI) // providing the boolean // value as true to play // the audio on loop player.setLooping(true) // starting the process player.start() // returns the status // of the program return START_STICKY } // execution of the service will // stop on calling this method override fun onDestroy() { super.onDestroy() // stopping the process player.stop() } override fun onBind(intent: Intent): IBinder? { return null }}
Step 5: Working with the MainActivity file
Now, the button objects will be declared and the process to be performed on clicking these buttons will be defined in the MainActivity class. Below is the code to implement this step.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // declaring objects of Button class private Button start, stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); // assigning ID of startButton // to the object start start = (Button) findViewById( R.id.startButton ); // assigning ID of stopButton // to the object stop stop = (Button) findViewById( R.id.stopButton ); // declaring listeners for the // buttons to make them respond // correctly according to the process start.setOnClickListener( this ); stop.setOnClickListener( this ); } public void onClick(View view) { // process to be performed // if start button is clicked if(view == start){ // starting the service startService(new Intent( this, NewService.class ) ); } // process to be performed // if stop button is clicked else if (view == stop){ // stopping the service stopService(new Intent( this, NewService.class ) ); } }}
import android.content.Intentimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), View.OnClickListener { // declaring objects of Button class private var start: Button? = null private var stop: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning ID of startButton // to the object start start = findViewById<View>(R.id.startButton) as Button // assigning ID of stopButton // to the object stop stop = findViewById<View>(R.id.stopButton) as Button // declaring listeners for the // buttons to make them respond // correctly according to the process start!!.setOnClickListener(this) stop!!.setOnClickListener(this) } override fun onClick(view: View) { // process to be performed // if start button is clicked if (view === start) { // starting the service startService(Intent(this, NewService::class.java)) } // process to be performed // if stop button is clicked else if (view === stop) { // stopping the service stopService(Intent(this, NewService::class.java)) } }}
Step 6: Modify the AndroidManifest.xml file
To implement the services successfully on any android device, it is necessary to mention the created service in the AndroidManifest.xml file. It is not possible for a service to perform its task if it is not mentioned in this file. The service name is mentioned inside the application tag.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.services_in_android"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="preloaded_fonts" android:resource="@array/preloaded_fonts" /> <!-- Mention the service name here --> <service android:name=".NewService"/> </application> </manifest>
android
Android
Java
Kotlin
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 1102,
"s": 52,
"text": "Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at the same time. A user-interface is not desirable for android services as it is designed to operate long-running processes without any user intervention. A service can run continuously in the background even if the application is closed or the user switches to another application. Further, application components can bind itself to service to carry out inter-process communication(IPC). There is a major difference between android services and threads, one must not be confused between the two. Thread is a feature provided by the Operating system to allow the user to perform operations in the background. While service is an android component that performs a long-running operation about which the user might not be aware of as it does not have UI."
},
{
"code": null,
"e": 1126,
"s": 1102,
"text": "1. Foreground Services:"
},
{
"code": null,
"e": 1439,
"s": 1126,
"text": "Services that notify the user about its ongoing operations are termed as Foreground Services. Users can interact with the service by the notifications provided about the ongoing task. Such as in downloading a file, the user can keep track of the progress in downloading and can also pause and resume the process."
},
{
"code": null,
"e": 1463,
"s": 1439,
"text": "2. Background Services:"
},
{
"code": null,
"e": 1711,
"s": 1463,
"text": "Background services do not require any user intervention. These services do not notify the user about ongoing background tasks and users also cannot access them. The process like schedule syncing of data or storing of data fall under this service."
},
{
"code": null,
"e": 1730,
"s": 1711,
"text": "3. Bound Services:"
},
{
"code": null,
"e": 2098,
"s": 1730,
"text": "This type of android service allows the components of the application like activity to bound themselves with it. Bound services perform their task as long as any application component is bound to it. More than one component is allowed to bind themselves with a service at a time. In order to bind an application component with a service bindService() method is used. "
},
{
"code": null,
"e": 2196,
"s": 2098,
"text": "In android, services have 2 possible paths to complete its life cycle namely Started and Bounded."
},
{
"code": null,
"e": 2520,
"s": 2196,
"text": "By following this path, a service will initiate when an application component calls the startService() method. Once initiated, the service can run continuously in the background even if the component is destroyed which was responsible for the start of the service. Two option are available to stop the execution of service:"
},
{
"code": null,
"e": 2553,
"s": 2520,
"text": "By calling stopService() method,"
},
{
"code": null,
"e": 2609,
"s": 2553,
"text": "The service can stop itself by using stopSelf() method."
},
{
"code": null,
"e": 3033,
"s": 2609,
"text": "It can be treated as a server in a client-server interface. By following this path, android application components can send requests to the service and can fetch results. A service is termed as bounded when an application component binds itself with a service by calling bindService() method. To stop the execution of this service, all the components must unbind themselves from the service by using unbindService() method."
},
{
"code": null,
"e": 3346,
"s": 3033,
"text": "To carry out a downloading task in the background, the startService() method will be called. Whereas to get information regarding the download progress and to pause or resume the process while the application is still in the background, the service must be bounded with a component which can perform these tasks."
},
{
"code": null,
"e": 3649,
"s": 3346,
"text": "A user-defined service can be created through a normal class which is extending the class Service. Further, to carry out the operations of service on applications, there are certain callback methods which are needed to be overridden. The following are some of the important methods of Android Services:"
},
{
"code": null,
"e": 3657,
"s": 3649,
"text": "Methods"
},
{
"code": null,
"e": 3669,
"s": 3657,
"text": "Description"
},
{
"code": null,
"e": 3739,
"s": 3669,
"text": "The Android service calls this method when a component(eg: activity) "
},
{
"code": null,
"e": 3818,
"s": 3739,
"text": "requests to start a service using startService(). Once the service is started,"
},
{
"code": null,
"e": 3890,
"s": 3818,
"text": "it can be stopped explicitly using stopService() or stopSelf() methods."
},
{
"code": null,
"e": 3963,
"s": 3890,
"text": "This method is mandatory to implement in android service and is invoked "
},
{
"code": null,
"e": 4040,
"s": 3963,
"text": "whenever an application component calls the bindService() method in order to"
},
{
"code": null,
"e": 4116,
"s": 4040,
"text": "bind itself with a service. User-interface is also provided to communicate "
},
{
"code": null,
"e": 4178,
"s": 4116,
"text": "with the service effectively by returning an IBinder object. "
},
{
"code": null,
"e": 4254,
"s": 4178,
"text": "If the binding of service is not required then the method must return null."
},
{
"code": null,
"e": 4315,
"s": 4254,
"text": "The Android system invokes this method when all the clients "
},
{
"code": null,
"e": 4369,
"s": 4315,
"text": "get disconnected from a particular service interface."
},
{
"code": null,
"e": 4448,
"s": 4369,
"text": "Once all clients are disconnected from the particular interface of service and"
},
{
"code": null,
"e": 4535,
"s": 4448,
"text": "there is a need to connect the service with new clients, the system calls this method."
},
{
"code": null,
"e": 4608,
"s": 4535,
"text": "Whenever a service is created either using onStartCommand() or onBind(),"
},
{
"code": null,
"e": 4683,
"s": 4608,
"text": "the android system calls this method. This method is necessary to perform "
},
{
"code": null,
"e": 4702,
"s": 4683,
"text": "a one-time-set-up."
},
{
"code": null,
"e": 4769,
"s": 4702,
"text": "When a service is no longer in use, the system invokes this method"
},
{
"code": null,
"e": 4843,
"s": 4769,
"text": " just before the service destroys as a final clean up call. Services must"
},
{
"code": null,
"e": 4924,
"s": 4843,
"text": " implement this method in order to clean up resources like registered listeners,"
},
{
"code": null,
"e": 4950,
"s": 4924,
"text": " threads, receivers, etc."
},
{
"code": null,
"e": 5346,
"s": 4950,
"text": "Playing music in the background is a very common example of services in android. From the time when a user starts the service, music play continuously in the background even if the user switches to another application. The user has to stop the service explicitly in order to pause the music. Below is the complete step-by-step implementation of this android service using a few callback methods."
},
{
"code": null,
"e": 5412,
"s": 5346,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 5441,
"s": 5412,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 5572,
"s": 5441,
"text": "Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need."
},
{
"code": null,
"e": 5612,
"s": 5572,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 5634,
"s": 5612,
"text": "Choose Empty activity"
},
{
"code": null,
"e": 5665,
"s": 5634,
"text": "Select language as Java/Kotlin"
},
{
"code": null,
"e": 5706,
"s": 5665,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 5738,
"s": 5706,
"text": "Step 2: Modify strings.xml file"
},
{
"code": null,
"e": 5810,
"s": 5738,
"text": "All the strings which are used in the activity are listed in this file."
},
{
"code": null,
"e": 5814,
"s": 5810,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">Services_In_Android</string> <string name=\"heading\">Services In Android</string> <string name=\"startButtonText\">Start the Service</string> <string name=\"stopButtonText\">Stop the Service</string></resources>",
"e": 6069,
"s": 5814,
"text": null
},
{
"code": null,
"e": 6117,
"s": 6069,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 6270,
"s": 6117,
"text": "Open the activity_main.xml file and add 2 Buttons in it which will start and stop the service. Below is the code for designing a proper activity layout."
},
{
"code": null,
"e": 6274,
"s": 6270,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:orientation=\"vertical\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"1.0\" tools:ignore=\"MissingConstraints\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"170dp\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/startButton\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/startButtonText\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Display1\" android:textColor=\"#FFFFFF\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/stopButton\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/stopButtonText\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Display1\" android:textColor=\"#FFFFFF\" android:textStyle=\"bold\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"80dp\" app:srcCompat=\"@drawable/banner\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 9377,
"s": 6274,
"text": null
},
{
"code": null,
"e": 9419,
"s": 9377,
"text": "Step 4: Creating the custom service class"
},
{
"code": null,
"e": 9720,
"s": 9419,
"text": "A custom service class will be created in the same directory where the MainActivity class resides and this class will extend the Service class. The callback methods are used to initiate and destroy the services. To play music, the MediaPlayer object is used. Below is the code to carry out this task."
},
{
"code": null,
"e": 9725,
"s": 9720,
"text": "Java"
},
{
"code": null,
"e": 9732,
"s": 9725,
"text": "Kotlin"
},
{
"code": "import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.provider.Settings;import androidx.annotation.Nullable; public class NewService extends Service { // declaring object of MediaPlayer private MediaPlayer player; @Override // execution of service will start // on calling this method public int onStartCommand(Intent intent, int flags, int startId) { // creating a media player which // will play the audio of Default // ringtone in android device player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); // providing the boolean // value as true to play // the audio on loop player.setLooping( true ); // starting the process player.start(); // returns the status // of the program return START_STICKY; } @Override // execution of the service will // stop on calling this method public void onDestroy() { super.onDestroy(); // stopping the process player.stop(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; }}",
"e": 10959,
"s": 9732,
"text": null
},
{
"code": "import android.app.Serviceimport android.content.Intentimport android.media.MediaPlayerimport android.os.IBinderimport android.provider.Settings class NewService : Service() { // declaring object of MediaPlayer private lateinit var player:MediaPlayer // execution of service will start // on calling this method override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { // creating a media player which // will play the audio of Default // ringtone in android device player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI) // providing the boolean // value as true to play // the audio on loop player.setLooping(true) // starting the process player.start() // returns the status // of the program return START_STICKY } // execution of the service will // stop on calling this method override fun onDestroy() { super.onDestroy() // stopping the process player.stop() } override fun onBind(intent: Intent): IBinder? { return null }}",
"e": 12099,
"s": 10959,
"text": null
},
{
"code": null,
"e": 12142,
"s": 12099,
"text": "Step 5: Working with the MainActivity file"
},
{
"code": null,
"e": 12326,
"s": 12142,
"text": "Now, the button objects will be declared and the process to be performed on clicking these buttons will be defined in the MainActivity class. Below is the code to implement this step."
},
{
"code": null,
"e": 12331,
"s": 12326,
"text": "Java"
},
{
"code": null,
"e": 12338,
"s": 12331,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // declaring objects of Button class private Button start, stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); // assigning ID of startButton // to the object start start = (Button) findViewById( R.id.startButton ); // assigning ID of stopButton // to the object stop stop = (Button) findViewById( R.id.stopButton ); // declaring listeners for the // buttons to make them respond // correctly according to the process start.setOnClickListener( this ); stop.setOnClickListener( this ); } public void onClick(View view) { // process to be performed // if start button is clicked if(view == start){ // starting the service startService(new Intent( this, NewService.class ) ); } // process to be performed // if stop button is clicked else if (view == stop){ // stopping the service stopService(new Intent( this, NewService.class ) ); } }}",
"e": 13750,
"s": 12338,
"text": null
},
{
"code": "import android.content.Intentimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), View.OnClickListener { // declaring objects of Button class private var start: Button? = null private var stop: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning ID of startButton // to the object start start = findViewById<View>(R.id.startButton) as Button // assigning ID of stopButton // to the object stop stop = findViewById<View>(R.id.stopButton) as Button // declaring listeners for the // buttons to make them respond // correctly according to the process start!!.setOnClickListener(this) stop!!.setOnClickListener(this) } override fun onClick(view: View) { // process to be performed // if start button is clicked if (view === start) { // starting the service startService(Intent(this, NewService::class.java)) } // process to be performed // if stop button is clicked else if (view === stop) { // stopping the service stopService(Intent(this, NewService::class.java)) } }}",
"e": 15166,
"s": 13750,
"text": null
},
{
"code": null,
"e": 15210,
"s": 15166,
"text": "Step 6: Modify the AndroidManifest.xml file"
},
{
"code": null,
"e": 15500,
"s": 15210,
"text": "To implement the services successfully on any android device, it is necessary to mention the created service in the AndroidManifest.xml file. It is not possible for a service to perform its task if it is not mentioned in this file. The service name is mentioned inside the application tag."
},
{
"code": null,
"e": 15504,
"s": 15500,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.services_in_android\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <meta-data android:name=\"preloaded_fonts\" android:resource=\"@array/preloaded_fonts\" /> <!-- Mention the service name here --> <service android:name=\".NewService\"/> </application> </manifest>",
"e": 16437,
"s": 15504,
"text": null
},
{
"code": null,
"e": 16445,
"s": 16437,
"text": "android"
},
{
"code": null,
"e": 16453,
"s": 16445,
"text": "Android"
},
{
"code": null,
"e": 16458,
"s": 16453,
"text": "Java"
},
{
"code": null,
"e": 16465,
"s": 16458,
"text": "Kotlin"
},
{
"code": null,
"e": 16470,
"s": 16465,
"text": "Java"
},
{
"code": null,
"e": 16478,
"s": 16470,
"text": "Android"
},
{
"code": null,
"e": 16576,
"s": 16478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16645,
"s": 16576,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 16676,
"s": 16645,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 16708,
"s": 16676,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 16757,
"s": 16708,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 16786,
"s": 16757,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 16801,
"s": 16786,
"text": "Arrays in Java"
},
{
"code": null,
"e": 16845,
"s": 16801,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 16881,
"s": 16845,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 16932,
"s": 16881,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
CloudFail - Unmask/Bypass CloudFlare Security in Kali Linux - GeeksforGeeks
|
20 Apr, 2021
CloudFail is a free and open-source tool available on GitHub. CloudFail is a tactical reconnaissance tool. There are some websites that are protected by Cloudflare security. It’s hard to find information about such websites but now impossible. By using CloudFail tool we can get enough information about the target domain which is protected by Cloudflare security. CloudFail is a tool that helps to unmask CloudFlare by providing the actual IP of the server. According to the developers, CloudFail has 3 phases.
Features of CloudFail tool :
CloudFail check in Crimeflare.com to perform tactical reconnaissance.
CloudFail check in DNSDumpster.com to lookup for IP-address.
CloudFail Performs a brute force with more than 2500 subdomains for reconnaissance.
Step 1. Open your Kali Linux and move to the Desktop directory using the following command.
command : cd Desktop
Step 2. Create a new directory here and name it cloudfail.
command : mkdir cloudfail
Step 3. Move to the directory that you have created using the following command.
command : cd cloudfail
Step 4. Now you are in the cloudfail directory. You have to clone the tool here in this directory using the following command.
command : git clone https://github.com/m0rtem/CloudFail
Step 5. The tool has been downloaded in the cloudfail directory. To list out the content of the tool use following command.
command : ls
Step 6. You can see that a new directory is found after listing out the contents. Now move to this directory using the following command.
command : cd CloudFail
Step 7. Now you are under CloudFail directory. You have to list out the contents of the tool using the following command.
command : ls
Step 8. Give permission to the python files of the tools using the following command.
command : chmod +x cloudfail.py
Step 9. Now you have to install all the requirements that are used by the tool using the following command.
command : pip3 install -r requirements.txt
Step 10. All the requirements have been downloaded into the tool. Now, this is the time to run the tool. To run the tool use the following command. First, we will check for help by the tool.
command : python3 cloudfail.py --help
Step 11. The tool is running and now uses the following command to update dependencies of the CloudFail tool.
command : python3 cloudfail.py -u
All the dependencies has been updated. Now you can set the target and run the tool. Now lets see some examples how you can bypass cloudflare security.
Example. By using CloudFail tool scan techchip.com
command : python3 cloudfail.py -t techchip.com
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Named Pipe or FIFO with example C program
Thread functions in C/C++
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
Introduction to Linux Shell and Shell Scripting
Linux system call in Detail
chown command in Linux with Examples
Looping Statements | Shell Script
mv command in Linux with examples
PING Command in Linux with examples
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 24838,
"s": 24326,
"text": "CloudFail is a free and open-source tool available on GitHub. CloudFail is a tactical reconnaissance tool. There are some websites that are protected by Cloudflare security. It’s hard to find information about such websites but now impossible. By using CloudFail tool we can get enough information about the target domain which is protected by Cloudflare security. CloudFail is a tool that helps to unmask CloudFlare by providing the actual IP of the server. According to the developers, CloudFail has 3 phases."
},
{
"code": null,
"e": 24867,
"s": 24838,
"text": "Features of CloudFail tool :"
},
{
"code": null,
"e": 24937,
"s": 24867,
"text": "CloudFail check in Crimeflare.com to perform tactical reconnaissance."
},
{
"code": null,
"e": 24998,
"s": 24937,
"text": "CloudFail check in DNSDumpster.com to lookup for IP-address."
},
{
"code": null,
"e": 25082,
"s": 24998,
"text": "CloudFail Performs a brute force with more than 2500 subdomains for reconnaissance."
},
{
"code": null,
"e": 25174,
"s": 25082,
"text": "Step 1. Open your Kali Linux and move to the Desktop directory using the following command."
},
{
"code": null,
"e": 25195,
"s": 25174,
"text": "command : cd Desktop"
},
{
"code": null,
"e": 25256,
"s": 25195,
"text": "Step 2. Create a new directory here and name it cloudfail. "
},
{
"code": null,
"e": 25282,
"s": 25256,
"text": "command : mkdir cloudfail"
},
{
"code": null,
"e": 25363,
"s": 25282,
"text": "Step 3. Move to the directory that you have created using the following command."
},
{
"code": null,
"e": 25387,
"s": 25363,
"text": "command : cd cloudfail "
},
{
"code": null,
"e": 25514,
"s": 25387,
"text": "Step 4. Now you are in the cloudfail directory. You have to clone the tool here in this directory using the following command."
},
{
"code": null,
"e": 25570,
"s": 25514,
"text": "command : git clone https://github.com/m0rtem/CloudFail"
},
{
"code": null,
"e": 25694,
"s": 25570,
"text": "Step 5. The tool has been downloaded in the cloudfail directory. To list out the content of the tool use following command."
},
{
"code": null,
"e": 25707,
"s": 25694,
"text": "command : ls"
},
{
"code": null,
"e": 25845,
"s": 25707,
"text": "Step 6. You can see that a new directory is found after listing out the contents. Now move to this directory using the following command."
},
{
"code": null,
"e": 25868,
"s": 25845,
"text": "command : cd CloudFail"
},
{
"code": null,
"e": 25990,
"s": 25868,
"text": "Step 7. Now you are under CloudFail directory. You have to list out the contents of the tool using the following command."
},
{
"code": null,
"e": 26003,
"s": 25990,
"text": "command : ls"
},
{
"code": null,
"e": 26089,
"s": 26003,
"text": "Step 8. Give permission to the python files of the tools using the following command."
},
{
"code": null,
"e": 26121,
"s": 26089,
"text": "command : chmod +x cloudfail.py"
},
{
"code": null,
"e": 26229,
"s": 26121,
"text": "Step 9. Now you have to install all the requirements that are used by the tool using the following command."
},
{
"code": null,
"e": 26272,
"s": 26229,
"text": "command : pip3 install -r requirements.txt"
},
{
"code": null,
"e": 26464,
"s": 26272,
"text": "Step 10. All the requirements have been downloaded into the tool. Now, this is the time to run the tool. To run the tool use the following command. First, we will check for help by the tool. "
},
{
"code": null,
"e": 26502,
"s": 26464,
"text": "command : python3 cloudfail.py --help"
},
{
"code": null,
"e": 26612,
"s": 26502,
"text": "Step 11. The tool is running and now uses the following command to update dependencies of the CloudFail tool."
},
{
"code": null,
"e": 26646,
"s": 26612,
"text": "command : python3 cloudfail.py -u"
},
{
"code": null,
"e": 26797,
"s": 26646,
"text": "All the dependencies has been updated. Now you can set the target and run the tool. Now lets see some examples how you can bypass cloudflare security."
},
{
"code": null,
"e": 26848,
"s": 26797,
"text": "Example. By using CloudFail tool scan techchip.com"
},
{
"code": null,
"e": 26896,
"s": 26848,
"text": "command : python3 cloudfail.py -t techchip.com "
},
{
"code": null,
"e": 26911,
"s": 26896,
"text": "Cyber-security"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26934,
"s": 26922,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26945,
"s": 26934,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27043,
"s": 26945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27052,
"s": 27043,
"text": "Comments"
},
{
"code": null,
"e": 27065,
"s": 27052,
"text": "Old Comments"
},
{
"code": null,
"e": 27107,
"s": 27065,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27133,
"s": 27107,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27162,
"s": 27133,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27202,
"s": 27162,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 27250,
"s": 27202,
"text": "Introduction to Linux Shell and Shell Scripting"
},
{
"code": null,
"e": 27278,
"s": 27250,
"text": "Linux system call in Detail"
},
{
"code": null,
"e": 27315,
"s": 27278,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27349,
"s": 27315,
"text": "Looping Statements | Shell Script"
},
{
"code": null,
"e": 27383,
"s": 27349,
"text": "mv command in Linux with examples"
}
] |
Exporting Pandas DataFrame to JSON File - GeeksforGeeks
|
31 Aug, 2021
Let us see how to export a Pandas DataFrame as a JSON file. To perform this task we will be using the DataFrame.to_json() and the pandas.read_json() function.
Example 1 :
Python3
# importing the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], index =['row 1', 'row 2', 'row3'], columns =['col 1', 'col 2', 'col3']) # storing the data in JSON formatdf.to_json('file.json', orient = 'split', compression = 'infer', index = 'true') # reading the JSON filedf = pd.read_json('file.json', orient ='split', compression = 'infer') # displaying the DataFrameprint(df)
Output :
We can see that the DataFrame has been exported as a JSON file.
Example 2 :
Python3
# importing the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame(data = [['15135', 'Alex', '25 / 4/2014'], ['23515', 'Bob', '26 / 8/2018'], ['31313', 'Martha', '18 / 1/2019'], ['55665', 'Alen', '5 / 5/2020'], ['63513', 'Maria', '9 / 12 / 2020']], columns =['ID', 'NAME', 'DATE OF JOINING']) # storing data in JSON formatdf.to_json('file1.json', orient = 'split', compression = 'infer') # reading the JSON filedf = pd.read_json('file1.json', orient ='split', compression = 'infer')print(df)
Output :
We can see that this DataFrame has also been exported as a JSON file.
sooda367
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
|
[
{
"code": null,
"e": 23921,
"s": 23893,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 24080,
"s": 23921,
"text": "Let us see how to export a Pandas DataFrame as a JSON file. To perform this task we will be using the DataFrame.to_json() and the pandas.read_json() function."
},
{
"code": null,
"e": 24092,
"s": 24080,
"text": "Example 1 :"
},
{
"code": null,
"e": 24100,
"s": 24092,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], index =['row 1', 'row 2', 'row3'], columns =['col 1', 'col 2', 'col3']) # storing the data in JSON formatdf.to_json('file.json', orient = 'split', compression = 'infer', index = 'true') # reading the JSON filedf = pd.read_json('file.json', orient ='split', compression = 'infer') # displaying the DataFrameprint(df)",
"e": 24585,
"s": 24100,
"text": null
},
{
"code": null,
"e": 24595,
"s": 24585,
"text": "Output : "
},
{
"code": null,
"e": 24659,
"s": 24595,
"text": "We can see that the DataFrame has been exported as a JSON file."
},
{
"code": null,
"e": 24671,
"s": 24659,
"text": "Example 2 :"
},
{
"code": null,
"e": 24679,
"s": 24671,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame(data = [['15135', 'Alex', '25 / 4/2014'], ['23515', 'Bob', '26 / 8/2018'], ['31313', 'Martha', '18 / 1/2019'], ['55665', 'Alen', '5 / 5/2020'], ['63513', 'Maria', '9 / 12 / 2020']], columns =['ID', 'NAME', 'DATE OF JOINING']) # storing data in JSON formatdf.to_json('file1.json', orient = 'split', compression = 'infer') # reading the JSON filedf = pd.read_json('file1.json', orient ='split', compression = 'infer')print(df)",
"e": 25276,
"s": 24679,
"text": null
},
{
"code": null,
"e": 25286,
"s": 25276,
"text": "Output : "
},
{
"code": null,
"e": 25356,
"s": 25286,
"text": "We can see that this DataFrame has also been exported as a JSON file."
},
{
"code": null,
"e": 25367,
"s": 25358,
"text": "sooda367"
},
{
"code": null,
"e": 25391,
"s": 25367,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 25414,
"s": 25391,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 25428,
"s": 25414,
"text": "Python-pandas"
},
{
"code": null,
"e": 25435,
"s": 25428,
"text": "Python"
},
{
"code": null,
"e": 25533,
"s": 25435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25542,
"s": 25533,
"text": "Comments"
},
{
"code": null,
"e": 25555,
"s": 25542,
"text": "Old Comments"
},
{
"code": null,
"e": 25592,
"s": 25555,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25628,
"s": 25592,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25646,
"s": 25628,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25669,
"s": 25646,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25691,
"s": 25669,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25730,
"s": 25691,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25763,
"s": 25730,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 25812,
"s": 25763,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 25845,
"s": 25812,
"text": "Graph Plotting in Python | Set 1"
}
] |
5 tips for data aggregation in pandas | by Zolzaya Luvsandorj | Towards Data Science
|
When doing data analysis, being able to skillfully aggregate data plays an important role. Pandas provides many useful methods, some of which are perhaps less popular than others. Moreover, even for the well-known methods, we could increase its utility by tweaking its arguments further or complement it with other methods. With these considerations, here are 5 tips on data aggregation in pandas in case you haven’t across these before:
In this post, I will demonstrate how they are useful with examples. I also hope these tips will help you write a clear, concise and readable code.
I assume the reader (👀 yes, you!) has:◼️ access to and is familiar with Python including installing packages, defining functions and other basic tasks◼️ working knowledge using pandas including basic data manipulation.
Make sure you have both pandas and seaborn installed if you haven’t already.
If you are new to Python, this is a good place to get started. If you haven’t used pandas before, this is a good resource to check out.
I have used and tested the scripts in Python 3.7.1 in Jupyter Notebook.
We will use seaborn’s tips dataset to illustrate my tips.
# Import packagesimport pandas as pdfrom seaborn import load_dataset# Import data df = load_dataset('tips').rename(columns={'sex': 'gender'})df
Details about this dataset including data dictionary can be found here (this source is actually for R, but it appears to be referring to the same underlying dataset). I have quoted their data description below for quick access:
“One waiter recorded information about each tip he received over a period of a few months working in one restaurant.”
You are probably already familiar with this series function: value_counts(). Running df['day'].value_counts() will give us the counts of unique values in day variable. If we specify normalize=True inside the method, it will give us percentages instead. This is useful for a single variable, but sometimes we need to see counts by multiple variables. For instance, if we wanted to get counts by day and time, one way to get this is to use groupby() + size() + unstack():
df.groupby(['time', 'day']).size().unstack()
Another more flexible way is to use crosstab():
pd.crosstab(df['time'], df['day'])
Using crosstab() has some advantages. Firstly, it’s easy to get row and column subtotals - we just add margins=True:
pd.crosstab(df['time'], df['day'], margins=True)
Isn’t it awesome? Secondly, we can easily get percentages instead of counts by tweaking the normalize argument:
pd.crosstab(df['time'], df['day'], margins=True, normalize=True)
In this example, we got table percentages by setting normalize=True. This is equivalent to setting it to normalize='all'. For row percentages, we use normalize='index' and normalize='columns' for column percentages. We could further extend the variable sets for columns and rows too:
pd.crosstab([df['time'], df['gender']], [df['day'], df['smoker']], margins=True)
After discovering crosstab(), I now use it regularly when using pandas.
You may already know about both groupby() and describe(). But have you used them together? By using these two together, we can check the summary statistics of a numeric variable by unique values in a categorical column with just one line like this:
df.groupby('day')['tip'].describe()
We can see how the summary statistics of tip compare across days.
In this post, we will use agg(), the alias of aggregate(). However, both can be used interchangeably.
You may probably know the basic aggregation syntax like this one:
df.groupby('day')[['tip']].mean()
Here are some alternative ways to get the same output with agg():
df.groupby('day')[['tip']].agg('mean')df.groupby('day').agg({'tip': 'mean'})
In this simple example, there isn’t a clear advantage why one should use agg() over the first alternative. However, using agg() gives us more flexibility when we want to look at output of multiple aggregate functions. For instance, we can get both mean and standard deviation at one go by either passing a list or a dictionary to agg().
df.groupby('day')[['tip']].agg(['mean', 'std']) # listdf.groupby(['day']).agg({'tip': ['mean', 'std']}) # dictionary
If we ever had to rename the output columns, instead of doing this:
df.groupby('day')[['tip']].agg(['mean', 'std']).rename(columns={'mean': 'avg', 'std': 'sd'})
we could do either of these more succinctly:
df.groupby(['day'])[['tip']].agg([('avg', 'mean'), ('sd', 'std')])df.groupby(['day']).agg({'tip': [('avg', 'mean'), ('sd', 'std')]})
Using either list or dictionary so far has worked equally. However, using list is more concise if we want to inspect a same set of summary statistics for multiple variables.
df.groupby('day')[['tip', 'size']].agg(['mean', 'std'])
On the other hand, sometimes using dictionary is the way to go. With dictionary, we can specify different sets of aggregate functions for each variable:
df.groupby(['day']).agg({'tip': ['mean', 'std'], 'size': ['median']})
There are many aggregate functions to use:
◼️ Frequency / Counts: size() , count()◼️ Central tendency: mean() , median()◼️ Variance: std(), var()◼️ Others: min(), max(), ️sum(), prod(), quantile() and many more.
On top of these, we could use any Series or DataFrame method inside agg(). For instance, to see the highest two tips by day, we use:
df.groupby('day')['tip'].nlargest(2)
We can see that some of the biggest tips were on Saturday. 💰
In addition, we could use lambda functions too:
df.groupby(['day']).agg({'tip': [('range', lambda x: x.max() - x.min()), ('IQR', lambda x: x.quantile(.75) - x.quantile(.25))]})
This extends the possibility of what we could do! 😎
Let’s say we needed to get the mean tip by 2 variables. A common approach is to use groupby():
df.groupby(['time', 'day'])['tip'].mean().unstack()
But a slightly better way to do this is to use pivot_table():
df.pivot_table('tip', 'time', 'day')
Here, we didn’t specify the arguments because we have provided the values to the method in the correct order. Here is another version of the same code where all arguments are explicitly specified:
df.pivot_table(values='tip', index='time', columns='day')
This version is probably more readable. I think readability won’t be compromised if we omit the first argument name to be slightly more concise:
df.pivot_table('tip', index='time', columns='day')
We will keep this format moving forward.
By default, pivot_table() gives us mean values. However, we can easily change to our preferred function such as sum() by specifying it to the aggfunc argument:
df.pivot_table('tip', index='time', columns='day', aggfunc='sum')
Similar to crosstab(), it's also easy to get subtotals with pivot_table().
df.pivot_table('tip', index='time', columns='day', aggfunc='sum', margins=True)
We can also pass dictionary to aggfunc to customise the aggregate functions for each variable passed to values argument. Another useful argument is fill_value where we specify what values we want to see if the output is missing. Let’s see an example exemplifying these points:
df.pivot_table(['tip', 'size'], index=['time', 'smoker'], columns='day', fill_value=0, margins=True, aggfunc={'tip': 'sum', 'size': 'max'})
With pivot_table(), you know exactly which variables would be in rows and columns and no reshaping the data is necessary.
This tip is useful when we want to append the group aggregate measures back to the ungrouped data. Here is an example to clarify this:
df['avg_tip_by_gender'] = df.groupby('gender')['tip'].transform('mean')df.head()
In this example, newly created variable avg_tip_by_gender shows average tip by gender. In other words, mean tip by gender from below have been added back to the ungrouped data.
df.groupby('gender')['tip'].agg(['mean', 'std'])
Now, let’s take a slightly more advanced example:
df['n_sd_from_gender_avg_tip'] = df.groupby('gender')['tip'].transform(lambda x: (x-x.mean())/x.std())df.head()
Here, using lambda function, we did 3 things for variable tip:
x.mean(): Find mean by gender.x-x.mean(): Find the distance from mean by gender.(x-x.mean())/x.std(): Find the distance in units of standard deviation.
Let’s take the first record (index=0) as an example and round up the numbers to 2 decimal places for simplicity: x=1.01, x.mean()=2.83, x.std()= 1.16
Then, n_sd_from_gender_avg_tip = (1.01 - 2.83)/ 1.16 = -1.57
That’s what we find in the first row of n_sd_from_gender_avg_tip. For this record, the tip amount was about 1.57 standard deviations lower than the average tip among female customers.
Voila❕ These were my current top data aggregation tips in pandas!
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading my post. Hope you find my tips useful ✂️. If you are interested to learn more about pandas, here are links to my other posts:◼️️ Writing 5 common SQL queries in pandas◼️️ 5 tips for pandas users◼️️ How to transform variables in a pandas DataFrame
Bye for now 🏃💨
|
[
{
"code": null,
"e": 610,
"s": 172,
"text": "When doing data analysis, being able to skillfully aggregate data plays an important role. Pandas provides many useful methods, some of which are perhaps less popular than others. Moreover, even for the well-known methods, we could increase its utility by tweaking its arguments further or complement it with other methods. With these considerations, here are 5 tips on data aggregation in pandas in case you haven’t across these before:"
},
{
"code": null,
"e": 757,
"s": 610,
"text": "In this post, I will demonstrate how they are useful with examples. I also hope these tips will help you write a clear, concise and readable code."
},
{
"code": null,
"e": 976,
"s": 757,
"text": "I assume the reader (👀 yes, you!) has:◼️ access to and is familiar with Python including installing packages, defining functions and other basic tasks◼️ working knowledge using pandas including basic data manipulation."
},
{
"code": null,
"e": 1053,
"s": 976,
"text": "Make sure you have both pandas and seaborn installed if you haven’t already."
},
{
"code": null,
"e": 1189,
"s": 1053,
"text": "If you are new to Python, this is a good place to get started. If you haven’t used pandas before, this is a good resource to check out."
},
{
"code": null,
"e": 1261,
"s": 1189,
"text": "I have used and tested the scripts in Python 3.7.1 in Jupyter Notebook."
},
{
"code": null,
"e": 1319,
"s": 1261,
"text": "We will use seaborn’s tips dataset to illustrate my tips."
},
{
"code": null,
"e": 1463,
"s": 1319,
"text": "# Import packagesimport pandas as pdfrom seaborn import load_dataset# Import data df = load_dataset('tips').rename(columns={'sex': 'gender'})df"
},
{
"code": null,
"e": 1691,
"s": 1463,
"text": "Details about this dataset including data dictionary can be found here (this source is actually for R, but it appears to be referring to the same underlying dataset). I have quoted their data description below for quick access:"
},
{
"code": null,
"e": 1809,
"s": 1691,
"text": "“One waiter recorded information about each tip he received over a period of a few months working in one restaurant.”"
},
{
"code": null,
"e": 2279,
"s": 1809,
"text": "You are probably already familiar with this series function: value_counts(). Running df['day'].value_counts() will give us the counts of unique values in day variable. If we specify normalize=True inside the method, it will give us percentages instead. This is useful for a single variable, but sometimes we need to see counts by multiple variables. For instance, if we wanted to get counts by day and time, one way to get this is to use groupby() + size() + unstack():"
},
{
"code": null,
"e": 2324,
"s": 2279,
"text": "df.groupby(['time', 'day']).size().unstack()"
},
{
"code": null,
"e": 2372,
"s": 2324,
"text": "Another more flexible way is to use crosstab():"
},
{
"code": null,
"e": 2407,
"s": 2372,
"text": "pd.crosstab(df['time'], df['day'])"
},
{
"code": null,
"e": 2524,
"s": 2407,
"text": "Using crosstab() has some advantages. Firstly, it’s easy to get row and column subtotals - we just add margins=True:"
},
{
"code": null,
"e": 2573,
"s": 2524,
"text": "pd.crosstab(df['time'], df['day'], margins=True)"
},
{
"code": null,
"e": 2685,
"s": 2573,
"text": "Isn’t it awesome? Secondly, we can easily get percentages instead of counts by tweaking the normalize argument:"
},
{
"code": null,
"e": 2750,
"s": 2685,
"text": "pd.crosstab(df['time'], df['day'], margins=True, normalize=True)"
},
{
"code": null,
"e": 3034,
"s": 2750,
"text": "In this example, we got table percentages by setting normalize=True. This is equivalent to setting it to normalize='all'. For row percentages, we use normalize='index' and normalize='columns' for column percentages. We could further extend the variable sets for columns and rows too:"
},
{
"code": null,
"e": 3127,
"s": 3034,
"text": "pd.crosstab([df['time'], df['gender']], [df['day'], df['smoker']], margins=True)"
},
{
"code": null,
"e": 3199,
"s": 3127,
"text": "After discovering crosstab(), I now use it regularly when using pandas."
},
{
"code": null,
"e": 3448,
"s": 3199,
"text": "You may already know about both groupby() and describe(). But have you used them together? By using these two together, we can check the summary statistics of a numeric variable by unique values in a categorical column with just one line like this:"
},
{
"code": null,
"e": 3484,
"s": 3448,
"text": "df.groupby('day')['tip'].describe()"
},
{
"code": null,
"e": 3550,
"s": 3484,
"text": "We can see how the summary statistics of tip compare across days."
},
{
"code": null,
"e": 3652,
"s": 3550,
"text": "In this post, we will use agg(), the alias of aggregate(). However, both can be used interchangeably."
},
{
"code": null,
"e": 3718,
"s": 3652,
"text": "You may probably know the basic aggregation syntax like this one:"
},
{
"code": null,
"e": 3752,
"s": 3718,
"text": "df.groupby('day')[['tip']].mean()"
},
{
"code": null,
"e": 3818,
"s": 3752,
"text": "Here are some alternative ways to get the same output with agg():"
},
{
"code": null,
"e": 3895,
"s": 3818,
"text": "df.groupby('day')[['tip']].agg('mean')df.groupby('day').agg({'tip': 'mean'})"
},
{
"code": null,
"e": 4232,
"s": 3895,
"text": "In this simple example, there isn’t a clear advantage why one should use agg() over the first alternative. However, using agg() gives us more flexibility when we want to look at output of multiple aggregate functions. For instance, we can get both mean and standard deviation at one go by either passing a list or a dictionary to agg()."
},
{
"code": null,
"e": 4349,
"s": 4232,
"text": "df.groupby('day')[['tip']].agg(['mean', 'std']) # listdf.groupby(['day']).agg({'tip': ['mean', 'std']}) # dictionary"
},
{
"code": null,
"e": 4417,
"s": 4349,
"text": "If we ever had to rename the output columns, instead of doing this:"
},
{
"code": null,
"e": 4510,
"s": 4417,
"text": "df.groupby('day')[['tip']].agg(['mean', 'std']).rename(columns={'mean': 'avg', 'std': 'sd'})"
},
{
"code": null,
"e": 4555,
"s": 4510,
"text": "we could do either of these more succinctly:"
},
{
"code": null,
"e": 4688,
"s": 4555,
"text": "df.groupby(['day'])[['tip']].agg([('avg', 'mean'), ('sd', 'std')])df.groupby(['day']).agg({'tip': [('avg', 'mean'), ('sd', 'std')]})"
},
{
"code": null,
"e": 4862,
"s": 4688,
"text": "Using either list or dictionary so far has worked equally. However, using list is more concise if we want to inspect a same set of summary statistics for multiple variables."
},
{
"code": null,
"e": 4918,
"s": 4862,
"text": "df.groupby('day')[['tip', 'size']].agg(['mean', 'std'])"
},
{
"code": null,
"e": 5071,
"s": 4918,
"text": "On the other hand, sometimes using dictionary is the way to go. With dictionary, we can specify different sets of aggregate functions for each variable:"
},
{
"code": null,
"e": 5166,
"s": 5071,
"text": "df.groupby(['day']).agg({'tip': ['mean', 'std'], 'size': ['median']})"
},
{
"code": null,
"e": 5209,
"s": 5166,
"text": "There are many aggregate functions to use:"
},
{
"code": null,
"e": 5378,
"s": 5209,
"text": "◼️ Frequency / Counts: size() , count()◼️ Central tendency: mean() , median()◼️ Variance: std(), var()◼️ Others: min(), max(), ️sum(), prod(), quantile() and many more."
},
{
"code": null,
"e": 5511,
"s": 5378,
"text": "On top of these, we could use any Series or DataFrame method inside agg(). For instance, to see the highest two tips by day, we use:"
},
{
"code": null,
"e": 5548,
"s": 5511,
"text": "df.groupby('day')['tip'].nlargest(2)"
},
{
"code": null,
"e": 5609,
"s": 5548,
"text": "We can see that some of the biggest tips were on Saturday. 💰"
},
{
"code": null,
"e": 5657,
"s": 5609,
"text": "In addition, we could use lambda functions too:"
},
{
"code": null,
"e": 5819,
"s": 5657,
"text": "df.groupby(['day']).agg({'tip': [('range', lambda x: x.max() - x.min()), ('IQR', lambda x: x.quantile(.75) - x.quantile(.25))]})"
},
{
"code": null,
"e": 5871,
"s": 5819,
"text": "This extends the possibility of what we could do! 😎"
},
{
"code": null,
"e": 5966,
"s": 5871,
"text": "Let’s say we needed to get the mean tip by 2 variables. A common approach is to use groupby():"
},
{
"code": null,
"e": 6018,
"s": 5966,
"text": "df.groupby(['time', 'day'])['tip'].mean().unstack()"
},
{
"code": null,
"e": 6080,
"s": 6018,
"text": "But a slightly better way to do this is to use pivot_table():"
},
{
"code": null,
"e": 6117,
"s": 6080,
"text": "df.pivot_table('tip', 'time', 'day')"
},
{
"code": null,
"e": 6314,
"s": 6117,
"text": "Here, we didn’t specify the arguments because we have provided the values to the method in the correct order. Here is another version of the same code where all arguments are explicitly specified:"
},
{
"code": null,
"e": 6372,
"s": 6314,
"text": "df.pivot_table(values='tip', index='time', columns='day')"
},
{
"code": null,
"e": 6517,
"s": 6372,
"text": "This version is probably more readable. I think readability won’t be compromised if we omit the first argument name to be slightly more concise:"
},
{
"code": null,
"e": 6568,
"s": 6517,
"text": "df.pivot_table('tip', index='time', columns='day')"
},
{
"code": null,
"e": 6609,
"s": 6568,
"text": "We will keep this format moving forward."
},
{
"code": null,
"e": 6769,
"s": 6609,
"text": "By default, pivot_table() gives us mean values. However, we can easily change to our preferred function such as sum() by specifying it to the aggfunc argument:"
},
{
"code": null,
"e": 6835,
"s": 6769,
"text": "df.pivot_table('tip', index='time', columns='day', aggfunc='sum')"
},
{
"code": null,
"e": 6910,
"s": 6835,
"text": "Similar to crosstab(), it's also easy to get subtotals with pivot_table()."
},
{
"code": null,
"e": 7005,
"s": 6910,
"text": "df.pivot_table('tip', index='time', columns='day', aggfunc='sum', margins=True)"
},
{
"code": null,
"e": 7282,
"s": 7005,
"text": "We can also pass dictionary to aggfunc to customise the aggregate functions for each variable passed to values argument. Another useful argument is fill_value where we specify what values we want to see if the output is missing. Let’s see an example exemplifying these points:"
},
{
"code": null,
"e": 7451,
"s": 7282,
"text": "df.pivot_table(['tip', 'size'], index=['time', 'smoker'], columns='day', fill_value=0, margins=True, aggfunc={'tip': 'sum', 'size': 'max'})"
},
{
"code": null,
"e": 7573,
"s": 7451,
"text": "With pivot_table(), you know exactly which variables would be in rows and columns and no reshaping the data is necessary."
},
{
"code": null,
"e": 7708,
"s": 7573,
"text": "This tip is useful when we want to append the group aggregate measures back to the ungrouped data. Here is an example to clarify this:"
},
{
"code": null,
"e": 7789,
"s": 7708,
"text": "df['avg_tip_by_gender'] = df.groupby('gender')['tip'].transform('mean')df.head()"
},
{
"code": null,
"e": 7966,
"s": 7789,
"text": "In this example, newly created variable avg_tip_by_gender shows average tip by gender. In other words, mean tip by gender from below have been added back to the ungrouped data."
},
{
"code": null,
"e": 8015,
"s": 7966,
"text": "df.groupby('gender')['tip'].agg(['mean', 'std'])"
},
{
"code": null,
"e": 8065,
"s": 8015,
"text": "Now, let’s take a slightly more advanced example:"
},
{
"code": null,
"e": 8177,
"s": 8065,
"text": "df['n_sd_from_gender_avg_tip'] = df.groupby('gender')['tip'].transform(lambda x: (x-x.mean())/x.std())df.head()"
},
{
"code": null,
"e": 8240,
"s": 8177,
"text": "Here, using lambda function, we did 3 things for variable tip:"
},
{
"code": null,
"e": 8392,
"s": 8240,
"text": "x.mean(): Find mean by gender.x-x.mean(): Find the distance from mean by gender.(x-x.mean())/x.std(): Find the distance in units of standard deviation."
},
{
"code": null,
"e": 8542,
"s": 8392,
"text": "Let’s take the first record (index=0) as an example and round up the numbers to 2 decimal places for simplicity: x=1.01, x.mean()=2.83, x.std()= 1.16"
},
{
"code": null,
"e": 8603,
"s": 8542,
"text": "Then, n_sd_from_gender_avg_tip = (1.01 - 2.83)/ 1.16 = -1.57"
},
{
"code": null,
"e": 8787,
"s": 8603,
"text": "That’s what we find in the first row of n_sd_from_gender_avg_tip. For this record, the tip amount was about 1.57 standard deviations lower than the average tip among female customers."
},
{
"code": null,
"e": 8853,
"s": 8787,
"text": "Voila❕ These were my current top data aggregation tips in pandas!"
},
{
"code": null,
"e": 9077,
"s": 8853,
"text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me."
},
{
"code": null,
"e": 9346,
"s": 9077,
"text": "Thank you for reading my post. Hope you find my tips useful ✂️. If you are interested to learn more about pandas, here are links to my other posts:◼️️ Writing 5 common SQL queries in pandas◼️️ 5 tips for pandas users◼️️ How to transform variables in a pandas DataFrame"
}
] |
Clojure - Variadic Functions
|
Variadic functions are functions that take varying number of arguments (some arguments are optional). Function can also specify the ‘&’ ampersand symbol to take in an arbitrary number of arguments.
Following example shows how this can be achieved.
(defn demo
[message & others]
(str message (clojure.string/join " " others)))
The above function declaration has the ‘&’ symbol next to the argument others, which means that it can take an arbitrary number of arguments.
If you invoke the above function as
(demo "Hello" "This" "is" "the" "message")
Following will be the output.
“HelloThis is the message”
The ‘clojure.string/join’ is used to combine each individual string argument, which is passed to the function.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2572,
"s": 2374,
"text": "Variadic functions are functions that take varying number of arguments (some arguments are optional). Function can also specify the ‘&’ ampersand symbol to take in an arbitrary number of arguments."
},
{
"code": null,
"e": 2622,
"s": 2572,
"text": "Following example shows how this can be achieved."
},
{
"code": null,
"e": 2707,
"s": 2622,
"text": "(defn demo \n [message & others]\n (str message (clojure.string/join \" \" others)))"
},
{
"code": null,
"e": 2849,
"s": 2707,
"text": "The above function declaration has the ‘&’ symbol next to the argument others, which means that it can take an arbitrary number of arguments."
},
{
"code": null,
"e": 2885,
"s": 2849,
"text": "If you invoke the above function as"
},
{
"code": null,
"e": 2928,
"s": 2885,
"text": "(demo \"Hello\" \"This\" \"is\" \"the\" \"message\")"
},
{
"code": null,
"e": 2958,
"s": 2928,
"text": "Following will be the output."
},
{
"code": null,
"e": 2986,
"s": 2958,
"text": "“HelloThis is the message”\n"
},
{
"code": null,
"e": 3097,
"s": 2986,
"text": "The ‘clojure.string/join’ is used to combine each individual string argument, which is passed to the function."
},
{
"code": null,
"e": 3104,
"s": 3097,
"text": " Print"
},
{
"code": null,
"e": 3115,
"s": 3104,
"text": " Add Notes"
}
] |
File Handling in Java using FileReader and FileWriter
|
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Following example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
|
[
{
"code": null,
"e": 1554,
"s": 1062,
"text": "Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time."
},
{
"code": null,
"e": 1686,
"s": 1554,
"text": "Following example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −"
},
{
"code": null,
"e": 2205,
"s": 1686,
"text": "import java.io.*;\npublic class CopyFile {\n\n public static void main(String args[]) throws IOException {\n\n FileReader in = null;\n FileWriter out = null;\n\n try {\n in = new FileReader(\"input.txt\");\n out = new FileWriter(\"output.txt\");\n\n int c;\n while ((c = in.read()) != -1) {\n out.write(c);\n }\n } finally {\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n }\n }\n}"
},
{
"code": null,
"e": 2266,
"s": 2205,
"text": "Now let's have a file input.txt with the following content −"
},
{
"code": null,
"e": 2294,
"s": 2266,
"text": "This is test for copy file."
},
{
"code": null,
"e": 2518,
"s": 2294,
"text": "As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −"
},
{
"code": null,
"e": 2554,
"s": 2518,
"text": "$javac CopyFile.java\n$java CopyFile"
}
] |
Binary search in Java.
|
Following is the required program.
Live Demo
public class Tester {
public static int binarySearch(int arr[], int first, int last, int element){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < element ){
first = mid + 1;
}else if ( arr[mid] == element ){
return mid;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
return -1;
}
public static void main(String a[]) {
int[] array = { 10, 20, 30, 40, 50, 60 };
int element = 50;
int last=array.length-1;
int index = binarySearch(array,0,last,element);
if (index != -1) {
System.out.println(element + " present at index: " + index);
} else {
System.out.println(element + " is not present.");
}
}
}
50 is present at index: 4
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1957,
"s": 1107,
"text": "public class Tester {\n public static int binarySearch(int arr[], int first, int last, int element){\n int mid = (first + last)/2;\n while( first <= last ){\n if ( arr[mid] < element ){\n first = mid + 1; \n }else if ( arr[mid] == element ){ \n return mid;\n }else{\n last = mid - 1;\n }\n mid = (first + last)/2;\n }\n return -1; \n }\n \n public static void main(String a[]) {\n int[] array = { 10, 20, 30, 40, 50, 60 };\n int element = 50;\n int last=array.length-1;\n int index = binarySearch(array,0,last,element);\n if (index != -1) {\n System.out.println(element + \" present at index: \" + index);\n } else {\n System.out.println(element + \" is not present.\");\n }\n }\n}"
},
{
"code": null,
"e": 1983,
"s": 1957,
"text": "50 is present at index: 4"
}
] |
Remove consonants from a string | Practice | GeeksforGeeks
|
Given a string S, remove all consonants and print the modified string that contains vowels only.
Example 1:
Input
S = "abEkipo"
Output
aEio
Explanation : a, E, i, o are only vowels in the string.
Example 2:
Input
S = "rrty"
Output
No Vowel
Explanation: There are no vowels.
Your Task: You don't need to read input or print anything.Your task is to complete the function removeConsonants() which takes a string as input parameters, and returns the modified string that contains vowels only. If there is no vowel present in the string S, then return "No Vowel".
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).
Constraints
1 <= |S| <= 105
The string should consist of only alphabets.
0
vinayreddy222vr1 week ago
python solution
x="" for i in s: if (i=='a' or i=='e' or i=='i'or i=='o' or i=='u' or i=='A' or i=='E'or i=='I' or i=='O' or i=='U'): x=x+i if(len(x)==0): return 'No Vowel' return x
0
princejee20191 month ago
C++ || EASY TO UNDERSTAND
string removeConsonants(string s){ string res; for(int i =0;i<s.size();i++){ if(s[i]=='a' || s[i]=='A' || s[i]=='e' || s[i]=='E' || s[i]=='i' ||s[i]=='I' || s[i]=='o'|| s[i]=='O' || s[i]=='u' || s[i]=='U'){ res.push_back(s[i]); } } if(res.size()==0) return "No Vowel"; return res; }
0
atif836141 month ago
JAVA SOLUTION :
if (s.length() == 0) {
return null;
}
String ss ="";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o'
|| s.charAt(i) == 'u' || s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I'
|| s.charAt(i) == 'O' || s.charAt(i) == 'U') {
ss = ss + s.charAt(i);
}
if(res.length()==0){
return "No Vowel";
}
return ss;
}
0
codewithshoaib192 months ago
// Simple use of regex
String x=s.replaceAll("[^aeiouAEIOU]",""); // System.out.println(x); if(x.equals("")){ return "No Vowel"; } return x;
0
ankitparashxr2 months ago
java
String vo = "aeiouAEIOU"; StringBuffer res = new StringBuffer(); for(int i =0;i<s.length();i++) { if(vo.indexOf(s.charAt(i))!=-1) { res.append(s.charAt(i)); } } if(res.length()==0) { return "No Vowel"; } return res.toString();
+1
ciph3rcodes2 months ago
//JAVA SOLN BEST
String answer = "No Vowel";boolean check = false;if(s.contains("a") || s.contains("e") || s.contains("i") || s.contains("o")|| s.contains("u") || s.contains("A") || s.contains("E") || s.contains("I")|| s.contains("O") || s.contains("U")){check = true;}
if(check == true){return s.replaceAll("[BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz]", "");}
return answer;
0
arshergon3 months ago
Python3 Solution With O(N) and O(1) Space complexity;
Use a HashSet for O(1) lookUps, List has O(N) lookUps
def removeConsants(s):
hashSet = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
res = ""
for i in s:
if i in hashSet:
res+= i
return res if res else "No Vowel"
0
amiransarimy3 months ago
Simple Python Solutions
Total Time Taken:
0.3/1.8
def removeConsonants(self, s):
vowel_list =['A','E','I','O','U','a','e','i','o','u']
res =""
for ch in s:
if ch in vowel_list:
res += ch
return "No Vowel" if len(res) == 0 else res
0
ybrijesh6 months ago
string removeConsonants(string s){ //complete the function heredef removeConsonants(s): string a; for(int i=0;i<s.length();i++) { if(s[i]=='a' || s[i]=='A' || s[i]=='e' || s[i]=='E' || s[i]=='i' || s[i]=='I' || s[i]=='o' || s[i]=='O' || s[i]=='u' ||s[i]=='U') { a=a+s[i]; } } if(!a.empty()) { return a; } else { return "No Vowel"; }
0
SACHIN KUMAR1 year ago
SACHIN KUMAR
string removeConsonants(string s){ string str; for(int i=0;i<s.size();i++) {="" if(s[i]="='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U')" {="" str+="s[i];" }="" }="" int="" c="0;" for(int="" i="0;i<str.size();i++)" {="" c++;="" }="" if(c="=0)" {="" return="" "no="" vowel";="" }="" else="" {="" return="" str;="" }="" }<="" u="">
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.
|
[
{
"code": null,
"e": 335,
"s": 238,
"text": "Given a string S, remove all consonants and print the modified string that contains vowels only."
},
{
"code": null,
"e": 346,
"s": 335,
"text": "Example 1:"
},
{
"code": null,
"e": 435,
"s": 346,
"text": "Input\nS = \"abEkipo\"\nOutput\naEio\nExplanation : a, E, i, o are only vowels in the string.\n"
},
{
"code": null,
"e": 446,
"s": 435,
"text": "Example 2:"
},
{
"code": null,
"e": 515,
"s": 446,
"text": "Input\nS = \"rrty\"\nOutput\nNo Vowel\nExplanation: There are no vowels.\n\n"
},
{
"code": null,
"e": 801,
"s": 515,
"text": "Your Task: You don't need to read input or print anything.Your task is to complete the function removeConsonants() which takes a string as input parameters, and returns the modified string that contains vowels only. If there is no vowel present in the string S, then return \"No Vowel\"."
},
{
"code": null,
"e": 867,
"s": 801,
"text": "Expected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 940,
"s": 867,
"text": "Constraints\n1 <= |S| <= 105\nThe string should consist of only alphabets."
},
{
"code": null,
"e": 942,
"s": 940,
"text": "0"
},
{
"code": null,
"e": 968,
"s": 942,
"text": "vinayreddy222vr1 week ago"
},
{
"code": null,
"e": 984,
"s": 968,
"text": "python solution"
},
{
"code": null,
"e": 1203,
"s": 984,
"text": "x=\"\" for i in s: if (i=='a' or i=='e' or i=='i'or i=='o' or i=='u' or i=='A' or i=='E'or i=='I' or i=='O' or i=='U'): x=x+i if(len(x)==0): return 'No Vowel' return x "
},
{
"code": null,
"e": 1205,
"s": 1203,
"text": "0"
},
{
"code": null,
"e": 1230,
"s": 1205,
"text": "princejee20191 month ago"
},
{
"code": null,
"e": 1256,
"s": 1230,
"text": "C++ || EASY TO UNDERSTAND"
},
{
"code": null,
"e": 1605,
"s": 1256,
"text": "string removeConsonants(string s){ string res; for(int i =0;i<s.size();i++){ if(s[i]=='a' || s[i]=='A' || s[i]=='e' || s[i]=='E' || s[i]=='i' ||s[i]=='I' || s[i]=='o'|| s[i]=='O' || s[i]=='u' || s[i]=='U'){ res.push_back(s[i]); } } if(res.size()==0) return \"No Vowel\"; return res; }"
},
{
"code": null,
"e": 1607,
"s": 1605,
"text": "0"
},
{
"code": null,
"e": 1628,
"s": 1607,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 1644,
"s": 1628,
"text": "JAVA SOLUTION :"
},
{
"code": null,
"e": 2090,
"s": 1644,
"text": " if (s.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tString ss =\"\";\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o'\n\t\t\t\t\t|| s.charAt(i) == 'u' || s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I'\n\t\t\t\t\t|| s.charAt(i) == 'O' || s.charAt(i) == 'U') {\n\t\t\t\tss = ss + s.charAt(i);\n\t\t\t}\n\n\n\t\tif(res.length()==0){\n\t\t return \"No Vowel\";\n\t\t \n\t\t}\n\t\treturn ss;\n\t\t}"
},
{
"code": null,
"e": 2092,
"s": 2090,
"text": "0"
},
{
"code": null,
"e": 2121,
"s": 2092,
"text": "codewithshoaib192 months ago"
},
{
"code": null,
"e": 2144,
"s": 2121,
"text": "// Simple use of regex"
},
{
"code": null,
"e": 2296,
"s": 2144,
"text": "String x=s.replaceAll(\"[^aeiouAEIOU]\",\"\"); // System.out.println(x); if(x.equals(\"\")){ return \"No Vowel\"; } return x;"
},
{
"code": null,
"e": 2298,
"s": 2296,
"text": "0"
},
{
"code": null,
"e": 2324,
"s": 2298,
"text": "ankitparashxr2 months ago"
},
{
"code": null,
"e": 2329,
"s": 2324,
"text": "java"
},
{
"code": null,
"e": 2658,
"s": 2329,
"text": " String vo = \"aeiouAEIOU\"; StringBuffer res = new StringBuffer(); for(int i =0;i<s.length();i++) { if(vo.indexOf(s.charAt(i))!=-1) { res.append(s.charAt(i)); } } if(res.length()==0) { return \"No Vowel\"; } return res.toString();"
},
{
"code": null,
"e": 2661,
"s": 2658,
"text": "+1"
},
{
"code": null,
"e": 2685,
"s": 2661,
"text": "ciph3rcodes2 months ago"
},
{
"code": null,
"e": 2702,
"s": 2685,
"text": "//JAVA SOLN BEST"
},
{
"code": null,
"e": 2957,
"s": 2704,
"text": "String answer = \"No Vowel\";boolean check = false;if(s.contains(\"a\") || s.contains(\"e\") || s.contains(\"i\") || s.contains(\"o\")|| s.contains(\"u\") || s.contains(\"A\") || s.contains(\"E\") || s.contains(\"I\")|| s.contains(\"O\") || s.contains(\"U\")){check = true;}"
},
{
"code": null,
"e": 3049,
"s": 2957,
"text": "if(check == true){return s.replaceAll(\"[BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz]\", \"\");}"
},
{
"code": null,
"e": 3064,
"s": 3049,
"text": "return answer;"
},
{
"code": null,
"e": 3066,
"s": 3064,
"text": "0"
},
{
"code": null,
"e": 3088,
"s": 3066,
"text": "arshergon3 months ago"
},
{
"code": null,
"e": 3142,
"s": 3088,
"text": "Python3 Solution With O(N) and O(1) Space complexity;"
},
{
"code": null,
"e": 3196,
"s": 3142,
"text": "Use a HashSet for O(1) lookUps, List has O(N) lookUps"
},
{
"code": null,
"e": 3391,
"s": 3196,
"text": "def removeConsants(s):\n\thashSet = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n res = \"\"\n for i in s:\n \tif i in hashSet:\n res+= i\n return res if res else \"No Vowel\" "
},
{
"code": null,
"e": 3393,
"s": 3391,
"text": "0"
},
{
"code": null,
"e": 3418,
"s": 3393,
"text": "amiransarimy3 months ago"
},
{
"code": null,
"e": 3442,
"s": 3418,
"text": "Simple Python Solutions"
},
{
"code": null,
"e": 3460,
"s": 3442,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 3468,
"s": 3460,
"text": "0.3/1.8"
},
{
"code": null,
"e": 3720,
"s": 3468,
"text": "\ndef removeConsonants(self, s):\n vowel_list =['A','E','I','O','U','a','e','i','o','u']\n res =\"\"\n for ch in s:\n if ch in vowel_list:\n res += ch\n \n return \"No Vowel\" if len(res) == 0 else res"
},
{
"code": null,
"e": 3722,
"s": 3720,
"text": "0"
},
{
"code": null,
"e": 3743,
"s": 3722,
"text": "ybrijesh6 months ago"
},
{
"code": null,
"e": 4192,
"s": 3743,
"text": " string removeConsonants(string s){ //complete the function heredef removeConsonants(s): string a; for(int i=0;i<s.length();i++) { if(s[i]=='a' || s[i]=='A' || s[i]=='e' || s[i]=='E' || s[i]=='i' || s[i]=='I' || s[i]=='o' || s[i]=='O' || s[i]=='u' ||s[i]=='U') { a=a+s[i]; } } if(!a.empty()) { return a; } else { return \"No Vowel\"; } "
},
{
"code": null,
"e": 4194,
"s": 4192,
"text": "0"
},
{
"code": null,
"e": 4217,
"s": 4194,
"text": "SACHIN KUMAR1 year ago"
},
{
"code": null,
"e": 4230,
"s": 4217,
"text": "SACHIN KUMAR"
},
{
"code": null,
"e": 4626,
"s": 4230,
"text": "string removeConsonants(string s){ string str; for(int i=0;i<s.size();i++) {=\"\" if(s[i]=\"='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U')\" {=\"\" str+=\"s[i];\" }=\"\" }=\"\" int=\"\" c=\"0;\" for(int=\"\" i=\"0;i<str.size();i++)\" {=\"\" c++;=\"\" }=\"\" if(c=\"=0)\" {=\"\" return=\"\" \"no=\"\" vowel\";=\"\" }=\"\" else=\"\" {=\"\" return=\"\" str;=\"\" }=\"\" }<=\"\" u=\"\">"
},
{
"code": null,
"e": 4772,
"s": 4626,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4808,
"s": 4772,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4818,
"s": 4808,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4828,
"s": 4818,
"text": "\nContest\n"
},
{
"code": null,
"e": 4891,
"s": 4828,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5039,
"s": 4891,
"text": "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."
},
{
"code": null,
"e": 5247,
"s": 5039,
"text": "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."
},
{
"code": null,
"e": 5353,
"s": 5247,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to use SELF JOIN in MySQL?
|
To use SELF JOIN, let us create a table. The query to create a table is as follows −
mysql> create table SelfJoinDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> CountryName varchar(20),
-> CountryRank int,
-> `Year` varchar(10)
-> );
Query OK, 0 rows affected (1.02 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('US',1,'2016');
Query OK, 1 row affected (0.12 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',5,'2013');
Query OK, 1 row affected (0.16 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('France',45,'2010');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Turkey',3,'2000');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Japan',78,'1995');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Romania',110,'2007');
Query OK, 1 row affected (0.22 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',3,'2000');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from SelfJoinDemo;
The following is the output −
+----+-------------+-------------+------+
| Id | CountryName | CountryRank | Year |
+----+-------------+-------------+------+
| 1 | US | 1 | 2016 |
| 2 | UK | 5 | 2013 |
| 3 | France | 45 | 2010 |
| 4 | Turkey | 3 | 2000 |
| 5 | Japan | 78 | 1995 |
| 6 | Romania | 110 | 2007 |
| 7 | UK | 3 | 2000 |
+----+-------------+-------------+------+
7 rows in set (0.00 sec)
Here is the query of SELF JOIN −
mysql> SELECT DISTINCT t1.CountryName, t2.Year
-> FROM SelfJoinDemo AS t1,
-> SelfJoinDemo AS t2
-> WHERE t1.Year=t2.Year
-> and t1.CountryName='US';
The following is the output −
+-------------+------+
| CountryName | Year |
+-------------+------+
| US | 2016 |
+-------------+------+
1 row in set (0.00 sec
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To use SELF JOIN, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1363,
"s": 1147,
"text": "mysql> create table SelfJoinDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> CountryName varchar(20),\n -> CountryRank int,\n -> `Year` varchar(10)\n -> );\nQuery OK, 0 rows affected (1.02 sec)"
},
{
"code": null,
"e": 1456,
"s": 1363,
"text": "Now you can insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2337,
"s": 1456,
"text": "mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('US',1,'2016');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',5,'2013');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('France',45,'2010');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Turkey',3,'2000');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Japan',78,'1995');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Romania',110,'2007');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',3,'2000');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2424,
"s": 2337,
"text": "Display all records from the table using a select statement. The query is as follows −"
},
{
"code": null,
"e": 2458,
"s": 2424,
"text": "mysql> select *from SelfJoinDemo;"
},
{
"code": null,
"e": 2488,
"s": 2458,
"text": "The following is the output −"
},
{
"code": null,
"e": 2975,
"s": 2488,
"text": "+----+-------------+-------------+------+\n| Id | CountryName | CountryRank | Year |\n+----+-------------+-------------+------+\n| 1 | US | 1 | 2016 |\n| 2 | UK | 5 | 2013 |\n| 3 | France | 45 | 2010 |\n| 4 | Turkey | 3 | 2000 |\n| 5 | Japan | 78 | 1995 |\n| 6 | Romania | 110 | 2007 |\n| 7 | UK | 3 | 2000 |\n+----+-------------+-------------+------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3008,
"s": 2975,
"text": "Here is the query of SELF JOIN −"
},
{
"code": null,
"e": 3170,
"s": 3008,
"text": "mysql> SELECT DISTINCT t1.CountryName, t2.Year\n -> FROM SelfJoinDemo AS t1,\n -> SelfJoinDemo AS t2\n -> WHERE t1.Year=t2.Year\n -> and t1.CountryName='US';"
},
{
"code": null,
"e": 3200,
"s": 3170,
"text": "The following is the output −"
},
{
"code": null,
"e": 3338,
"s": 3200,
"text": "+-------------+------+\n| CountryName | Year |\n+-------------+------+\n| US | 2016 |\n+-------------+------+\n1 row in set (0.00 sec"
}
] |
Pair with maximum difference in a Matrix - GeeksforGeeks
|
28 May, 2021
Given a NxM matrix with N rows and M columns of positive integers. The task is to find the pair with the maximum difference in the given matrix.Note: Pairs at positions (a, b) and (b, a) are considered equivalent.Examples:
Input : mat[N][M] = {{1, 2, 3, 4},
{25, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}}
Output : 24
Pair (25, 1) has the maximum difference
Input : mat[N][M] = {{1, 2, 3},
{4, 6, 7},
{9, 10, 5}}
Output : 9
Pair (10, 1) has the maximum difference.
The idea is to observe that the elements contributing to the pair with maximum difference are the maximum and minimum elements in the matrix. So, find the maximum and minimum elements in the matrix and return the difference between them.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find with maximum// difference in a matrix #include <bits/stdc++.h>using namespace std; #define N 4 // Rows#define M 4 // Columns // Function to find pair with maximum// difference in a matrixint maxDifferencePair(int mat[N][M]){ int maxElement = INT_MIN; // max int minElement = INT_MAX; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return abs(maxElement - minElement);} // Driver Codeint main(){ // matrix int mat[N][M] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << maxDifferencePair(mat) << endl; return 0;}
// Java program to find with maximum// difference in a matrix import java.io.*; class GFG { static int N= 4; // Rowsstatic int M = 4; // Columns // Function to find pair with maximum// difference in a matrixstatic int maxDifferencePair(int mat[][]){ int maxElement = Integer.MIN_VALUE; // max int minElement = Integer.MAX_VALUE; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return Math.abs(maxElement - minElement);} // Driver Code public static void main (String[] args) { // matrix int mat[][] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println( maxDifferencePair(mat)); }} // This code is contributed by inder_verma..
# Python3 program to find with maximum# difference in a matrix N = 4 # RowsM = 4 # Columns # Function to find pair with maximum# difference in a matrixdef maxDifferencePair(mat): maxElement = -10**9 # max minElement = 10**9 # min # Traverse the matrix for i in range(N): for j in range(M): # Find max element if (mat[i][j] > maxElement): maxElement = mat[i][j] # Find min element if (mat[i][j] < minElement): minElement = mat[i][j] return abs(maxElement - minElement) # Driver Code # matrixmat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16]] print(maxDifferencePair(mat)) # This code is contributed# by mohit kumar
// C# program to find with maximum// difference in a matrixusing System; class GFG{static int N = 4; // Rowsstatic int M = 4; // Columns // Function to find pair with// maximum difference in a matrixstatic int maxDifferencePair(int [,]mat){ int maxElement = int.MinValue; // max int minElement = int.MaxValue; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i, j] > maxElement) { maxElement = mat[i, j]; } // Find min element if (mat[i, j] < minElement) { minElement = mat[i, j]; } } } return Math.Abs(maxElement - minElement);} // Driver Codepublic static void Main (){ // matrix int [,]mat = {{ 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }}; Console.WriteLine( maxDifferencePair(mat));}} // This code is contributed// by inder_verma
<script> // JavaScript program to find with maximum// difference in a matrix let N= 4; // Rowslet M = 4; // Columns // Function to find pair with maximum// difference in a matrixfunction maxDifferencePair(mat){ let maxElement = Number.MIN_VALUE; // max let minElement = Number.MAX_VALUE; // min // Traverse the matrix for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return Math.abs(maxElement - minElement);} // Driver Codelet mat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16]]; document.write( maxDifferencePair(mat)); // This code is contributed by unknown2108 </script>
24
inderDuMCA
mohit kumar 29
unknown2108
Arrays
Matrix
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
The Celebrity Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Gold Mine Problem
Python program to multiply two matrices
Multiplication of two Matrices in Single line using Numpy in Python
Program to find transpose of a matrix
|
[
{
"code": null,
"e": 25099,
"s": 25071,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 25324,
"s": 25099,
"text": "Given a NxM matrix with N rows and M columns of positive integers. The task is to find the pair with the maximum difference in the given matrix.Note: Pairs at positions (a, b) and (b, a) are considered equivalent.Examples: "
},
{
"code": null,
"e": 25654,
"s": 25324,
"text": "Input : mat[N][M] = {{1, 2, 3, 4},\n {25, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15, 16}}\nOutput : 24\nPair (25, 1) has the maximum difference\n\nInput : mat[N][M] = {{1, 2, 3},\n {4, 6, 7},\n {9, 10, 5}}\nOutput : 9\nPair (10, 1) has the maximum difference."
},
{
"code": null,
"e": 25946,
"s": 25656,
"text": "The idea is to observe that the elements contributing to the pair with maximum difference are the maximum and minimum elements in the matrix. So, find the maximum and minimum elements in the matrix and return the difference between them.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25950,
"s": 25946,
"text": "C++"
},
{
"code": null,
"e": 25955,
"s": 25950,
"text": "Java"
},
{
"code": null,
"e": 25963,
"s": 25955,
"text": "Python3"
},
{
"code": null,
"e": 25966,
"s": 25963,
"text": "C#"
},
{
"code": null,
"e": 25977,
"s": 25966,
"text": "Javascript"
},
{
"code": "// C++ program to find with maximum// difference in a matrix #include <bits/stdc++.h>using namespace std; #define N 4 // Rows#define M 4 // Columns // Function to find pair with maximum// difference in a matrixint maxDifferencePair(int mat[N][M]){ int maxElement = INT_MIN; // max int minElement = INT_MAX; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return abs(maxElement - minElement);} // Driver Codeint main(){ // matrix int mat[N][M] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << maxDifferencePair(mat) << endl; return 0;}",
"e": 26955,
"s": 25977,
"text": null
},
{
"code": "// Java program to find with maximum// difference in a matrix import java.io.*; class GFG { static int N= 4; // Rowsstatic int M = 4; // Columns // Function to find pair with maximum// difference in a matrixstatic int maxDifferencePair(int mat[][]){ int maxElement = Integer.MIN_VALUE; // max int minElement = Integer.MAX_VALUE; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return Math.abs(maxElement - minElement);} // Driver Code public static void main (String[] args) { // matrix int mat[][] = { { 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println( maxDifferencePair(mat)); }} // This code is contributed by inder_verma..",
"e": 28034,
"s": 26955,
"text": null
},
{
"code": "# Python3 program to find with maximum# difference in a matrix N = 4 # RowsM = 4 # Columns # Function to find pair with maximum# difference in a matrixdef maxDifferencePair(mat): maxElement = -10**9 # max minElement = 10**9 # min # Traverse the matrix for i in range(N): for j in range(M): # Find max element if (mat[i][j] > maxElement): maxElement = mat[i][j] # Find min element if (mat[i][j] < minElement): minElement = mat[i][j] return abs(maxElement - minElement) # Driver Code # matrixmat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16]] print(maxDifferencePair(mat)) # This code is contributed# by mohit kumar",
"e": 28806,
"s": 28034,
"text": null
},
{
"code": "// C# program to find with maximum// difference in a matrixusing System; class GFG{static int N = 4; // Rowsstatic int M = 4; // Columns // Function to find pair with// maximum difference in a matrixstatic int maxDifferencePair(int [,]mat){ int maxElement = int.MinValue; // max int minElement = int.MaxValue; // min // Traverse the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Find max element if (mat[i, j] > maxElement) { maxElement = mat[i, j]; } // Find min element if (mat[i, j] < minElement) { minElement = mat[i, j]; } } } return Math.Abs(maxElement - minElement);} // Driver Codepublic static void Main (){ // matrix int [,]mat = {{ 1, 2, 3, 4 }, { 25, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }}; Console.WriteLine( maxDifferencePair(mat));}} // This code is contributed// by inder_verma",
"e": 29882,
"s": 28806,
"text": null
},
{
"code": "<script> // JavaScript program to find with maximum// difference in a matrix let N= 4; // Rowslet M = 4; // Columns // Function to find pair with maximum// difference in a matrixfunction maxDifferencePair(mat){ let maxElement = Number.MIN_VALUE; // max let minElement = Number.MAX_VALUE; // min // Traverse the matrix for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // Find max element if (mat[i][j] > maxElement) { maxElement = mat[i][j]; } // Find min element if (mat[i][j] < minElement) { minElement = mat[i][j]; } } } return Math.abs(maxElement - minElement);} // Driver Codelet mat = [[ 1, 2, 3, 4 ], [ 25, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16]]; document.write( maxDifferencePair(mat)); // This code is contributed by unknown2108 </script>",
"e": 30813,
"s": 29882,
"text": null
},
{
"code": null,
"e": 30816,
"s": 30813,
"text": "24"
},
{
"code": null,
"e": 30829,
"s": 30818,
"text": "inderDuMCA"
},
{
"code": null,
"e": 30844,
"s": 30829,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30856,
"s": 30844,
"text": "unknown2108"
},
{
"code": null,
"e": 30863,
"s": 30856,
"text": "Arrays"
},
{
"code": null,
"e": 30870,
"s": 30863,
"text": "Matrix"
},
{
"code": null,
"e": 30877,
"s": 30870,
"text": "Arrays"
},
{
"code": null,
"e": 30884,
"s": 30877,
"text": "Matrix"
},
{
"code": null,
"e": 30982,
"s": 30884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30991,
"s": 30982,
"text": "Comments"
},
{
"code": null,
"e": 31004,
"s": 30991,
"text": "Old Comments"
},
{
"code": null,
"e": 31066,
"s": 31004,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 31099,
"s": 31066,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31120,
"s": 31099,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 31162,
"s": 31120,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 31184,
"s": 31162,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 31266,
"s": 31184,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 31284,
"s": 31266,
"text": "Gold Mine Problem"
},
{
"code": null,
"e": 31324,
"s": 31284,
"text": "Python program to multiply two matrices"
},
{
"code": null,
"e": 31392,
"s": 31324,
"text": "Multiplication of two Matrices in Single line using Numpy in Python"
}
] |
Python SQLite – Update Data
|
08 May, 2021
In this article, we will discuss how we can update data in tables in the SQLite database using Python – sqlite3 module.
The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement.
UPDATE table_name SET column1 = value1, column2 = value2,...
WHERE condition;
In the above syntax, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated.
Below are some examples which depict how to update data in an SQLite table.
Example 1: Python SQLite program to update a particular column. In this example, we are first going to create an EMPLOYEE table and insert values into it. Then we are going to set the income of employees to 5000 whose age is less than 25
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg1.db') # Creating a cursor object using # the cursor() methodcursor = conn.cursor() # Creating tabletable = """CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255),AGE int, SEX VARCHAR(255), INCOME int);"""cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') # Display data insertedprint("EMPLOYEE Table: ")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Updatingcursor.execute('''UPDATE EMPLOYEE SET INCOME = 5000 WHERE Age<25;''')print('\nAfter Updating...\n') # Display dataprint("EMPLOYEE Table: ")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Example 2: In this program, we create a similar table as that of the previous example. Here we assign the age of the female employees to 0.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geeks1.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable = """CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255),AGE int, SEX VARCHAR(255), INCOME int);"""cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') # Display data insertedprint("EMPLOYEE Table: ")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Updatingcursor.execute('''UPDATE EMPLOYEE SET AGE = 0 WHERE SEX='F';''')print('\nAfer Updating...\n') # Display dataprint("EMPLOYEE Table: ")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Example 3: In the below program we update multiple columns using the UPDATE statement. In this example, we are first going to create a STAFF table and insert values into it. Then we are going to update all the columns i.e. all the attributes of the staff whose department is Computer.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg3.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STAFF(NAME VARCHAR(255), AGE int,DEPARTMENT VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STAFF VALUES('Anand', 45, 'Chemistry')''')cursor.execute('''INSERT INTO STAFF VALUES('Ravi', 32, 'Physics')''')cursor.execute('''INSERT INTO STAFF VALUES('Chandini', 32, 'Computer')''')cursor.execute('''INSERT INTO STAFF VALUES('Latika', 40, 'Maths')''') # Display data insertedprint("STAFF Table: ")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Updating cursor.execute('''UPDATE STAFF SET NAME = 'Ram', AGE = 30, DEPARTMENT = 'Biology' WHERE DEPARTMENT = 'Computer';''')print('\nAfter Updating...\n') # Display data print("STAFF Table: ")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Example 4: In the below program we create the previous table and update the name and age of the staff whose department is Chemistry.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg4.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STAFF(NAME VARCHAR(255), AGE int,DEPARTMENT VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STAFF VALUES('Anand', 45, 'Chemistry')''')cursor.execute('''INSERT INTO STAFF VALUES('Ravi', 32, 'Physics')''')cursor.execute('''INSERT INTO STAFF VALUES('Chandini', 32, 'Computer')''')cursor.execute('''INSERT INTO STAFF VALUES('Latika', 40, 'Maths')''') # Display data insertedprint("STAFF Table: ")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Updating cursor.execute('''UPDATE STAFF SET NAME = 'Chandini', AGE = 32 WHERE DEPARTMENT = 'Chemistry';''')print('\nAfter Updating...\n') # Display data print("STAFF Table: ")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Example 5: Below program depicts the use of the UPDATE statement without the WHERE statement. In this program, we create the STUDENT table and insert values into it. After that, we update the SECTION column of all the students by assigning it to X.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg5.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint("STUDENT Table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Updating cursor.execute('''UPDATE STUDENT SET SECTION = 'X';''')print('\nAfter Updating...\n') # Display data print("STUDENT Table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Example 6: In the below program we create a simple STUDENT table and update all the data into it using only UPDATE and SET query.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg6.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));"""cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint("STUDENT Table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Updating cursor.execute('''UPDATE STUDENT SET NAME = 'X',CLASS = 'Y', SECTION = 'Z';''')print('\nAfter Updating...\n') # Display data print("STUDENT Table: ")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Picked
Python-SQLite
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 May, 2021"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "In this article, we will discuss how we can update data in tables in the SQLite database using Python – sqlite3 module. "
},
{
"code": null,
"e": 346,
"s": 149,
"text": "The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement."
},
{
"code": null,
"e": 409,
"s": 346,
"text": "UPDATE table_name SET column1 = value1, column2 = value2,... "
},
{
"code": null,
"e": 427,
"s": 409,
"text": "WHERE condition; "
},
{
"code": null,
"e": 615,
"s": 427,
"text": "In the above syntax, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated. "
},
{
"code": null,
"e": 691,
"s": 615,
"text": "Below are some examples which depict how to update data in an SQLite table."
},
{
"code": null,
"e": 929,
"s": 691,
"text": "Example 1: Python SQLite program to update a particular column. In this example, we are first going to create an EMPLOYEE table and insert values into it. Then we are going to set the income of employees to 5000 whose age is less than 25"
},
{
"code": null,
"e": 937,
"s": 929,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg1.db') # Creating a cursor object using # the cursor() methodcursor = conn.cursor() # Creating tabletable = \"\"\"CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255),AGE int, SEX VARCHAR(255), INCOME int);\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') # Display data insertedprint(\"EMPLOYEE Table: \")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Updatingcursor.execute('''UPDATE EMPLOYEE SET INCOME = 5000 WHERE Age<25;''')print('\\nAfter Updating...\\n') # Display dataprint(\"EMPLOYEE Table: \")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()",
"e": 2424,
"s": 937,
"text": null
},
{
"code": null,
"e": 2432,
"s": 2424,
"text": "Output:"
},
{
"code": null,
"e": 2440,
"s": 2432,
"text": "SQLite:"
},
{
"code": null,
"e": 2580,
"s": 2440,
"text": "Example 2: In this program, we create a similar table as that of the previous example. Here we assign the age of the female employees to 0."
},
{
"code": null,
"e": 2588,
"s": 2580,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('geeks1.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable = \"\"\"CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255),AGE int, SEX VARCHAR(255), INCOME int);\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''') cursor.execute( '''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') # Display data insertedprint(\"EMPLOYEE Table: \")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Updatingcursor.execute('''UPDATE EMPLOYEE SET AGE = 0 WHERE SEX='F';''')print('\\nAfer Updating...\\n') # Display dataprint(\"EMPLOYEE Table: \")data = cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()",
"e": 4072,
"s": 2588,
"text": null
},
{
"code": null,
"e": 4080,
"s": 4072,
"text": "Output:"
},
{
"code": null,
"e": 4088,
"s": 4080,
"text": "SQLite:"
},
{
"code": null,
"e": 4373,
"s": 4088,
"text": "Example 3: In the below program we update multiple columns using the UPDATE statement. In this example, we are first going to create a STAFF table and insert values into it. Then we are going to update all the columns i.e. all the attributes of the staff whose department is Computer."
},
{
"code": null,
"e": 4381,
"s": 4373,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg3.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STAFF(NAME VARCHAR(255), AGE int,DEPARTMENT VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STAFF VALUES('Anand', 45, 'Chemistry')''')cursor.execute('''INSERT INTO STAFF VALUES('Ravi', 32, 'Physics')''')cursor.execute('''INSERT INTO STAFF VALUES('Chandini', 32, 'Computer')''')cursor.execute('''INSERT INTO STAFF VALUES('Latika', 40, 'Maths')''') # Display data insertedprint(\"STAFF Table: \")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Updating cursor.execute('''UPDATE STAFF SET NAME = 'Ram', AGE = 30, DEPARTMENT = 'Biology' WHERE DEPARTMENT = 'Computer';''')print('\\nAfter Updating...\\n') # Display data print(\"STAFF Table: \")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 5479,
"s": 4381,
"text": null
},
{
"code": null,
"e": 5487,
"s": 5479,
"text": "Output:"
},
{
"code": null,
"e": 5495,
"s": 5487,
"text": "SQLite:"
},
{
"code": null,
"e": 5628,
"s": 5495,
"text": "Example 4: In the below program we create the previous table and update the name and age of the staff whose department is Chemistry."
},
{
"code": null,
"e": 5636,
"s": 5628,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg4.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STAFF(NAME VARCHAR(255), AGE int,DEPARTMENT VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STAFF VALUES('Anand', 45, 'Chemistry')''')cursor.execute('''INSERT INTO STAFF VALUES('Ravi', 32, 'Physics')''')cursor.execute('''INSERT INTO STAFF VALUES('Chandini', 32, 'Computer')''')cursor.execute('''INSERT INTO STAFF VALUES('Latika', 40, 'Maths')''') # Display data insertedprint(\"STAFF Table: \")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Updating cursor.execute('''UPDATE STAFF SET NAME = 'Chandini', AGE = 32 WHERE DEPARTMENT = 'Chemistry';''')print('\\nAfter Updating...\\n') # Display data print(\"STAFF Table: \")data=cursor.execute('''SELECT * FROM STAFF''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 6716,
"s": 5636,
"text": null
},
{
"code": null,
"e": 6724,
"s": 6716,
"text": "Output:"
},
{
"code": null,
"e": 6732,
"s": 6724,
"text": "SQLite:"
},
{
"code": null,
"e": 6981,
"s": 6732,
"text": "Example 5: Below program depicts the use of the UPDATE statement without the WHERE statement. In this program, we create the STUDENT table and insert values into it. After that, we update the SECTION column of all the students by assigning it to X."
},
{
"code": null,
"e": 6989,
"s": 6981,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg5.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint(\"STUDENT Table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Updating cursor.execute('''UPDATE STUDENT SET SECTION = 'X';''')print('\\nAfter Updating...\\n') # Display data print(\"STUDENT Table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 7971,
"s": 6989,
"text": null
},
{
"code": null,
"e": 7980,
"s": 7971,
"text": "Output: "
},
{
"code": null,
"e": 7988,
"s": 7980,
"text": "SQLite:"
},
{
"code": null,
"e": 8118,
"s": 7988,
"text": "Example 6: In the below program we create a simple STUDENT table and update all the data into it using only UPDATE and SET query."
},
{
"code": null,
"e": 8126,
"s": 8118,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg6.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),SECTION VARCHAR(255));\"\"\"cursor.execute(table) # Queries to INSERT records.cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''') # Display data insertedprint(\"STUDENT Table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Updating cursor.execute('''UPDATE STUDENT SET NAME = 'X',CLASS = 'Y', SECTION = 'Z';''')print('\\nAfter Updating...\\n') # Display data print(\"STUDENT Table: \")data=cursor.execute('''SELECT * FROM STUDENT''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 9132,
"s": 8126,
"text": null
},
{
"code": null,
"e": 9141,
"s": 9132,
"text": "Output: "
},
{
"code": null,
"e": 9149,
"s": 9141,
"text": "SQLite:"
},
{
"code": null,
"e": 9156,
"s": 9149,
"text": "Picked"
},
{
"code": null,
"e": 9170,
"s": 9156,
"text": "Python-SQLite"
},
{
"code": null,
"e": 9177,
"s": 9170,
"text": "Python"
},
{
"code": null,
"e": 9275,
"s": 9177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9307,
"s": 9275,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 9334,
"s": 9307,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 9355,
"s": 9334,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 9378,
"s": 9355,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9434,
"s": 9378,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 9465,
"s": 9434,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 9507,
"s": 9465,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 9549,
"s": 9507,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 9588,
"s": 9549,
"text": "Python | Get unique values from a list"
}
] |
Change figure size in Pandas – Python
|
11 Dec, 2020
Prerequisites: Pandas
The size of a plot can be modified by passing required dimensions as a tuple to the figsize parameter of the plot() method. it is used to determine the size of a figure object.
Syntax:
figsize=(width, height)
Where dimensions should be given in inches.
Import pandas.
Create or load data
Call the plot() function with a figsize parameter along with dimensions.
Example 1
Python3
import pandas as pd # import the pandas module # python list of numbersdata1 = [10, 20, 50, 30, 15] # convert the list to a pandas seriess1 = pd.Series(data1) # creates a figure of size 20 inches wide and 10 inches highs1.plot(figsize=(20, 10))
Output:
Example 2
Python3
# import the pandas moduleimport pandas as pd # Creating a pandas dataframedf = pd.DataFrame({'names': ['A', 'B', 'C', 'D'], 'val': [10, 45, 30, 20]}) # creates a bar graph of size 15 inches wide and 10 inches highdf.plot.bar(x='names', y='val', rot=0, figsize=(15, 10))
Output :
Example 3
Python3
# import the pandas moduleimport pandas as pd # Creating a pandas dataframe with indexdf = pd.DataFrame({'value': [3.330, 4.87, 5.97]}, index=['Item 1', 'Item 2', 'Item 3']) df.plot.pie(y='value', figsize=(5, 5))
Output :
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 74,
"s": 52,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 251,
"s": 74,
"text": "The size of a plot can be modified by passing required dimensions as a tuple to the figsize parameter of the plot() method. it is used to determine the size of a figure object."
},
{
"code": null,
"e": 259,
"s": 251,
"text": "Syntax:"
},
{
"code": null,
"e": 283,
"s": 259,
"text": "figsize=(width, height)"
},
{
"code": null,
"e": 327,
"s": 283,
"text": "Where dimensions should be given in inches."
},
{
"code": null,
"e": 342,
"s": 327,
"text": "Import pandas."
},
{
"code": null,
"e": 362,
"s": 342,
"text": "Create or load data"
},
{
"code": null,
"e": 435,
"s": 362,
"text": "Call the plot() function with a figsize parameter along with dimensions."
},
{
"code": null,
"e": 445,
"s": 435,
"text": "Example 1"
},
{
"code": null,
"e": 453,
"s": 445,
"text": "Python3"
},
{
"code": "import pandas as pd # import the pandas module # python list of numbersdata1 = [10, 20, 50, 30, 15] # convert the list to a pandas seriess1 = pd.Series(data1) # creates a figure of size 20 inches wide and 10 inches highs1.plot(figsize=(20, 10))",
"e": 704,
"s": 453,
"text": null
},
{
"code": null,
"e": 712,
"s": 704,
"text": "Output:"
},
{
"code": null,
"e": 722,
"s": 712,
"text": "Example 2"
},
{
"code": null,
"e": 730,
"s": 722,
"text": "Python3"
},
{
"code": "# import the pandas moduleimport pandas as pd # Creating a pandas dataframedf = pd.DataFrame({'names': ['A', 'B', 'C', 'D'], 'val': [10, 45, 30, 20]}) # creates a bar graph of size 15 inches wide and 10 inches highdf.plot.bar(x='names', y='val', rot=0, figsize=(15, 10))",
"e": 1005,
"s": 730,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1005,
"text": "Output :"
},
{
"code": null,
"e": 1024,
"s": 1014,
"text": "Example 3"
},
{
"code": null,
"e": 1032,
"s": 1024,
"text": "Python3"
},
{
"code": "# import the pandas moduleimport pandas as pd # Creating a pandas dataframe with indexdf = pd.DataFrame({'value': [3.330, 4.87, 5.97]}, index=['Item 1', 'Item 2', 'Item 3']) df.plot.pie(y='value', figsize=(5, 5))",
"e": 1264,
"s": 1032,
"text": null
},
{
"code": null,
"e": 1273,
"s": 1264,
"text": "Output :"
},
{
"code": null,
"e": 1296,
"s": 1273,
"text": "Python pandas-plotting"
},
{
"code": null,
"e": 1310,
"s": 1296,
"text": "Python-pandas"
},
{
"code": null,
"e": 1317,
"s": 1310,
"text": "Python"
},
{
"code": null,
"e": 1415,
"s": 1317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1433,
"s": 1415,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1475,
"s": 1433,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1497,
"s": 1475,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1532,
"s": 1497,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1558,
"s": 1532,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1590,
"s": 1558,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1619,
"s": 1590,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1646,
"s": 1619,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1676,
"s": 1646,
"text": "Iterate over a list in Python"
}
] |
GATE | GATE CS 2019 | Question 15
|
27 Sep, 2021
Consider Z = X − Y where X, Y and Z are all in sign-magnitude form. X and Y are each represented in n bits. To avoid overflow, the representation of Z would require a minimum of:(A) n bits(B) n−1 bits(C) n+1 bits(D) n+2 bitsAnswer: (C)Explanation: Overflow can occur when two same sign numbers are added or two opposite sign numbers are subtracted.
For example:
let n = 4 bit, X = +6 and Y = -5 (1 bit for sign and 3 bit for magnitude)
Therefore, Z = X - Y = 6 - (-5) = 6+5 = 11
But result (Z) 11 needs 5 (= 4 + 1) bits to store,
Sin integer 11 needs 1 bit for sign and 4 bit for magnitude.
Therefore, to avoid overflow, the representation of Z would require a minimum of (n + 1) bits.
Option (C) is correct.
Number Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersNumber Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:06 / 28:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XpFNwoGzBQ8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 403,
"s": 54,
"text": "Consider Z = X − Y where X, Y and Z are all in sign-magnitude form. X and Y are each represented in n bits. To avoid overflow, the representation of Z would require a minimum of:(A) n bits(B) n−1 bits(C) n+1 bits(D) n+2 bitsAnswer: (C)Explanation: Overflow can occur when two same sign numbers are added or two opposite sign numbers are subtracted."
},
{
"code": null,
"e": 416,
"s": 403,
"text": "For example:"
},
{
"code": null,
"e": 647,
"s": 416,
"text": "let n = 4 bit, X = +6 and Y = -5 (1 bit for sign and 3 bit for magnitude)\nTherefore, Z = X - Y = 6 - (-5) = 6+5 = 11\nBut result (Z) 11 needs 5 (= 4 + 1) bits to store, \nSin integer 11 needs 1 bit for sign and 4 bit for magnitude. "
},
{
"code": null,
"e": 742,
"s": 647,
"text": "Therefore, to avoid overflow, the representation of Z would require a minimum of (n + 1) bits."
},
{
"code": null,
"e": 765,
"s": 742,
"text": "Option (C) is correct."
},
{
"code": null,
"e": 1743,
"s": 765,
"text": "Number Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersNumber Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:06 / 28:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=XpFNwoGzBQ8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 1765,
"s": 1743,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1770,
"s": 1765,
"text": "GATE"
},
{
"code": null,
"e": 1868,
"s": 1770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1910,
"s": 1868,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 1944,
"s": 1910,
"text": "GATE | Gate IT 2005 | Question 11"
},
{
"code": null,
"e": 1980,
"s": 1944,
"text": "GATE | GATE MOCK 2017 | Question 45"
},
{
"code": null,
"e": 2014,
"s": 1980,
"text": "GATE | GATE-CS-2004 | Question 90"
},
{
"code": null,
"e": 2047,
"s": 2014,
"text": "GATE | GATE-CS-2000 | Question 2"
},
{
"code": null,
"e": 2081,
"s": 2047,
"text": "GATE | GATE CS 2013 | Question 50"
},
{
"code": null,
"e": 2115,
"s": 2081,
"text": "GATE | GATE CS 2012 | Question 65"
},
{
"code": null,
"e": 2149,
"s": 2115,
"text": "GATE | GATE-CS-2003 | Question 64"
},
{
"code": null,
"e": 2183,
"s": 2149,
"text": "GATE | GATE-CS-2004 | Question 90"
}
] |
Split the string into substrings using delimiter
|
21 May, 2021
Given a string and a delimiter character. Split the string based on the delimiter and print the list of resulting sub strings.Examples:
Input : str = "geeks;for;geeks"
d_ch = ';'
Output : geeks
for
geeks
Input : str = "##ayush##jauhari####"
d_ch = '#'
Output : ayush
jauhari
Source: Microsoft IDC Bangalore Interview | Set 153.
Algorithm:
splitStrings(str, substr_list, dl)
Initialize word = ""
Initialize num = 0
str = str + dl
l = str.size
for i = 0 to l-1
if str[i] != dl
word = word + str[i]
else
if word.size != 0
substr_list[num] = word
num++
word = ""
return num
This algorithm will fill in the splitted substrings in the array substr_list[] and will return the number of such substrings as num.
C++
Java
Python3
C#
Javascript
// C++ implementation to split string into// substrings on the basis of delimiter#include <bits/stdc++.h>using namespace std; // function to split string into substrings on the// basis of delimiter and return the substrings// after splitvector<string> splitStrings(string str, char dl){ string word = ""; // to count the number of split strings int num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' int l = str.size(); // traversing 'str' from left to right vector<string> substr_list; for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if ((int)word.size() != 0) substr_list.push_back(word); // reset 'word' word = ""; } } // return the splitted strings return substr_list;} // Driver program to test aboveint main(){ string str = "geeks;for;geeks"; char dl = ';'; vector<string> res = splitStrings(str, dl); for (auto x : res) cout << x << endl; return 0;}
// Java implementation to split String into// substrings on the basis of delimiterimport java.util.*; class GFG{ // function to split String into subStrings // on the basis of delimiter and return // the subStrings after split static Vector<String> splitStrings(String str, char dl) { String word = ""; // to count the number of split Strings int num = 0; // adding delimiter character // at the end of 'str' str = str + dl; // length of 'str' int l = str.length(); // traversing 'str' from left to right Vector<String> substr_list = new Vector<String>(); for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str.charAt(i) != dl) { word = word + str.charAt(i); } else { // if 'word' is not an empty String, // then add this 'word' to the array // 'substr_list[]' if ((int) word.length() != 0) { substr_list.add(word); } // reset 'word' word = ""; } } // return the splitted Strings return substr_list; } // Driver code public static void main(String[] args) { String str = "geeks;for;geeks"; char dl = ';'; Vector<String> res = splitStrings(str, dl); for (String x : res) { System.out.println(x); } }} // This code is contributed by PrinciRaj1992
# Python 3 implementation to split string# into substrings on the basis of delimiter # function to split string into substrings# on the basis of delimiter and return the# substrings after splitdef splitStrings(st, dl): word = "" # to count the number of split strings num = 0 # adding delimiter character at # the end of 'str' st += dl # length of 'str' l = len(st) # traversing 'str' from left to right substr_list = [] for i in range(l): # if str[i] is not equal to the # delimiter character then accumulate # it to 'word' if (st[i] != dl): word += st[i] else: # if 'word' is not an empty string, # then add this 'word' to the array # 'substr_list[]' if (len(word) != 0): substr_list.append(word) # reset 'word' word = "" # return the splitted strings return substr_list # Driver Codeif __name__ == '__main__': str = "geeks;for;geeks" dl = ';' res = splitStrings(str, dl) for x in range(len(res)): print(res[x]) # This code is contributed by# Surendra_Gangwar
// C# implementation to split String into// substrings on the basis of delimiterusing System;using System.Collections.Generic; class GFG{ // function to split String into subStrings // on the basis of delimiter and return // the subStrings after split static List<String> splitStrings(String str, char dl) { String word = ""; // to count the number of split Strings int num = 0; // adding delimiter character // at the end of 'str' str = str + dl; // length of 'str' int l = str.Length; // traversing 'str' from left to right List<String> substr_list = new List<String>(); for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) { word = word + str[i]; } else { // if 'word' is not an empty String, // then add this 'word' to the array // 'substr_list[]' if ((int) word.Length != 0) { substr_list.Add(word); } // reset 'word' word = ""; } } // return the splitted Strings return substr_list; } // Driver code public static void Main() { String str = "geeks;for;geeks"; char dl = ';'; List<String> res = splitStrings(str, dl); foreach (String x in res) { Console.WriteLine(x); } }} //This code is contributed by 29AjayKumar
<script> // Javascript implementation to split string into// substrings on the basis of delimiter // function to split string into substrings on the// basis of delimiter and return the substrings// after splitfunction splitStrings(str, dl){ var word = ""; // to count the number of split strings var num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' var l = str.length; // traversing 'str' from left to right var substr_list = []; for (var i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if (word.length != 0) substr_list.push(word); // reset 'word' word = ""; } } // return the splitted strings return substr_list;} // Driver program to test abovevar str = "geeks;for;geeks";var dl = ';';var res = splitStrings(str, dl);res.forEach(x => { document.write( x + "<br>");}); </script>
Output:
geeks
for
geeks
Time Complexity: O(n), where n is the length of the given string.
princiraj1992
29AjayKumar
SURENDRA_GANGWAR
famously
cpp-vector
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
What is Data Structure: Types, Classifications and Applications
Reverse words in a given string
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 190,
"s": 52,
"text": "Given a string and a delimiter character. Split the string based on the delimiter and print the list of resulting sub strings.Examples: "
},
{
"code": null,
"e": 373,
"s": 190,
"text": "Input : str = \"geeks;for;geeks\"\n d_ch = ';'\nOutput : geeks\n for\n geeks\n\nInput : str = \"##ayush##jauhari####\"\n d_ch = '#'\nOutput : ayush\n jauhari"
},
{
"code": null,
"e": 426,
"s": 373,
"text": "Source: Microsoft IDC Bangalore Interview | Set 153."
},
{
"code": null,
"e": 441,
"s": 428,
"text": "Algorithm: "
},
{
"code": null,
"e": 781,
"s": 441,
"text": "splitStrings(str, substr_list, dl)\n Initialize word = \"\"\n Initialize num = 0\n str = str + dl\n l = str.size\n \n for i = 0 to l-1\n if str[i] != dl\n word = word + str[i]\n else\n if word.size != 0\n substr_list[num] = word\n num++\n word = \"\"\n\n return num"
},
{
"code": null,
"e": 915,
"s": 781,
"text": "This algorithm will fill in the splitted substrings in the array substr_list[] and will return the number of such substrings as num. "
},
{
"code": null,
"e": 919,
"s": 915,
"text": "C++"
},
{
"code": null,
"e": 924,
"s": 919,
"text": "Java"
},
{
"code": null,
"e": 932,
"s": 924,
"text": "Python3"
},
{
"code": null,
"e": 935,
"s": 932,
"text": "C#"
},
{
"code": null,
"e": 946,
"s": 935,
"text": "Javascript"
},
{
"code": "// C++ implementation to split string into// substrings on the basis of delimiter#include <bits/stdc++.h>using namespace std; // function to split string into substrings on the// basis of delimiter and return the substrings// after splitvector<string> splitStrings(string str, char dl){ string word = \"\"; // to count the number of split strings int num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' int l = str.size(); // traversing 'str' from left to right vector<string> substr_list; for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if ((int)word.size() != 0) substr_list.push_back(word); // reset 'word' word = \"\"; } } // return the splitted strings return substr_list;} // Driver program to test aboveint main(){ string str = \"geeks;for;geeks\"; char dl = ';'; vector<string> res = splitStrings(str, dl); for (auto x : res) cout << x << endl; return 0;}",
"e": 2258,
"s": 946,
"text": null
},
{
"code": "// Java implementation to split String into// substrings on the basis of delimiterimport java.util.*; class GFG{ // function to split String into subStrings // on the basis of delimiter and return // the subStrings after split static Vector<String> splitStrings(String str, char dl) { String word = \"\"; // to count the number of split Strings int num = 0; // adding delimiter character // at the end of 'str' str = str + dl; // length of 'str' int l = str.length(); // traversing 'str' from left to right Vector<String> substr_list = new Vector<String>(); for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str.charAt(i) != dl) { word = word + str.charAt(i); } else { // if 'word' is not an empty String, // then add this 'word' to the array // 'substr_list[]' if ((int) word.length() != 0) { substr_list.add(word); } // reset 'word' word = \"\"; } } // return the splitted Strings return substr_list; } // Driver code public static void main(String[] args) { String str = \"geeks;for;geeks\"; char dl = ';'; Vector<String> res = splitStrings(str, dl); for (String x : res) { System.out.println(x); } }} // This code is contributed by PrinciRaj1992",
"e": 3911,
"s": 2258,
"text": null
},
{
"code": "# Python 3 implementation to split string# into substrings on the basis of delimiter # function to split string into substrings# on the basis of delimiter and return the# substrings after splitdef splitStrings(st, dl): word = \"\" # to count the number of split strings num = 0 # adding delimiter character at # the end of 'str' st += dl # length of 'str' l = len(st) # traversing 'str' from left to right substr_list = [] for i in range(l): # if str[i] is not equal to the # delimiter character then accumulate # it to 'word' if (st[i] != dl): word += st[i] else: # if 'word' is not an empty string, # then add this 'word' to the array # 'substr_list[]' if (len(word) != 0): substr_list.append(word) # reset 'word' word = \"\" # return the splitted strings return substr_list # Driver Codeif __name__ == '__main__': str = \"geeks;for;geeks\" dl = ';' res = splitStrings(str, dl) for x in range(len(res)): print(res[x]) # This code is contributed by# Surendra_Gangwar",
"e": 5096,
"s": 3911,
"text": null
},
{
"code": "// C# implementation to split String into// substrings on the basis of delimiterusing System;using System.Collections.Generic; class GFG{ // function to split String into subStrings // on the basis of delimiter and return // the subStrings after split static List<String> splitStrings(String str, char dl) { String word = \"\"; // to count the number of split Strings int num = 0; // adding delimiter character // at the end of 'str' str = str + dl; // length of 'str' int l = str.Length; // traversing 'str' from left to right List<String> substr_list = new List<String>(); for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) { word = word + str[i]; } else { // if 'word' is not an empty String, // then add this 'word' to the array // 'substr_list[]' if ((int) word.Length != 0) { substr_list.Add(word); } // reset 'word' word = \"\"; } } // return the splitted Strings return substr_list; } // Driver code public static void Main() { String str = \"geeks;for;geeks\"; char dl = ';'; List<String> res = splitStrings(str, dl); foreach (String x in res) { Console.WriteLine(x); } }} //This code is contributed by 29AjayKumar",
"e": 6736,
"s": 5096,
"text": null
},
{
"code": "<script> // Javascript implementation to split string into// substrings on the basis of delimiter // function to split string into substrings on the// basis of delimiter and return the substrings// after splitfunction splitStrings(str, dl){ var word = \"\"; // to count the number of split strings var num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' var l = str.length; // traversing 'str' from left to right var substr_list = []; for (var i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if (word.length != 0) substr_list.push(word); // reset 'word' word = \"\"; } } // return the splitted strings return substr_list;} // Driver program to test abovevar str = \"geeks;for;geeks\";var dl = ';';var res = splitStrings(str, dl);res.forEach(x => { document.write( x + \"<br>\");}); </script>",
"e": 7945,
"s": 6736,
"text": null
},
{
"code": null,
"e": 7955,
"s": 7945,
"text": "Output: "
},
{
"code": null,
"e": 7971,
"s": 7955,
"text": "geeks\nfor\ngeeks"
},
{
"code": null,
"e": 8038,
"s": 7971,
"text": "Time Complexity: O(n), where n is the length of the given string. "
},
{
"code": null,
"e": 8052,
"s": 8038,
"text": "princiraj1992"
},
{
"code": null,
"e": 8064,
"s": 8052,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8081,
"s": 8064,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8090,
"s": 8081,
"text": "famously"
},
{
"code": null,
"e": 8101,
"s": 8090,
"text": "cpp-vector"
},
{
"code": null,
"e": 8109,
"s": 8101,
"text": "Strings"
},
{
"code": null,
"e": 8117,
"s": 8109,
"text": "Strings"
},
{
"code": null,
"e": 8215,
"s": 8117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8253,
"s": 8215,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 8314,
"s": 8253,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 8350,
"s": 8314,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 8395,
"s": 8350,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 8447,
"s": 8395,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 8511,
"s": 8447,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8543,
"s": 8511,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 8588,
"s": 8543,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 8632,
"s": 8588,
"text": "Reverse string in Python (6 different ways)"
}
] |
R program to find perfect numbers upto n numbers and in the given range
|
25 Feb, 2021
Given a range the task is to write a R program to print all perfect numbers in that range.
A positive integer that is equal to the sum of its proper divisors is known as a perfect number. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8,128. Please note that all the perfect square numbers end with 0, 1, 4, 5, 6 or 9 but all the numbers with end with 0, 1, 4, 5, 6 or 9 thus perfect numbers are not perfect square numbers. Example, 11, 21, 51, 79, 76 etc. are the numbers which are not perfect square numbers.
Algorithm:
Fix interval
Find factors of the number
Find sum
Check equivalence
Choose accordingly
Increment number
Keeping going in this fashion until end of the interval is reached.
Example :
Find the perfect and non-perfect numbers upto 10 numbers starting from 1 ?
Output:
[1] “1 is not a perfect number”
[1] “2 is not a perfect number”
[1] “3 is not a perfect number”
[1] “4 is not a perfect number”
[1] “5 is not a perfect number”
[1] “6 is a perfect number”
[1] “7 is not a perfect number”
[1] “8 is not a perfect number”
[1] “9 is not a perfect number”
[1] “10 is not a perfect number”
Example 1:
R
for (k in 50:100) { n = k i = 1 s = 0 while (i < n) { if (n %% i == 0) { s = s + i } i = i + 1 } if (s == n) { print(paste(n,"is a perfect number")) } else{ print(paste(n,"is not a perfect number")) }k=k+1}
Output:
[1] “1 is not a perfect number”
[1] .
[1] .
[1] “6 is a perfect number”
[1] “7 is not a perfect number”
[1] .
[1] .
[1] “27 is not a perfect number”
[1] “28 is a perfect number”
[1] .
[1] .
[1] “495 is not a perfect number”
[1] “496 is a perfect number”
[1] .
[1] .
[1] “500 is not a perfect number”
Example 2:
R
perfect_numbers = c()non_perfect_numbers=c()for (k in 1:100) { n <- k i = 1 s = 0 while (i < n) { if (n %% i == 0) { s = s + i } i = i + 1 } if (s == n) { perfect_numbers = c(perfect_numbers, n) } else{ non_perfect_numbers = c(non_perfect_numbers, n) }}print(perfect_numbers)print(non_perfect_numbers)k=k+1
Output:
(perfect_numbers)
[1] 6 28
(non_perfect_numbers)
[1] 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 20
[20] 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40
[39] 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
[58] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
[77] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
[96] 98 99 100
R-Mathematics
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?
R - if statement
How to filter R DataFrame by values in a column?
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
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "Given a range the task is to write a R program to print all perfect numbers in that range."
},
{
"code": null,
"e": 622,
"s": 143,
"text": "A positive integer that is equal to the sum of its proper divisors is known as a perfect number. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8,128. Please note that all the perfect square numbers end with 0, 1, 4, 5, 6 or 9 but all the numbers with end with 0, 1, 4, 5, 6 or 9 thus perfect numbers are not perfect square numbers. Example, 11, 21, 51, 79, 76 etc. are the numbers which are not perfect square numbers."
},
{
"code": null,
"e": 633,
"s": 622,
"text": "Algorithm:"
},
{
"code": null,
"e": 646,
"s": 633,
"text": "Fix interval"
},
{
"code": null,
"e": 673,
"s": 646,
"text": "Find factors of the number"
},
{
"code": null,
"e": 682,
"s": 673,
"text": "Find sum"
},
{
"code": null,
"e": 700,
"s": 682,
"text": "Check equivalence"
},
{
"code": null,
"e": 719,
"s": 700,
"text": "Choose accordingly"
},
{
"code": null,
"e": 736,
"s": 719,
"text": "Increment number"
},
{
"code": null,
"e": 804,
"s": 736,
"text": "Keeping going in this fashion until end of the interval is reached."
},
{
"code": null,
"e": 814,
"s": 804,
"text": "Example :"
},
{
"code": null,
"e": 889,
"s": 814,
"text": "Find the perfect and non-perfect numbers upto 10 numbers starting from 1 ?"
},
{
"code": null,
"e": 897,
"s": 889,
"text": "Output:"
},
{
"code": null,
"e": 929,
"s": 897,
"text": "[1] “1 is not a perfect number”"
},
{
"code": null,
"e": 961,
"s": 929,
"text": "[1] “2 is not a perfect number”"
},
{
"code": null,
"e": 993,
"s": 961,
"text": "[1] “3 is not a perfect number”"
},
{
"code": null,
"e": 1025,
"s": 993,
"text": "[1] “4 is not a perfect number”"
},
{
"code": null,
"e": 1057,
"s": 1025,
"text": "[1] “5 is not a perfect number”"
},
{
"code": null,
"e": 1085,
"s": 1057,
"text": "[1] “6 is a perfect number”"
},
{
"code": null,
"e": 1117,
"s": 1085,
"text": "[1] “7 is not a perfect number”"
},
{
"code": null,
"e": 1149,
"s": 1117,
"text": "[1] “8 is not a perfect number”"
},
{
"code": null,
"e": 1181,
"s": 1149,
"text": "[1] “9 is not a perfect number”"
},
{
"code": null,
"e": 1215,
"s": 1181,
"text": "[1] “10 is not a perfect number” "
},
{
"code": null,
"e": 1227,
"s": 1215,
"text": "Example 1: "
},
{
"code": null,
"e": 1229,
"s": 1227,
"text": "R"
},
{
"code": "for (k in 50:100) { n = k i = 1 s = 0 while (i < n) { if (n %% i == 0) { s = s + i } i = i + 1 } if (s == n) { print(paste(n,\"is a perfect number\")) } else{ print(paste(n,\"is not a perfect number\")) }k=k+1}",
"e": 1494,
"s": 1229,
"text": null
},
{
"code": null,
"e": 1502,
"s": 1494,
"text": "Output:"
},
{
"code": null,
"e": 1534,
"s": 1502,
"text": "[1] “1 is not a perfect number”"
},
{
"code": null,
"e": 1540,
"s": 1534,
"text": "[1] ."
},
{
"code": null,
"e": 1546,
"s": 1540,
"text": "[1] ."
},
{
"code": null,
"e": 1574,
"s": 1546,
"text": "[1] “6 is a perfect number”"
},
{
"code": null,
"e": 1606,
"s": 1574,
"text": "[1] “7 is not a perfect number”"
},
{
"code": null,
"e": 1612,
"s": 1606,
"text": "[1] ."
},
{
"code": null,
"e": 1618,
"s": 1612,
"text": "[1] ."
},
{
"code": null,
"e": 1651,
"s": 1618,
"text": "[1] “27 is not a perfect number”"
},
{
"code": null,
"e": 1680,
"s": 1651,
"text": "[1] “28 is a perfect number”"
},
{
"code": null,
"e": 1686,
"s": 1680,
"text": "[1] ."
},
{
"code": null,
"e": 1692,
"s": 1686,
"text": "[1] ."
},
{
"code": null,
"e": 1726,
"s": 1692,
"text": "[1] “495 is not a perfect number”"
},
{
"code": null,
"e": 1756,
"s": 1726,
"text": "[1] “496 is a perfect number”"
},
{
"code": null,
"e": 1762,
"s": 1756,
"text": "[1] ."
},
{
"code": null,
"e": 1768,
"s": 1762,
"text": "[1] ."
},
{
"code": null,
"e": 1802,
"s": 1768,
"text": "[1] “500 is not a perfect number”"
},
{
"code": null,
"e": 1813,
"s": 1802,
"text": "Example 2:"
},
{
"code": null,
"e": 1815,
"s": 1813,
"text": "R"
},
{
"code": "perfect_numbers = c()non_perfect_numbers=c()for (k in 1:100) { n <- k i = 1 s = 0 while (i < n) { if (n %% i == 0) { s = s + i } i = i + 1 } if (s == n) { perfect_numbers = c(perfect_numbers, n) } else{ non_perfect_numbers = c(non_perfect_numbers, n) }}print(perfect_numbers)print(non_perfect_numbers)k=k+1",
"e": 2182,
"s": 1815,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2182,
"text": "Output:"
},
{
"code": null,
"e": 2208,
"s": 2190,
"text": "(perfect_numbers)"
},
{
"code": null,
"e": 2218,
"s": 2208,
"text": "[1] 6 28"
},
{
"code": null,
"e": 2240,
"s": 2218,
"text": "(non_perfect_numbers)"
},
{
"code": null,
"e": 2321,
"s": 2240,
"text": " [1] 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 20"
},
{
"code": null,
"e": 2402,
"s": 2321,
"text": "[20] 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40"
},
{
"code": null,
"e": 2483,
"s": 2402,
"text": "[39] 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59"
},
{
"code": null,
"e": 2564,
"s": 2483,
"text": "[58] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78"
},
{
"code": null,
"e": 2645,
"s": 2564,
"text": "[77] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97"
},
{
"code": null,
"e": 2662,
"s": 2645,
"text": "[96] 98 99 100"
},
{
"code": null,
"e": 2676,
"s": 2662,
"text": "R-Mathematics"
},
{
"code": null,
"e": 2687,
"s": 2676,
"text": "R Language"
},
{
"code": null,
"e": 2785,
"s": 2687,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2837,
"s": 2785,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2895,
"s": 2837,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2930,
"s": 2895,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2968,
"s": 2930,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2985,
"s": 2968,
"text": "R - if statement"
},
{
"code": null,
"e": 3034,
"s": 2985,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3071,
"s": 3034,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3114,
"s": 3071,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3151,
"s": 3114,
"text": "How to import an Excel File into R ?"
}
] |
Infosys-InfyTQ Archives - GeeksforGeeks
|
Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ
Infosys InfyTQ Interview Experience 2022
Infosys Infytq Interview Experience for System Engineer
Infosys InfyTQ DSE Interview Experience 2023
Infosys Certification Exam (InfyTQ) 2021
Infosys InfyTq System Engineer Specialist Interview Experience
INFYTQ Interview Experience for System Engineer 2022
Infosys(Infytq) Certification Exam (Systems Engineer Role)
Infosys Certification Exam | InfyTQ
Infosys Infytq Interview Experience for System Engineer 2020
|
[
{
"code": null,
"e": 24206,
"s": 24130,
"text": "Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ"
},
{
"code": null,
"e": 24247,
"s": 24206,
"text": "Infosys InfyTQ Interview Experience 2022"
},
{
"code": null,
"e": 24303,
"s": 24247,
"text": "Infosys Infytq Interview Experience for System Engineer"
},
{
"code": null,
"e": 24348,
"s": 24303,
"text": "Infosys InfyTQ DSE Interview Experience 2023"
},
{
"code": null,
"e": 24389,
"s": 24348,
"text": "Infosys Certification Exam (InfyTQ) 2021"
},
{
"code": null,
"e": 24452,
"s": 24389,
"text": "Infosys InfyTq System Engineer Specialist Interview Experience"
},
{
"code": null,
"e": 24505,
"s": 24452,
"text": "INFYTQ Interview Experience for System Engineer 2022"
},
{
"code": null,
"e": 24564,
"s": 24505,
"text": "Infosys(Infytq) Certification Exam (Systems Engineer Role)"
},
{
"code": null,
"e": 24600,
"s": 24564,
"text": "Infosys Certification Exam | InfyTQ"
}
] |
File uploading in React.js
|
29 Jan, 2021
For any developer who envisions building an application, uploading images is a major component they have to take into account. It is an essential requirement while creating a complete application. File uploading means a user from a client machine wants to upload files to the server. For example, users can upload images, videos, etc on Facebook, Instagram. As with any programming problem, there are many ways to achieve this outcome. This article explains a simple way to implement the approach to upload a single file with React. The process of uploading an image can be broadly divided into two steps:
Select a File (user input): To enable the user to pick a file, the first step is to add the tag to our App component. This tag should have the type attribute set as “file”. Now, we need an event handler to listen to any changes made to the file. This event handler will be triggered whenever the user selects a new file and will update the state.
Send a request to the server: After storing the selected file (in the state), we are now required to send it to a server. For this purpose, we can use fetch or Axios. (In this code, we use Axios a promise-based HTTP client for the browser and NodeJS). The file is sent to the service wrapped in a FormData object.Installation Axios: Run the below command.
Run the below command.
npm install axios --save
Open your react project directory and edit the App.js file from src folder:
src App.js:
javascript
import axios from 'axios'; import React,{Component} from 'react'; class App extends Component { state = { // Initially, no file is selected selectedFile: null }; // On file select (from the pop up) onFileChange = event => { // Update the state this.setState({ selectedFile: event.target.files[0] }); }; // On file upload (click the upload button) onFileUpload = () => { // Create an object of formData const formData = new FormData(); // Update the formData object formData.append( "myFile", this.state.selectedFile, this.state.selectedFile.name ); // Details of the uploaded file console.log(this.state.selectedFile); // Request made to the backend api // Send formData object axios.post("api/uploadfile", formData); }; // File content to be displayed after // file upload is complete fileData = () => { if (this.state.selectedFile) { return ( <div> <h2>File Details:</h2> <p>File Name: {this.state.selectedFile.name}</p> <p>File Type: {this.state.selectedFile.type}</p> <p> Last Modified:{" "} {this.state.selectedFile.lastModifiedDate.toDateString()} </p> </div> ); } else { return ( <div> <br /> <h4>Choose before Pressing the Upload button</h4> </div> ); } }; render() { return ( <div> <h1> GeeksforGeeks </h1> <h3> File Upload using React! </h3> <div> <input type="file" onChange={this.onFileChange} /> <button onClick={this.onFileUpload}> Upload! </button> </div> {this.fileData()} </div> ); } } export default App;
Output:
shubhamyadav4
react-js
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jan, 2021"
},
{
"code": null,
"e": 662,
"s": 54,
"text": "For any developer who envisions building an application, uploading images is a major component they have to take into account. It is an essential requirement while creating a complete application. File uploading means a user from a client machine wants to upload files to the server. For example, users can upload images, videos, etc on Facebook, Instagram. As with any programming problem, there are many ways to achieve this outcome. This article explains a simple way to implement the approach to upload a single file with React. The process of uploading an image can be broadly divided into two steps: "
},
{
"code": null,
"e": 1009,
"s": 662,
"text": "Select a File (user input): To enable the user to pick a file, the first step is to add the tag to our App component. This tag should have the type attribute set as “file”. Now, we need an event handler to listen to any changes made to the file. This event handler will be triggered whenever the user selects a new file and will update the state."
},
{
"code": null,
"e": 1365,
"s": 1009,
"text": "Send a request to the server: After storing the selected file (in the state), we are now required to send it to a server. For this purpose, we can use fetch or Axios. (In this code, we use Axios a promise-based HTTP client for the browser and NodeJS). The file is sent to the service wrapped in a FormData object.Installation Axios: Run the below command."
},
{
"code": null,
"e": 1388,
"s": 1365,
"text": "Run the below command."
},
{
"code": null,
"e": 1413,
"s": 1388,
"text": "npm install axios --save"
},
{
"code": null,
"e": 1489,
"s": 1413,
"text": "Open your react project directory and edit the App.js file from src folder:"
},
{
"code": null,
"e": 1502,
"s": 1489,
"text": "src App.js: "
},
{
"code": null,
"e": 1513,
"s": 1502,
"text": "javascript"
},
{
"code": "import axios from 'axios'; import React,{Component} from 'react'; class App extends Component { state = { // Initially, no file is selected selectedFile: null }; // On file select (from the pop up) onFileChange = event => { // Update the state this.setState({ selectedFile: event.target.files[0] }); }; // On file upload (click the upload button) onFileUpload = () => { // Create an object of formData const formData = new FormData(); // Update the formData object formData.append( \"myFile\", this.state.selectedFile, this.state.selectedFile.name ); // Details of the uploaded file console.log(this.state.selectedFile); // Request made to the backend api // Send formData object axios.post(\"api/uploadfile\", formData); }; // File content to be displayed after // file upload is complete fileData = () => { if (this.state.selectedFile) { return ( <div> <h2>File Details:</h2> <p>File Name: {this.state.selectedFile.name}</p> <p>File Type: {this.state.selectedFile.type}</p> <p> Last Modified:{\" \"} {this.state.selectedFile.lastModifiedDate.toDateString()} </p> </div> ); } else { return ( <div> <br /> <h4>Choose before Pressing the Upload button</h4> </div> ); } }; render() { return ( <div> <h1> GeeksforGeeks </h1> <h3> File Upload using React! </h3> <div> <input type=\"file\" onChange={this.onFileChange} /> <button onClick={this.onFileUpload}> Upload! </button> </div> {this.fileData()} </div> ); } } export default App;",
"e": 3507,
"s": 1513,
"text": null
},
{
"code": null,
"e": 3517,
"s": 3507,
"text": "Output: "
},
{
"code": null,
"e": 3533,
"s": 3519,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 3542,
"s": 3533,
"text": "react-js"
},
{
"code": null,
"e": 3553,
"s": 3542,
"text": "JavaScript"
},
{
"code": null,
"e": 3570,
"s": 3553,
"text": "Web Technologies"
},
{
"code": null,
"e": 3597,
"s": 3570,
"text": "Web technologies Questions"
}
] |
Python – Consecutive identical elements count
|
12 Nov, 2020
Given the elements list, get all the elements that have an identical element as the next element.
Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] Output : 3 Explanation : 5, 6 and 2 has identical element as their next element.
Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 3, 10] Output : 2 Explanation : 5 and 6 has identical element as their next element.
Method #1 : Using loop + set()
In this, we iterate and check for the next element, if equal to current, we add in result list, then it is converted to set to get distinct elements.
Python3
# Python3 code to demonstrate working of # Consecutive identical elements count# Using loop + set() # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] # printing original listprint("The original list is : " + str(test_list)) res = []for idx in range(0, len(test_list) - 1): # getting Consecutive elements if test_list[idx] == test_list[idx + 1]: res.append(test_list[idx]) # getting count of unique elements res = len(list(set(res))) # printing result print("Consecutive identical elements count : " + str(res))
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3
Method #2 : Using list comprehension + set() + len()
This method is similar to above method, difference being its shorter way to solve this problem. The len(), and set() are used for task of getting unique elements count.
Python3
# Python3 code to demonstrate working of# Consecutive identical elements count# Using list comprehension + set() + len() # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] # printing original listprint("The original list is : " + str(test_list)) # getting Consecutive elementsres = [test_list[idx] for idx in range( 0, len(test_list) - 1) if test_list[idx] == test_list[idx + 1]] # getting count of unique elementsres = len(list(set(res))) # printing resultprint("Consecutive identical elements count : " + str(res))
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3
Python list-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 ?
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given the elements list, get all the elements that have an identical element as the next element."
},
{
"code": null,
"e": 265,
"s": 126,
"text": "Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] Output : 3 Explanation : 5, 6 and 2 has identical element as their next element."
},
{
"code": null,
"e": 402,
"s": 265,
"text": "Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 3, 10] Output : 2 Explanation : 5 and 6 has identical element as their next element. "
},
{
"code": null,
"e": 433,
"s": 402,
"text": "Method #1 : Using loop + set()"
},
{
"code": null,
"e": 583,
"s": 433,
"text": "In this, we iterate and check for the next element, if equal to current, we add in result list, then it is converted to set to get distinct elements."
},
{
"code": null,
"e": 591,
"s": 583,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Consecutive identical elements count# Using loop + set() # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] # printing original listprint(\"The original list is : \" + str(test_list)) res = []for idx in range(0, len(test_list) - 1): # getting Consecutive elements if test_list[idx] == test_list[idx + 1]: res.append(test_list[idx]) # getting count of unique elements res = len(list(set(res))) # printing result print(\"Consecutive identical elements count : \" + str(res))",
"e": 1161,
"s": 591,
"text": null
},
{
"code": null,
"e": 1264,
"s": 1161,
"text": "The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]\nConsecutive identical elements count : 3\n"
},
{
"code": null,
"e": 1317,
"s": 1264,
"text": "Method #2 : Using list comprehension + set() + len()"
},
{
"code": null,
"e": 1486,
"s": 1317,
"text": "This method is similar to above method, difference being its shorter way to solve this problem. The len(), and set() are used for task of getting unique elements count."
},
{
"code": null,
"e": 1494,
"s": 1486,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Consecutive identical elements count# Using list comprehension + set() + len() # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # getting Consecutive elementsres = [test_list[idx] for idx in range( 0, len(test_list) - 1) if test_list[idx] == test_list[idx + 1]] # getting count of unique elementsres = len(list(set(res))) # printing resultprint(\"Consecutive identical elements count : \" + str(res))",
"e": 2037,
"s": 1494,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2037,
"text": "The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]\nConsecutive identical elements count : 3\n"
},
{
"code": null,
"e": 2161,
"s": 2140,
"text": "Python list-programs"
},
{
"code": null,
"e": 2168,
"s": 2161,
"text": "Python"
},
{
"code": null,
"e": 2184,
"s": 2168,
"text": "Python Programs"
},
{
"code": null,
"e": 2282,
"s": 2184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2314,
"s": 2282,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2341,
"s": 2314,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2362,
"s": 2341,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2385,
"s": 2362,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2441,
"s": 2385,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2463,
"s": 2441,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2502,
"s": 2463,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2540,
"s": 2502,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2589,
"s": 2540,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Testing with Jest
|
27 Jan, 2022
Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code(usually, a function) and match the output with the expected output.
Jest Features:
zero config: As we will see later in this article, close to none configuration is required to get started with writing tests and deploying them. However, a config file can be supplied to the test suite as well.
snapshots: Jest has the ability to enable snapshot testing as well. Essentially, the snapshots are matched with the saved snapshot and check for matching functionality.
isolated tests: Jest tests are run parallelly to improve run time.
Setting up a jest project
Install Jest using npm:
npm install jest. The -D keyword installs jest as dev dependency
Project Structure: In the project root directory, make a tests folder. This folder will store all the test files. Note that the js files(which are to be tested) are mapped by their names. For example, index.js is mapped to index.test.js. This index.test.js file is placed in the ‘tests’ folder. This is the conventional project structure.
Start testing:
To start, lets see a basic test workflow.
test – adding two pos nums
To run the test, use the script
npm run test
This will look for the test script mentioned in the package.json of the project.
pkg-json-test-script-ss. See test in scripts
We will use the ‘expect’ method to test our functions. The functions can also be tested using ‘describe’ and ‘it’.
A basic test: adding two positive nums and checking result.
//index.js
testForAdd: (a, b) => { return (a + b) },
//index.test.js
test('test adding two positive nums', function() {
expect(testFns.testForAdd(4, 5)).toBe(9);
});
When the ‘npm run test’ is run, the index.test.js file is gone through. Then the testForAdd function is run which is placed in the ‘testFns’ object. The toBe is used to ‘match’ the returned response from the test to what is expected. This ‘result matching’ leads to either a ‘fail’ or a ‘pass’.
test adding two pos nums
The following test will fail because of the ‘toBe(8)’.
//example of a failing test
test('test adding two positive nums - failing test', function() {
expect(testFns.testForAdd(4, 5)).toBe(8);
});
Opposite of toBe: not.toBe() The opposite of the ‘toBe’ matcher is created by simply prefixing it with ‘not.’ For example:
//test successful - test for opposite of a matcher.
//The following test will 'Pass' if the returned value is not equal to 8.
test('test adding two positive nums - failing test', function() {
expect(testFns.testForAdd(4, 5)).not.toBe(8);
});
Using ‘toBe’ with JS Objects: Let’s think of a case where every field of a JS object is to be tested. Jest provides us a way to do this using ‘toEqual’. The ‘toEqual’ is a deep-matcher(checks every field and sub-fields possible).
//expect toEqual example - check every field's value
// testFns.test_toEqual(gfgObj)
test('check gfgObj toEqual', () => {
let gfgObj = { name: "GFG" };
gfgObj['type'] = "company";
expect(gfgObj).toEqual({ name: "GFG", type: "company" });
});
Running the above test will ‘Pass’.
gfgobj toEqual
Another variation of doing this is matching two objects using the ‘toEqual’. This is done so like this :
test('check gfgObj toEqual', () => {
let gfgObj = {
name: "GFG",
type: "company",
members: {
employees: 100,
contributors: 500
}
};
let testObj = {
name: "GFG",
type: "company",
members: {
employees: 100,
contributors: 500
}
};
expect(gfgObj).toEqual(testObj);
});
This test demonstrates the deep-matching feature of toEqual. The above test passes as every key-pair in gfgObj matches with testObj.
gfgobj-testobj-toequal
toBeCloseTo – for floating point numbers and other approximate matches
//see here that a+b != c even though simple addition is taking place.
> var a = 1.32
> undefined
> var b = 2.31
> undefined
> c = a+b;
> 3.63
> var res = false;
> if(c==(a+b)) {c=true;}
> undefined
> c
> false
In such conditions, it is good to use ‘toBeCloseTo’ matcher from the Jest library.
test('floating point number - use toBeCloseTo instead', function() {
// const num1 = 0.3;
// const num2 = 0.2;
const result = 9.31 + 9.2;
expect(result).toBeCloseTo(18.51);
})
The above test passes too.
matching truthy and falsy: https://jestjs.io/docs/en/using-matchers#truthiness A lot of times, tests are written to check for truthy and falsy values returned by ‘expect’. Falsy values in JS. Truthy values in JS.
//checking for truthy values - All the tests will return truthy.
test('check for truthy', function() {
const gfgObj = {
first: null,
second: undefined,
third: false
}
expect(gfgObj.first).not.toBeTruthy(); // True - Pass
expect(gfgObj.second).toBeUndefined(); // True - Pass
expect(gfgObj.third).toBeFalsy(); // True - Pass
})
The above test passes.
truthy-test-js-all-test-passing
However, if any of the ‘expect’ above fails, Jest returns meaningful error messages like below.
Note that in above case, if any of the ‘expect’-s fail, the test also completely fails.
truthy-test-js-one-expect-failing-so-test-failing
Matching Numbers:
//tests for Number matches
test('test for numbers', function() {
const result = 3 + 9;
// expect(result).toBe(12); //the plain old matcher
expect(result).not.toBeLessThan(10); // result > 10
expect(result).toBeLessThan(15); // result < 15
expect(result).not.toBeGreaterThan(15); // result 10
expect(result).toBeGreaterThanOrEqual(12); //result >= 12
// expect(result).not.toBeGreaterThanOrEqual(12); // result == 12, this Fails
// expect(result).toBeLessThanOrEqual(10); // result >= 10, this Fails
})
number matching using jest
Testing values contained in arrays: We can also test if particular values are contained in an array. Note that this test will ‘Fail’ if at least one value is not present in the array. For example,
//testing arrays
const gfgUsers = [
'user1',
'user2',
'user3'
];
test('test for a value in gfgUsers', function() {
// expect(gfgUsers).toContain('user2');
// expect(gfgUsers).not.toContain('user2');
//expect array containing
expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user3']));
})
Th above test passes as user1 and user3 are present in gfgUsers.
user1-and-user3-in-gfgUsers
However, the following test will fail because ‘user4’ is not present in gfgUsers.
//testing arrays
const gfgUsers = [
'user1',
'user2',
'user3'
];
test('test for a value in gfgUsers', function() {
//expect array containing
expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user4']));
})
arraycontaining-fail-due-to-user4-absence
Testing using Regex:
test('string match tests - toMatch - used for regex-es', function() {
const str = 'GeeksforGeeks';
// expect(str).toMatch(/f/);
// expect(str).toMatch(/Z/);
//you can create more complex Regexes
const str1 = 'This is a test paragraph. I wrote it.'
expect(str1).toMatch(/[pP][hH][\.]/); //matches 'ph.' in the word 'paragraph'
})
tomatch-matching-ph-in-paragraph
Extending the Matchers Jest also has the provision to extend its ‘Matchers’ functionality, which is accomplished using the ‘expect.extend()’ keyword. The .extend() function is passed matchers as objects. Syntax: expect.extend({matcher1, matcher2}) ; For example, if we want to build a matcher that checks for a phrase presence in a string:
expect.extend({
stringPresent(receivedString, phraseString) {
bool phrasePresent = true;
var re = new RegExp(phraseString);
if (re.test(receivedString)) {
phrasePresent = true;
} else {
phrasePresent = false;
}
if (phrasePresent === true) {
return {
message: () =>
`string present`,
pass: true,
};
} else {
return {
message: () =>
`string absent`,
pass: false,
};
}
},
});
Dealing with exceptions We can also check the types of errors that a unit of code throws. We can check the error thrown by name, message, object, etc.
Syntax:expect( fnName() ).toThrow( error ); The error parameter/argument is optional here.
Let’s suppose that we want to test a function by the message of the error thrown.
function testGFGMessage() {
throw new Error('this is testGFGMessage function error');
}
test('testing testGFGMessage', function(){
expect(testGFGMessage).toThrow('this is testGFGMessage function error');
})
There are many other ways to throw Errors and check for them. A detailed reference can be found here.
Skipping/Running a subset of tests https://jestjs.io/docs/en/api#testskipname-fn Jest also has a provision for skipping specific tests while running the test suite. To implement it, simply use the ‘skip’ keyword. For example,
function addFn(num1, num2){
return num1 + num2;
}
test.skip('skip test example - skipping the addition test', () => {
expect(addFn(2, 3)).toBe(5);
});
The opposite of this is implementing only a subset of tests, which is achieved by using the ‘only’ keyword. For example,
function addFn(num1, num2){
return num1 + num2;
}
test.only('skip test example - skipping the addition test', () => {
expect(addFn(2, 3)).toBe(5);
});
saurabh1990aror
Technical Scripter 2019
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 249,
"s": 28,
"text": "Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code(usually, a function) and match the output with the expected output. "
},
{
"code": null,
"e": 266,
"s": 249,
"text": "Jest Features: "
},
{
"code": null,
"e": 477,
"s": 266,
"text": "zero config: As we will see later in this article, close to none configuration is required to get started with writing tests and deploying them. However, a config file can be supplied to the test suite as well."
},
{
"code": null,
"e": 646,
"s": 477,
"text": "snapshots: Jest has the ability to enable snapshot testing as well. Essentially, the snapshots are matched with the saved snapshot and check for matching functionality."
},
{
"code": null,
"e": 713,
"s": 646,
"text": "isolated tests: Jest tests are run parallelly to improve run time."
},
{
"code": null,
"e": 741,
"s": 713,
"text": "Setting up a jest project "
},
{
"code": null,
"e": 767,
"s": 741,
"text": "Install Jest using npm: "
},
{
"code": null,
"e": 832,
"s": 767,
"text": "npm install jest. The -D keyword installs jest as dev dependency"
},
{
"code": null,
"e": 1171,
"s": 832,
"text": "Project Structure: In the project root directory, make a tests folder. This folder will store all the test files. Note that the js files(which are to be tested) are mapped by their names. For example, index.js is mapped to index.test.js. This index.test.js file is placed in the ‘tests’ folder. This is the conventional project structure."
},
{
"code": null,
"e": 1188,
"s": 1171,
"text": "Start testing: "
},
{
"code": null,
"e": 1232,
"s": 1188,
"text": "To start, lets see a basic test workflow. "
},
{
"code": null,
"e": 1259,
"s": 1232,
"text": "test – adding two pos nums"
},
{
"code": null,
"e": 1293,
"s": 1259,
"text": "To run the test, use the script "
},
{
"code": null,
"e": 1306,
"s": 1293,
"text": "npm run test"
},
{
"code": null,
"e": 1389,
"s": 1306,
"text": "This will look for the test script mentioned in the package.json of the project. "
},
{
"code": null,
"e": 1434,
"s": 1389,
"text": "pkg-json-test-script-ss. See test in scripts"
},
{
"code": null,
"e": 1550,
"s": 1434,
"text": "We will use the ‘expect’ method to test our functions. The functions can also be tested using ‘describe’ and ‘it’. "
},
{
"code": null,
"e": 1612,
"s": 1550,
"text": "A basic test: adding two positive nums and checking result. "
},
{
"code": null,
"e": 1783,
"s": 1612,
"text": "//index.js\ntestForAdd: (a, b) => { return (a + b) },\n\n//index.test.js\ntest('test adding two positive nums', function() {\n expect(testFns.testForAdd(4, 5)).toBe(9);\n});"
},
{
"code": null,
"e": 2079,
"s": 1783,
"text": "When the ‘npm run test’ is run, the index.test.js file is gone through. Then the testForAdd function is run which is placed in the ‘testFns’ object. The toBe is used to ‘match’ the returned response from the test to what is expected. This ‘result matching’ leads to either a ‘fail’ or a ‘pass’. "
},
{
"code": null,
"e": 2106,
"s": 2081,
"text": "test adding two pos nums"
},
{
"code": null,
"e": 2163,
"s": 2106,
"text": "The following test will fail because of the ‘toBe(8)’. "
},
{
"code": null,
"e": 2310,
"s": 2163,
"text": "//example of a failing test\n test('test adding two positive nums - failing test', function() {\n expect(testFns.testForAdd(4, 5)).toBe(8);\n });"
},
{
"code": null,
"e": 2435,
"s": 2310,
"text": "Opposite of toBe: not.toBe() The opposite of the ‘toBe’ matcher is created by simply prefixing it with ‘not.’ For example: "
},
{
"code": null,
"e": 2681,
"s": 2435,
"text": "//test successful - test for opposite of a matcher.\n//The following test will 'Pass' if the returned value is not equal to 8.\ntest('test adding two positive nums - failing test', function() {\n expect(testFns.testForAdd(4, 5)).not.toBe(8);\n});"
},
{
"code": null,
"e": 2913,
"s": 2681,
"text": "Using ‘toBe’ with JS Objects: Let’s think of a case where every field of a JS object is to be tested. Jest provides us a way to do this using ‘toEqual’. The ‘toEqual’ is a deep-matcher(checks every field and sub-fields possible). "
},
{
"code": null,
"e": 3167,
"s": 2913,
"text": "//expect toEqual example - check every field's value\n// testFns.test_toEqual(gfgObj)\ntest('check gfgObj toEqual', () => {\n let gfgObj = { name: \"GFG\" };\n gfgObj['type'] = \"company\";\n expect(gfgObj).toEqual({ name: \"GFG\", type: \"company\" });\n});"
},
{
"code": null,
"e": 3205,
"s": 3167,
"text": "Running the above test will ‘Pass’. "
},
{
"code": null,
"e": 3220,
"s": 3205,
"text": "gfgobj toEqual"
},
{
"code": null,
"e": 3327,
"s": 3220,
"text": "Another variation of doing this is matching two objects using the ‘toEqual’. This is done so like this : "
},
{
"code": null,
"e": 3725,
"s": 3327,
"text": "test('check gfgObj toEqual', () => {\n let gfgObj = {\n name: \"GFG\",\n type: \"company\",\n members: {\n employees: 100,\n contributors: 500\n }\n };\n\n let testObj = {\n name: \"GFG\",\n type: \"company\",\n members: {\n employees: 100,\n contributors: 500\n }\n };\n expect(gfgObj).toEqual(testObj);\n});"
},
{
"code": null,
"e": 3860,
"s": 3725,
"text": "This test demonstrates the deep-matching feature of toEqual. The above test passes as every key-pair in gfgObj matches with testObj. "
},
{
"code": null,
"e": 3883,
"s": 3860,
"text": "gfgobj-testobj-toequal"
},
{
"code": null,
"e": 3956,
"s": 3883,
"text": "toBeCloseTo – for floating point numbers and other approximate matches "
},
{
"code": null,
"e": 4166,
"s": 3956,
"text": "//see here that a+b != c even though simple addition is taking place.\n> var a = 1.32\n> undefined\n> var b = 2.31\n> undefined\n> c = a+b;\n> 3.63\n> var res = false;\n> if(c==(a+b)) {c=true;}\n> undefined\n> c\n> false"
},
{
"code": null,
"e": 4251,
"s": 4166,
"text": "In such conditions, it is good to use ‘toBeCloseTo’ matcher from the Jest library. "
},
{
"code": null,
"e": 4444,
"s": 4251,
"text": "test('floating point number - use toBeCloseTo instead', function() {\n // const num1 = 0.3;\n // const num2 = 0.2;\n const result = 9.31 + 9.2;\n\n expect(result).toBeCloseTo(18.51);\n})"
},
{
"code": null,
"e": 4472,
"s": 4444,
"text": "The above test passes too. "
},
{
"code": null,
"e": 4687,
"s": 4472,
"text": "matching truthy and falsy: https://jestjs.io/docs/en/using-matchers#truthiness A lot of times, tests are written to check for truthy and falsy values returned by ‘expect’. Falsy values in JS. Truthy values in JS. "
},
{
"code": null,
"e": 5063,
"s": 4687,
"text": "//checking for truthy values - All the tests will return truthy.\ntest('check for truthy', function() {\n const gfgObj = {\n first: null,\n second: undefined,\n third: false\n }\n expect(gfgObj.first).not.toBeTruthy(); // True - Pass\n expect(gfgObj.second).toBeUndefined(); // True - Pass\n expect(gfgObj.third).toBeFalsy(); // True - Pass\n})"
},
{
"code": null,
"e": 5088,
"s": 5063,
"text": "The above test passes. "
},
{
"code": null,
"e": 5120,
"s": 5088,
"text": "truthy-test-js-all-test-passing"
},
{
"code": null,
"e": 5217,
"s": 5120,
"text": "However, if any of the ‘expect’ above fails, Jest returns meaningful error messages like below. "
},
{
"code": null,
"e": 5307,
"s": 5217,
"text": "Note that in above case, if any of the ‘expect’-s fail, the test also completely fails. "
},
{
"code": null,
"e": 5357,
"s": 5307,
"text": "truthy-test-js-one-expect-failing-so-test-failing"
},
{
"code": null,
"e": 5377,
"s": 5357,
"text": "Matching Numbers: "
},
{
"code": null,
"e": 5914,
"s": 5377,
"text": "//tests for Number matches\ntest('test for numbers', function() {\n const result = 3 + 9;\n // expect(result).toBe(12); //the plain old matcher\n expect(result).not.toBeLessThan(10); // result > 10\n expect(result).toBeLessThan(15); // result < 15\n expect(result).not.toBeGreaterThan(15); // result 10\n expect(result).toBeGreaterThanOrEqual(12); //result >= 12\n // expect(result).not.toBeGreaterThanOrEqual(12); // result == 12, this Fails\n // expect(result).toBeLessThanOrEqual(10); // result >= 10, this Fails\n})"
},
{
"code": null,
"e": 5943,
"s": 5916,
"text": "number matching using jest"
},
{
"code": null,
"e": 6142,
"s": 5943,
"text": "Testing values contained in arrays: We can also test if particular values are contained in an array. Note that this test will ‘Fail’ if at least one value is not present in the array. For example, "
},
{
"code": null,
"e": 6469,
"s": 6142,
"text": "//testing arrays\nconst gfgUsers = [\n 'user1',\n 'user2',\n 'user3'\n];\ntest('test for a value in gfgUsers', function() {\n // expect(gfgUsers).toContain('user2');\n // expect(gfgUsers).not.toContain('user2');\n //expect array containing\n expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user3']));\n})"
},
{
"code": null,
"e": 6536,
"s": 6469,
"text": "Th above test passes as user1 and user3 are present in gfgUsers. "
},
{
"code": null,
"e": 6564,
"s": 6536,
"text": "user1-and-user3-in-gfgUsers"
},
{
"code": null,
"e": 6648,
"s": 6564,
"text": "However, the following test will fail because ‘user4’ is not present in gfgUsers. "
},
{
"code": null,
"e": 6883,
"s": 6648,
"text": "//testing arrays\nconst gfgUsers = [\n 'user1',\n 'user2',\n 'user3'\n];\ntest('test for a value in gfgUsers', function() {\n //expect array containing\n expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user4']));\n})"
},
{
"code": null,
"e": 6927,
"s": 6885,
"text": "arraycontaining-fail-due-to-user4-absence"
},
{
"code": null,
"e": 6950,
"s": 6927,
"text": "Testing using Regex: "
},
{
"code": null,
"e": 7304,
"s": 6950,
"text": "test('string match tests - toMatch - used for regex-es', function() {\n const str = 'GeeksforGeeks';\n // expect(str).toMatch(/f/);\n // expect(str).toMatch(/Z/);\n //you can create more complex Regexes\n const str1 = 'This is a test paragraph. I wrote it.'\n expect(str1).toMatch(/[pP][hH][\\.]/); //matches 'ph.' in the word 'paragraph'\n})"
},
{
"code": null,
"e": 7339,
"s": 7306,
"text": "tomatch-matching-ph-in-paragraph"
},
{
"code": null,
"e": 7681,
"s": 7339,
"text": "Extending the Matchers Jest also has the provision to extend its ‘Matchers’ functionality, which is accomplished using the ‘expect.extend()’ keyword. The .extend() function is passed matchers as objects. Syntax: expect.extend({matcher1, matcher2}) ; For example, if we want to build a matcher that checks for a phrase presence in a string: "
},
{
"code": null,
"e": 8146,
"s": 7681,
"text": "expect.extend({\nstringPresent(receivedString, phraseString) {\nbool phrasePresent = true;\nvar re = new RegExp(phraseString);\nif (re.test(receivedString)) {\n phrasePresent = true;\n} else {\n phrasePresent = false;\n}\nif (phrasePresent === true) {\n return {\n message: () =>\n `string present`,\n pass: true,\n };\n } else {\n return {\n message: () =>\n `string absent`,\n pass: false,\n };\n }\n},\n});"
},
{
"code": null,
"e": 8298,
"s": 8146,
"text": "Dealing with exceptions We can also check the types of errors that a unit of code throws. We can check the error thrown by name, message, object, etc. "
},
{
"code": null,
"e": 8390,
"s": 8298,
"text": "Syntax:expect( fnName() ).toThrow( error ); The error parameter/argument is optional here. "
},
{
"code": null,
"e": 8474,
"s": 8390,
"text": "Let’s suppose that we want to test a function by the message of the error thrown. "
},
{
"code": null,
"e": 8685,
"s": 8474,
"text": "function testGFGMessage() {\n throw new Error('this is testGFGMessage function error');\n}\ntest('testing testGFGMessage', function(){\n expect(testGFGMessage).toThrow('this is testGFGMessage function error');\n})"
},
{
"code": null,
"e": 8788,
"s": 8685,
"text": "There are many other ways to throw Errors and check for them. A detailed reference can be found here. "
},
{
"code": null,
"e": 9016,
"s": 8788,
"text": "Skipping/Running a subset of tests https://jestjs.io/docs/en/api#testskipname-fn Jest also has a provision for skipping specific tests while running the test suite. To implement it, simply use the ‘skip’ keyword. For example, "
},
{
"code": null,
"e": 9172,
"s": 9016,
"text": "function addFn(num1, num2){\n return num1 + num2;\n}\n\ntest.skip('skip test example - skipping the addition test', () => {\n expect(addFn(2, 3)).toBe(5);\n});"
},
{
"code": null,
"e": 9295,
"s": 9172,
"text": "The opposite of this is implementing only a subset of tests, which is achieved by using the ‘only’ keyword. For example, "
},
{
"code": null,
"e": 9451,
"s": 9295,
"text": "function addFn(num1, num2){\n return num1 + num2;\n}\n\ntest.only('skip test example - skipping the addition test', () => {\n expect(addFn(2, 3)).toBe(5);\n});"
},
{
"code": null,
"e": 9469,
"s": 9453,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 9493,
"s": 9469,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 9512,
"s": 9493,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9529,
"s": 9512,
"text": "Web Technologies"
},
{
"code": null,
"e": 9627,
"s": 9529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9689,
"s": 9627,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 9722,
"s": 9689,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 9783,
"s": 9722,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9833,
"s": 9783,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 9876,
"s": 9833,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 9948,
"s": 9876,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 9988,
"s": 9948,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 10012,
"s": 9988,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 10045,
"s": 10012,
"text": "Node.js fs.readFileSync() Method"
}
] |
PHP | list() Function
|
03 Jun, 2020
The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. This function will only work on numerical arrays. When the array is assigned to multiple values, then the first element in the array is assigned to the first variable, second to the second variable, and so on, till the number of variables. The number of variables cannot exceed the length of the numerical array.
Syntax:
list($variable1, $variable2....)
Parameter: It accepts a list of variables separated by spaces. These variables are assigned values. At least one variable must be passed to the function.
Return Value: The function returns the assigned array to the multiple variables passed. If the number of variables passed is greater than the number of elements in the array, an error is thrown.
Below programs illustrate the list() function in PHP:
Program 1: Program to demonstrate the use of list() function.
<?php // PHP program to demonstrate the // use of list() function $array = array(1, 2, 3, 4); // Assign array values to variables list($a, $b, $c) = $array; // print all assigned values echo "a =", ($a), "\n";echo " b =", ($b), "\n";echo " c =", ($c), "\n"; // Perform multiplication of// those assigned numbersecho "a*b*c =", ($a*$b*$c); ?>
Output:
a =1
b =2
c =3
a*b*c =6
Program 2: Program to demonstrate the runtime error of list() function.
<?php // PHP program to demonstrate the // runtime error of list() function $array = array(1, 2, 3, 4); // assign array values to variables list($a, $b, $c, $d, $e) = $array; ?>
Output:
PHP Notice: Undefined offset: 4 in
/home/619f1441636b952bbd400f1e9e8e3d0c.php on line 6
Program 3: Program to demonstrate assignment of particular index values in the array to variables.
<?php // PHP program to demonstrate assignment of // particular index values in the array to // variables. $array = array(1, 2, 3, 4); // Assign array values to variables list(, , $a) = $array; // Print all assigned values echo " a = ", ($a), "\n"; ?>
Output:
a = 3
Reference:http://php.net/manual/en/function.list.php
ArkadyutiBanerjee
PHP-array
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 461,
"s": 28,
"text": "The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. This function will only work on numerical arrays. When the array is assigned to multiple values, then the first element in the array is assigned to the first variable, second to the second variable, and so on, till the number of variables. The number of variables cannot exceed the length of the numerical array."
},
{
"code": null,
"e": 469,
"s": 461,
"text": "Syntax:"
},
{
"code": null,
"e": 502,
"s": 469,
"text": "list($variable1, $variable2....)"
},
{
"code": null,
"e": 656,
"s": 502,
"text": "Parameter: It accepts a list of variables separated by spaces. These variables are assigned values. At least one variable must be passed to the function."
},
{
"code": null,
"e": 851,
"s": 656,
"text": "Return Value: The function returns the assigned array to the multiple variables passed. If the number of variables passed is greater than the number of elements in the array, an error is thrown."
},
{
"code": null,
"e": 905,
"s": 851,
"text": "Below programs illustrate the list() function in PHP:"
},
{
"code": null,
"e": 967,
"s": 905,
"text": "Program 1: Program to demonstrate the use of list() function."
},
{
"code": "<?php // PHP program to demonstrate the // use of list() function $array = array(1, 2, 3, 4); // Assign array values to variables list($a, $b, $c) = $array; // print all assigned values echo \"a =\", ($a), \"\\n\";echo \" b =\", ($b), \"\\n\";echo \" c =\", ($c), \"\\n\"; // Perform multiplication of// those assigned numbersecho \"a*b*c =\", ($a*$b*$c); ?>",
"e": 1317,
"s": 967,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1317,
"text": "Output:"
},
{
"code": null,
"e": 1352,
"s": 1325,
"text": " a =1\n b =2\n c =3\na*b*c =6"
},
{
"code": null,
"e": 1424,
"s": 1352,
"text": "Program 2: Program to demonstrate the runtime error of list() function."
},
{
"code": "<?php // PHP program to demonstrate the // runtime error of list() function $array = array(1, 2, 3, 4); // assign array values to variables list($a, $b, $c, $d, $e) = $array; ?>",
"e": 1606,
"s": 1424,
"text": null
},
{
"code": null,
"e": 1614,
"s": 1606,
"text": "Output:"
},
{
"code": null,
"e": 1705,
"s": 1614,
"text": "PHP Notice: Undefined offset: 4 in \n/home/619f1441636b952bbd400f1e9e8e3d0c.php on line 6\n"
},
{
"code": null,
"e": 1804,
"s": 1705,
"text": "Program 3: Program to demonstrate assignment of particular index values in the array to variables."
},
{
"code": "<?php // PHP program to demonstrate assignment of // particular index values in the array to // variables. $array = array(1, 2, 3, 4); // Assign array values to variables list(, , $a) = $array; // Print all assigned values echo \" a = \", ($a), \"\\n\"; ?>",
"e": 2063,
"s": 1804,
"text": null
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Output:"
},
{
"code": null,
"e": 2078,
"s": 2071,
"text": "a = 3\n"
},
{
"code": null,
"e": 2131,
"s": 2078,
"text": "Reference:http://php.net/manual/en/function.list.php"
},
{
"code": null,
"e": 2149,
"s": 2131,
"text": "ArkadyutiBanerjee"
},
{
"code": null,
"e": 2159,
"s": 2149,
"text": "PHP-array"
},
{
"code": null,
"e": 2163,
"s": 2159,
"text": "PHP"
},
{
"code": null,
"e": 2180,
"s": 2163,
"text": "Web Technologies"
},
{
"code": null,
"e": 2184,
"s": 2180,
"text": "PHP"
}
] |
Python String center() Method
|
Python string method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.
str.center(width[, fillchar])
width − This is the total width of the string.
width − This is the total width of the string.
fillchar − This is the filler character.
fillchar − This is the filler character.
This method returns centered in a string of length width.
The following example shows the usage of center() method.
#!/usr/bin/python
str = "this is string example....wow!!!"
print "str.center(40, 'a') : ", str.center(40, 'a')
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
|
[
{
"code": null,
"e": 2527,
"s": 2378,
"text": "Python string method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space."
},
{
"code": null,
"e": 2558,
"s": 2527,
"text": "str.center(width[, fillchar])\n"
},
{
"code": null,
"e": 2605,
"s": 2558,
"text": "width − This is the total width of the string."
},
{
"code": null,
"e": 2652,
"s": 2605,
"text": "width − This is the total width of the string."
},
{
"code": null,
"e": 2693,
"s": 2652,
"text": "fillchar − This is the filler character."
},
{
"code": null,
"e": 2734,
"s": 2693,
"text": "fillchar − This is the filler character."
},
{
"code": null,
"e": 2792,
"s": 2734,
"text": "This method returns centered in a string of length width."
},
{
"code": null,
"e": 2850,
"s": 2792,
"text": "The following example shows the usage of center() method."
},
{
"code": null,
"e": 2962,
"s": 2850,
"text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\"\nprint \"str.center(40, 'a') : \", str.center(40, 'a')"
}
] |
Dart – Symbols
|
09 May, 2021
In Dart, Symbols are basically an object representation of either an identifier or operator. The symbols in dart are opaque and dynamic string names that cannot be changed and remains constant throughout the compile time. It can be used for reflecting the metadata on a type, such as a library or class. They are generally used for creating APIs and establish a relationship between a string that is understandable to humans and a string that can be used by computers.
Symbols can be used to get various information about a type (library, class, etc) such as a list of instance methods, constructors, etc.
Symbols can be created in 2 different ways –
1. Adding a Hash (#) symbol to an identifier would convert it into a Symbol
print(#mysymbol);
Output:
Symbol("mysymbol")
2. Otherwise, a symbol can be created explicitly using the Class constructor.
Symbol mySymbol = Symbol('mysymbol');
print(mySymbol);
Output:
Symbol("mysymbol")
Example:
In this example, we’ll be creating a Custom Library and then show its metadata using Symbols.
Here, we have first created a Dart File Custom.dart containing a library custom_lib, which consists of a class called CustomClass having methods customFunction1 and customFunction2.
Dart
library custom_lib; class CustomClass { void customFunction1() { print("Custom Function 1"); } void customFunction2() { print("Custom Function 2"); }}
Next, we’ll create the main.dart file, which will import the Custom. dart file along with a couple of other libraries such as dart:core and dart:mirror
First, we’ll create 2 symbols. One for the custom library and the other for the custom class.
Next, we’ve to initialize the mirror system, and create a mirror reference to our custom_lib library, and then using that, to our CustomClass class.
Using classMirror, we can now extract some data i.e. a list of methods present in our class. That includes –User created methods such as customFunction1In-build methods such as toString
User created methods such as customFunction1
In-build methods such as toString
Dart
import 'dart:core';import 'dart:mirrors';import 'Custom.dart'; void main() { // Create symbols for library and class Symbol libraryName = Symbol('custom_lib'); Symbol className = Symbol('CustomClass'); // Init mirror system MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); ClassMirror classMirror = libMirror.declarations[className]; // Get and print methods final methods = classMirror.instanceMembers; print('Total number of methods = ${methods.length}'); methods.forEach((symbol, method) { print(symbol); });}
Output:
Total number of methods = 7
Symbol("==")
Symbol("hashCode")
Symbol("toString")
Symbol("noSuchMethod")
Symbol("runtimeType")
Symbol("customFunction1")
Symbol("customFunction2")
Dart-basics
Picked
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 498,
"s": 28,
"text": "In Dart, Symbols are basically an object representation of either an identifier or operator. The symbols in dart are opaque and dynamic string names that cannot be changed and remains constant throughout the compile time. It can be used for reflecting the metadata on a type, such as a library or class. They are generally used for creating APIs and establish a relationship between a string that is understandable to humans and a string that can be used by computers."
},
{
"code": null,
"e": 635,
"s": 498,
"text": "Symbols can be used to get various information about a type (library, class, etc) such as a list of instance methods, constructors, etc."
},
{
"code": null,
"e": 680,
"s": 635,
"text": "Symbols can be created in 2 different ways –"
},
{
"code": null,
"e": 756,
"s": 680,
"text": "1. Adding a Hash (#) symbol to an identifier would convert it into a Symbol"
},
{
"code": null,
"e": 774,
"s": 756,
"text": "print(#mysymbol);"
},
{
"code": null,
"e": 782,
"s": 774,
"text": "Output:"
},
{
"code": null,
"e": 801,
"s": 782,
"text": "Symbol(\"mysymbol\")"
},
{
"code": null,
"e": 879,
"s": 801,
"text": "2. Otherwise, a symbol can be created explicitly using the Class constructor."
},
{
"code": null,
"e": 934,
"s": 879,
"text": "Symbol mySymbol = Symbol('mysymbol');\nprint(mySymbol);"
},
{
"code": null,
"e": 942,
"s": 934,
"text": "Output:"
},
{
"code": null,
"e": 961,
"s": 942,
"text": "Symbol(\"mysymbol\")"
},
{
"code": null,
"e": 970,
"s": 961,
"text": "Example:"
},
{
"code": null,
"e": 1064,
"s": 970,
"text": "In this example, we’ll be creating a Custom Library and then show its metadata using Symbols."
},
{
"code": null,
"e": 1247,
"s": 1064,
"text": "Here, we have first created a Dart File Custom.dart containing a library custom_lib, which consists of a class called CustomClass having methods customFunction1 and customFunction2."
},
{
"code": null,
"e": 1252,
"s": 1247,
"text": "Dart"
},
{
"code": "library custom_lib; class CustomClass { void customFunction1() { print(\"Custom Function 1\"); } void customFunction2() { print(\"Custom Function 2\"); }}",
"e": 1416,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1416,
"text": "Next, we’ll create the main.dart file, which will import the Custom. dart file along with a couple of other libraries such as dart:core and dart:mirror"
},
{
"code": null,
"e": 1662,
"s": 1568,
"text": "First, we’ll create 2 symbols. One for the custom library and the other for the custom class."
},
{
"code": null,
"e": 1811,
"s": 1662,
"text": "Next, we’ve to initialize the mirror system, and create a mirror reference to our custom_lib library, and then using that, to our CustomClass class."
},
{
"code": null,
"e": 1997,
"s": 1811,
"text": "Using classMirror, we can now extract some data i.e. a list of methods present in our class. That includes –User created methods such as customFunction1In-build methods such as toString"
},
{
"code": null,
"e": 2042,
"s": 1997,
"text": "User created methods such as customFunction1"
},
{
"code": null,
"e": 2076,
"s": 2042,
"text": "In-build methods such as toString"
},
{
"code": null,
"e": 2081,
"s": 2076,
"text": "Dart"
},
{
"code": "import 'dart:core';import 'dart:mirrors';import 'Custom.dart'; void main() { // Create symbols for library and class Symbol libraryName = Symbol('custom_lib'); Symbol className = Symbol('CustomClass'); // Init mirror system MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); ClassMirror classMirror = libMirror.declarations[className]; // Get and print methods final methods = classMirror.instanceMembers; print('Total number of methods = ${methods.length}'); methods.forEach((symbol, method) { print(symbol); });}",
"e": 2685,
"s": 2081,
"text": null
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Output:"
},
{
"code": null,
"e": 2869,
"s": 2693,
"text": "Total number of methods = 7\nSymbol(\"==\")\nSymbol(\"hashCode\")\nSymbol(\"toString\")\nSymbol(\"noSuchMethod\")\nSymbol(\"runtimeType\")\nSymbol(\"customFunction1\")\nSymbol(\"customFunction2\")"
},
{
"code": null,
"e": 2881,
"s": 2869,
"text": "Dart-basics"
},
{
"code": null,
"e": 2888,
"s": 2881,
"text": "Picked"
},
{
"code": null,
"e": 2893,
"s": 2888,
"text": "Dart"
}
] |
GATE | GATE-CS-2014-(Set-2) | Question 65
|
28 Jun, 2021
Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1?
T(n) = 2T(n/2) + Logn
(A) Θ(n)(B) Θ(nLogn)(C) Θ(n*n)(D) Θ(log n)Answer: (A)Explanation:
T(n) = 2T(n/2) + log n
T(1) = 1
Substitute n = 2^k
T(2^k) = k + 2T(2^(k-1))
T(2^k) = k + 2(k-1) + 4T(2^(k-2))
= k + 2(k-1) + 4(K-2) + 8T(2^(k-3))
= k + 2(k-1) + 4(K-2) + 8(k-3) + 16T(2^(k-4))
= k + 2(k-1) + 4(K-2) + 8(k-3) + ...... + 2^kT(2^(k-k))
= k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^kT(1)
= k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^k --------(1)
2T(2^k) = 2k + 4(k-1) + 8(K-2) + ...... + 2*2^k + 2^(k+1) --------(2)
Subtracting 1 from 2, we get below
T(2^k) = - k + 2 + 4 ...... 2^(k-2) + 2^(k-1) + 2^k + 2^(k+1)
= - k + 2 * (1 + 2 + 4 + ..... 2^k)
= -k + [2*(2^k - 1)] / [2-1]
= -k + [2*(2^k - 1)]
T(n) = -Logn + 2*(n - 1)
T(n) = Θ(n)
Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 157,
"s": 54,
"text": "Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1?"
},
{
"code": null,
"e": 180,
"s": 157,
"text": "T(n) = 2T(n/2) + Logn "
},
{
"code": null,
"e": 246,
"s": 180,
"text": "(A) Θ(n)(B) Θ(nLogn)(C) Θ(n*n)(D) Θ(log n)Answer: (A)Explanation:"
},
{
"code": null,
"e": 988,
"s": 246,
"text": " T(n) = 2T(n/2) + log n\n T(1) = 1\nSubstitute n = 2^k\n\nT(2^k) = k + 2T(2^(k-1))\nT(2^k) = k + 2(k-1) + 4T(2^(k-2))\n = k + 2(k-1) + 4(K-2) + 8T(2^(k-3))\n = k + 2(k-1) + 4(K-2) + 8(k-3) + 16T(2^(k-4))\n = k + 2(k-1) + 4(K-2) + 8(k-3) + ...... + 2^kT(2^(k-k))\n = k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^kT(1)\n = k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^k --------(1)\n\n2T(2^k) = 2k + 4(k-1) + 8(K-2) + ...... + 2*2^k + 2^(k+1) --------(2)\n\nSubtracting 1 from 2, we get below\nT(2^k) = - k + 2 + 4 ...... 2^(k-2) + 2^(k-1) + 2^k + 2^(k+1)\n = - k + 2 * (1 + 2 + 4 + ..... 2^k)\n = -k + [2*(2^k - 1)] / [2-1]\n = -k + [2*(2^k - 1)]\n\nT(n) = -Logn + 2*(n - 1)\n\nT(n) = Θ(n) "
},
{
"code": null,
"e": 1010,
"s": 988,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1031,
"s": 1010,
"text": "GATE-CS-2014-(Set-2)"
},
{
"code": null,
"e": 1057,
"s": 1031,
"text": "GATE-GATE-CS-2014-(Set-2)"
},
{
"code": null,
"e": 1062,
"s": 1057,
"text": "GATE"
}
] |
Plotting multiple bar charts using Matplotlib in Python
|
25 Feb, 2021
A multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many customizations such as Multiple bar plots, stacked bar plots, horizontal bar charts. Multiple bar charts are generally used for comparing different entities. In this article, plotting multiple bar charts are discussed.
Example 1: Simple multiple bar chart
In this example we will see how to plot multiple bar charts using matplotlib, here we are plotting multiple bar charts to visualize the number of boys and girls in each Group.
Approach:
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The data for plotting multiple bar charts are taken into the list.The np.arange( ) function from numpy library is used to create a range of values. We are creating the X-axis values depending on the number of groups in our example.Plotting the multiple bars using plt.bar( ) function.To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis.The width of the bars of each group is taken as 0.4 units.Finally, the multiple bar charts for both boys and girls are plotted in each group.
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
The data for plotting multiple bar charts are taken into the list.
The np.arange( ) function from numpy library is used to create a range of values. We are creating the X-axis values depending on the number of groups in our example.
Plotting the multiple bars using plt.bar( ) function.
To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis.
The width of the bars of each group is taken as 0.4 units.
Finally, the multiple bar charts for both boys and girls are plotted in each group.
Code:
Python3
import numpy as np import matplotlib.pyplot as plt X = ['Group A','Group B','Group C','Group D']Ygirls = [10,20,20,40]Zboys = [20,30,25,30] X_axis = np.arange(len(X)) plt.bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls')plt.bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys') plt.xticks(X_axis, X)plt.xlabel("Groups")plt.ylabel("Number of Students")plt.title("Number of Students in each group")plt.legend()plt.show()
Output :
Example 2: Number of Men and Women voted from 2018-2021
Approach :
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The Men and Women data for multiple bar charts are taken into a list for easy plotting.The np.arange( ) function from numpy library is used to create a range of values.Plotting the multiple bars using plt.bar( ) function in matplotlib library.To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the X-axis in this example.The width of the bars of each group is taken as 0.25 units.The X-axis labels(Years) and x-ticks are plotted as required in our visualization.Finally, the multiple bar chart for the number of men and women who voted every year is plotted.
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
The Men and Women data for multiple bar charts are taken into a list for easy plotting.
The np.arange( ) function from numpy library is used to create a range of values.
Plotting the multiple bars using plt.bar( ) function in matplotlib library.
To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the X-axis in this example.
The width of the bars of each group is taken as 0.25 units.
The X-axis labels(Years) and x-ticks are plotted as required in our visualization.
Finally, the multiple bar chart for the number of men and women who voted every year is plotted.
Code:
Python3
import numpy as npimport matplotlib.pyplot as plt Women = [115, 215, 250, 200]Men = [114, 230, 510, 370] n=4r = np.arange(n)width = 0.25 plt.bar(r, Women, color = 'b', width = width, edgecolor = 'black', label='Women')plt.bar(r + width, Men, color = 'g', width = width, edgecolor = 'black', label='Men') plt.xlabel("Year")plt.ylabel("Number of people voted")plt.title("Number of people voted in each year") # plt.grid(linestyle='--')plt.xticks(r + width/2,['2018','2019','2020','2021'])plt.legend() plt.show()
Output :
Example3: Scores of different players on different dates
Approach:
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The np.arange( ) function from numpy library is used to create a range of values(Here, 3 values).Plotting the multiple bars using plt.bar( ) function in matplotlib library. In this Example, Dates are plotted on X-axis and Players Scores on Y-axis.To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the previous bar.The width of the bars of each group is taken as 0.25 units with different colors.The X-axis labels and x-ticks are plotted as required in our visualization.Finally, the multiple bar chart for the Scores of different players on different dates is plotted.
Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
The np.arange( ) function from numpy library is used to create a range of values(Here, 3 values).
Plotting the multiple bars using plt.bar( ) function in matplotlib library. In this Example, Dates are plotted on X-axis and Players Scores on Y-axis.
To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the previous bar.
The width of the bars of each group is taken as 0.25 units with different colors.
The X-axis labels and x-ticks are plotted as required in our visualization.
Finally, the multiple bar chart for the Scores of different players on different dates is plotted.
Code:
Python3
import numpy as npimport matplotlib.pyplot as plt N = 3ind = np.arange(N) width = 0.25 xvals = [8, 9, 2]bar1 = plt.bar(ind, xvals, width, color = 'r') yvals = [10, 20, 30]bar2 = plt.bar(ind+width, yvals, width, color='g') zvals = [11, 12, 13]bar3 = plt.bar(ind+width*2, zvals, width, color = 'b') plt.xlabel("Dates")plt.ylabel('Scores')plt.title("Players Score") plt.xticks(ind+width,['2021Feb01', '2021Feb02', '2021Feb03'])plt.legend( (bar1, bar2, bar3), ('Player1', 'Player2', 'Player3') )plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 363,
"s": 52,
"text": "A multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many customizations such as Multiple bar plots, stacked bar plots, horizontal bar charts. Multiple bar charts are generally used for comparing different entities. In this article, plotting multiple bar charts are discussed."
},
{
"code": null,
"e": 400,
"s": 363,
"text": "Example 1: Simple multiple bar chart"
},
{
"code": null,
"e": 576,
"s": 400,
"text": "In this example we will see how to plot multiple bar charts using matplotlib, here we are plotting multiple bar charts to visualize the number of boys and girls in each Group."
},
{
"code": null,
"e": 586,
"s": 576,
"text": "Approach:"
},
{
"code": null,
"e": 1253,
"s": 586,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The data for plotting multiple bar charts are taken into the list.The np.arange( ) function from numpy library is used to create a range of values. We are creating the X-axis values depending on the number of groups in our example.Plotting the multiple bars using plt.bar( ) function.To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis.The width of the bars of each group is taken as 0.4 units.Finally, the multiple bar charts for both boys and girls are plotted in each group."
},
{
"code": null,
"e": 1388,
"s": 1253,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data."
},
{
"code": null,
"e": 1455,
"s": 1388,
"text": "The data for plotting multiple bar charts are taken into the list."
},
{
"code": null,
"e": 1621,
"s": 1455,
"text": "The np.arange( ) function from numpy library is used to create a range of values. We are creating the X-axis values depending on the number of groups in our example."
},
{
"code": null,
"e": 1675,
"s": 1621,
"text": "Plotting the multiple bars using plt.bar( ) function."
},
{
"code": null,
"e": 1783,
"s": 1675,
"text": "To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis."
},
{
"code": null,
"e": 1842,
"s": 1783,
"text": "The width of the bars of each group is taken as 0.4 units."
},
{
"code": null,
"e": 1926,
"s": 1842,
"text": "Finally, the multiple bar charts for both boys and girls are plotted in each group."
},
{
"code": null,
"e": 1932,
"s": 1926,
"text": "Code:"
},
{
"code": null,
"e": 1940,
"s": 1932,
"text": "Python3"
},
{
"code": "import numpy as np import matplotlib.pyplot as plt X = ['Group A','Group B','Group C','Group D']Ygirls = [10,20,20,40]Zboys = [20,30,25,30] X_axis = np.arange(len(X)) plt.bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls')plt.bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys') plt.xticks(X_axis, X)plt.xlabel(\"Groups\")plt.ylabel(\"Number of Students\")plt.title(\"Number of Students in each group\")plt.legend()plt.show()",
"e": 2354,
"s": 1940,
"text": null
},
{
"code": null,
"e": 2363,
"s": 2354,
"text": "Output :"
},
{
"code": null,
"e": 2419,
"s": 2363,
"text": "Example 2: Number of Men and Women voted from 2018-2021"
},
{
"code": null,
"e": 2430,
"s": 2419,
"text": "Approach :"
},
{
"code": null,
"e": 3153,
"s": 2430,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The Men and Women data for multiple bar charts are taken into a list for easy plotting.The np.arange( ) function from numpy library is used to create a range of values.Plotting the multiple bars using plt.bar( ) function in matplotlib library.To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the X-axis in this example.The width of the bars of each group is taken as 0.25 units.The X-axis labels(Years) and x-ticks are plotted as required in our visualization.Finally, the multiple bar chart for the number of men and women who voted every year is plotted."
},
{
"code": null,
"e": 3288,
"s": 3153,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data."
},
{
"code": null,
"e": 3376,
"s": 3288,
"text": "The Men and Women data for multiple bar charts are taken into a list for easy plotting."
},
{
"code": null,
"e": 3458,
"s": 3376,
"text": "The np.arange( ) function from numpy library is used to create a range of values."
},
{
"code": null,
"e": 3534,
"s": 3458,
"text": "Plotting the multiple bars using plt.bar( ) function in matplotlib library."
},
{
"code": null,
"e": 3643,
"s": 3534,
"text": "To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the X-axis in this example."
},
{
"code": null,
"e": 3703,
"s": 3643,
"text": "The width of the bars of each group is taken as 0.25 units."
},
{
"code": null,
"e": 3786,
"s": 3703,
"text": "The X-axis labels(Years) and x-ticks are plotted as required in our visualization."
},
{
"code": null,
"e": 3883,
"s": 3786,
"text": "Finally, the multiple bar chart for the number of men and women who voted every year is plotted."
},
{
"code": null,
"e": 3889,
"s": 3883,
"text": "Code:"
},
{
"code": null,
"e": 3897,
"s": 3889,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt Women = [115, 215, 250, 200]Men = [114, 230, 510, 370] n=4r = np.arange(n)width = 0.25 plt.bar(r, Women, color = 'b', width = width, edgecolor = 'black', label='Women')plt.bar(r + width, Men, color = 'g', width = width, edgecolor = 'black', label='Men') plt.xlabel(\"Year\")plt.ylabel(\"Number of people voted\")plt.title(\"Number of people voted in each year\") # plt.grid(linestyle='--')plt.xticks(r + width/2,['2018','2019','2020','2021'])plt.legend() plt.show()",
"e": 4444,
"s": 3897,
"text": null
},
{
"code": null,
"e": 4453,
"s": 4444,
"text": "Output :"
},
{
"code": null,
"e": 4510,
"s": 4453,
"text": "Example3: Scores of different players on different dates"
},
{
"code": null,
"e": 4520,
"s": 4510,
"text": "Approach:"
},
{
"code": null,
"e": 5254,
"s": 4520,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.The np.arange( ) function from numpy library is used to create a range of values(Here, 3 values).Plotting the multiple bars using plt.bar( ) function in matplotlib library. In this Example, Dates are plotted on X-axis and Players Scores on Y-axis.To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the previous bar.The width of the bars of each group is taken as 0.25 units with different colors.The X-axis labels and x-ticks are plotted as required in our visualization.Finally, the multiple bar chart for the Scores of different players on different dates is plotted."
},
{
"code": null,
"e": 5389,
"s": 5254,
"text": "Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data."
},
{
"code": null,
"e": 5487,
"s": 5389,
"text": "The np.arange( ) function from numpy library is used to create a range of values(Here, 3 values)."
},
{
"code": null,
"e": 5638,
"s": 5487,
"text": "Plotting the multiple bars using plt.bar( ) function in matplotlib library. In this Example, Dates are plotted on X-axis and Players Scores on Y-axis."
},
{
"code": null,
"e": 5737,
"s": 5638,
"text": "To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the previous bar."
},
{
"code": null,
"e": 5819,
"s": 5737,
"text": "The width of the bars of each group is taken as 0.25 units with different colors."
},
{
"code": null,
"e": 5895,
"s": 5819,
"text": "The X-axis labels and x-ticks are plotted as required in our visualization."
},
{
"code": null,
"e": 5994,
"s": 5895,
"text": "Finally, the multiple bar chart for the Scores of different players on different dates is plotted."
},
{
"code": null,
"e": 6000,
"s": 5994,
"text": "Code:"
},
{
"code": null,
"e": 6008,
"s": 6000,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt N = 3ind = np.arange(N) width = 0.25 xvals = [8, 9, 2]bar1 = plt.bar(ind, xvals, width, color = 'r') yvals = [10, 20, 30]bar2 = plt.bar(ind+width, yvals, width, color='g') zvals = [11, 12, 13]bar3 = plt.bar(ind+width*2, zvals, width, color = 'b') plt.xlabel(\"Dates\")plt.ylabel('Scores')plt.title(\"Players Score\") plt.xticks(ind+width,['2021Feb01', '2021Feb02', '2021Feb03'])plt.legend( (bar1, bar2, bar3), ('Player1', 'Player2', 'Player3') )plt.show()",
"e": 6516,
"s": 6008,
"text": null
},
{
"code": null,
"e": 6524,
"s": 6516,
"text": "Output:"
},
{
"code": null,
"e": 6531,
"s": 6524,
"text": "Picked"
},
{
"code": null,
"e": 6549,
"s": 6531,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 6573,
"s": 6549,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6580,
"s": 6573,
"text": "Python"
},
{
"code": null,
"e": 6599,
"s": 6580,
"text": "Technical Scripter"
}
] |
How to Build an Instagram Like Custom RecyclerView in Android?
|
28 Nov, 2021
We have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Instagram like Custom RecyclerView in Android.
We will be building a simple application in which we will be displaying data from the Instagram profile, and we will be using an official Instagram API to load the data from user’s Instagram profile and display that data in a custom RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
// dependency for loading data from json file.
implementation ‘com.android.volley:volley:1.1.1’
// dependency for loading image from url.
implementation ‘com.squareup.picasso:picasso:2.71828’
// dependency for creating a circle image.
implementation ‘de.hdodenhof:circleimageview:3.1.0’
Step 3: Creating API for getting the data for generating API
Now for creating a basic display API for Instagram posts we will be creating an API for displaying this data. You may refer to the How to Generate API URL for Public Instagram Feeds in Android? Now we have created the URL with the access token and we will use this URL to get the JSON data.
Step 4: Adding permissions for the internet in the AndroidManifest.xml file
As we are loading data from the internet. For that, we will have to add the internet permissions to our AndroidManifest.xml file. Navigate to the app > AndroidManifest.xml file and add the below code to it.
XML
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--recycler view for displaying our Instagram posts--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVInstaFeeds" android:layout_width="match_parent" android:layout_height="match_parent" /> <!--progressbar for displaying our loading indicator--> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> </RelativeLayout>
Step 6: Creating a new layout file for displaying each item of our RecyclerView
Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as insta_feed_rv_item and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/idLLTopBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="4dp"> <!--circle image for displaying the user image--> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/idCVAuthor" android:layout_width="40dp" android:layout_height="40dp" android:layout_margin="5dp" /> <!--text view for displaying user name--> <TextView android:id="@+id/idTVAuthorName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="3dp" android:padding="3dp" android:text="geeks_for_geeks" android:textColor="@color/black" android:textStyle="bold" /> </LinearLayout> <!--image view to display the post image--> <ImageView android:id="@+id/idIVPost" android:layout_width="match_parent" android:layout_height="300dp" android:layout_below="@id/idLLTopBar" android:adjustViewBounds="true" android:scaleType="centerCrop" /> <!--text view to display likes count--> <TextView android:id="@+id/idTVLikes" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idIVPost" android:layout_margin="6dp" android:padding="5dp" android:text="likes" android:textColor="@color/black" android:textStyle="bold" /> <!--text view to display the caption in instagram post--> <TextView android:id="@+id/idTVPostDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVLikes" android:layout_margin="6dp" android:padding="5dp" android:textColor="@color/black" android:textSize="11sp" /> </RelativeLayout>
Step 7: Create a Modal Class to store data for our Feed
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as InstaModal.
Java
public class InstaModal { // variables for storing data // of our recycler view item private String id; private String media_type; private String permalink; private String media_url; private String username; private String caption; private String timestamp; public String getAuthor_url() { return author_url; } public void setAuthor_url(String author_url) { this.author_url = author_url; } public int getLikesCount() { return likesCount; } public void setLikesCount(int likesCount) { this.likesCount = likesCount; } private String author_url; private int likesCount; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMedia_type() { return media_type; } public void setMedia_type(String media_type) { this.media_type = media_type; } public String getPermalink() { return permalink; } public void setPermalink(String permalink) { this.permalink = permalink; } public String getMedia_url() { return media_url; } public void setMedia_url(String media_url) { this.media_url = media_url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public InstaModal(String id, String media_type, String permalink, String media_url, String username, String caption, String timestamp, String author_url, int likesCount) { this.id = id; this.media_type = media_type; this.permalink = permalink; this.media_url = media_url; this.username = username; this.caption = caption; this.timestamp = timestamp; this.author_url = author_url; this.likesCount = likesCount; }}
Step 8: Creating an Adapter class for setting this data to each item of our RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name it as InstagramFeedRVAdapter and add the below code to it.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class InstagramFeedRVAdapter extends RecyclerView.Adapter<InstagramFeedRVAdapter.ViewHolder> { private ArrayList<InstaModal> instaModalArrayList; private Context context; public InstagramFeedRVAdapter(ArrayList<InstaModal> instaModalArrayList, Context context) { this.instaModalArrayList = instaModalArrayList; this.context = context; } @NonNull @Override public InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout for item of recycler view item. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false); return new InstagramFeedRVAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) { InstaModal modal = instaModalArrayList.get(position); holder.authorTV.setText(modal.getUsername()); if (modal.getMedia_type().equals("IMAGE")) { Picasso.get().load(modal.getMedia_url()).into(holder.postIV); } holder.desctv.setText(modal.getCaption()); holder.likeTV.setText("" + modal.getLikesCount() + " likes"); Picasso.get().load(modal.getAuthor_url()).into(holder.authorIV); } @Override public int getItemCount() { return instaModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView authorIV; private TextView authorTV; private ImageView postIV; private TextView likeTV, desctv; public ViewHolder(@NonNull View itemView) { super(itemView); authorIV = itemView.findViewById(R.id.idCVAuthor); authorTV = itemView.findViewById(R.id.idTVAuthorName); postIV = itemView.findViewById(R.id.idIVPost); likeTV = itemView.findViewById(R.id.idTVLikes); desctv = itemView.findViewById(R.id.idTVPostDesc); } }}
Step 9: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our requestqueue, // array list, progressbar, edittext, // image button and our recycler view. private RequestQueue mRequestQueue; private ArrayList<InstaModal> instaModalArrayList; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views. progressBar = findViewById(R.id.idLoadingPB); instaModalArrayList = new ArrayList<>(); // calling method to load // data in recycler view. getInstagramData(); } private void getInstagramData() { // below line is use to initialize the variable for our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // below line is use to clear cache this will // be use when our data is being updated. mRequestQueue.getCache().clear(); // below is the url for getting data // from API in json format. String url = "Enter your URL"; // below line we are creating a new request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); try { JSONArray dataArray = response.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { // below line is to extract data from JSON file. JSONObject dataObj = dataArray.getJSONObject(i); String id = dataObj.getString("id"); String media_type = dataObj.getString("media_type"); String permalink = dataObj.getString("permalink"); String media_url = dataObj.getString("media_url"); String username = dataObj.getString("username"); String caption = dataObj.getString("caption"); String timestamp = dataObj.getString("timestamp"); // below line is to add a constant author image URL to our recycler view. String author_url = "https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B"; int likesCount = 100 + (i * 10); // below line is use to add data to our modal class. InstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount); // below line is use to add modal // class to our array list. instaModalArrayList.add(instaModal); // below line we are creating an adapter class and adding our array list in it. InstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this); RecyclerView instRV = findViewById(R.id.idRVInstaFeeds); // below line is for setting linear layout manager to our recycler view. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); // below line is to set layout manager to our recycler view. instRV.setLayoutManager(linearLayoutManager); // below line is to set adapter // to our recycler view. instRV.setAdapter(adapter); } } catch (JSONException e) { // handling error case. e.printStackTrace(); Toast.makeText(MainActivity.this, "Fail to get Data.." + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling error message. Toast.makeText(MainActivity.this, "Fail to get Data.." + error, Toast.LENGTH_SHORT).show(); } }); queue.add(jsonObjectRequest); }}
Now run your app and see the output of the app.
Check out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp/tree/InstagramCustomListVIew
kalrap615
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "We have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Instagram like Custom RecyclerView in Android. "
},
{
"code": null,
"e": 633,
"s": 221,
"text": "We will be building a simple application in which we will be displaying data from the Instagram profile, and we will be using an official Instagram API to load the data from user’s Instagram profile and display that data in a custom RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 662,
"s": 633,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 824,
"s": 662,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 885,
"s": 824,
"text": "Step 2: Add the below dependency in your build.gradle file "
},
{
"code": null,
"e": 1115,
"s": 885,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 1162,
"s": 1115,
"text": "// dependency for loading data from json file."
},
{
"code": null,
"e": 1211,
"s": 1162,
"text": "implementation ‘com.android.volley:volley:1.1.1’"
},
{
"code": null,
"e": 1253,
"s": 1211,
"text": "// dependency for loading image from url."
},
{
"code": null,
"e": 1307,
"s": 1253,
"text": "implementation ‘com.squareup.picasso:picasso:2.71828’"
},
{
"code": null,
"e": 1352,
"s": 1307,
"text": "// dependency for creating a circle image. "
},
{
"code": null,
"e": 1404,
"s": 1352,
"text": "implementation ‘de.hdodenhof:circleimageview:3.1.0’"
},
{
"code": null,
"e": 1466,
"s": 1404,
"text": "Step 3: Creating API for getting the data for generating API "
},
{
"code": null,
"e": 1759,
"s": 1466,
"text": "Now for creating a basic display API for Instagram posts we will be creating an API for displaying this data. You may refer to the How to Generate API URL for Public Instagram Feeds in Android? Now we have created the URL with the access token and we will use this URL to get the JSON data. "
},
{
"code": null,
"e": 1835,
"s": 1759,
"text": "Step 4: Adding permissions for the internet in the AndroidManifest.xml file"
},
{
"code": null,
"e": 2043,
"s": 1835,
"text": "As we are loading data from the internet. For that, we will have to add the internet permissions to our AndroidManifest.xml file. Navigate to the app > AndroidManifest.xml file and add the below code to it. "
},
{
"code": null,
"e": 2047,
"s": 2043,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />",
"e": 2184,
"s": 2047,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2184,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2375,
"s": 2232,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2379,
"s": 2375,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--recycler view for displaying our Instagram posts--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVInstaFeeds\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> <!--progressbar for displaying our loading indicator--> <ProgressBar android:id=\"@+id/idLoadingPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:visibility=\"visible\" /> </RelativeLayout>",
"e": 3218,
"s": 2379,
"text": null
},
{
"code": null,
"e": 3299,
"s": 3218,
"text": "Step 6: Creating a new layout file for displaying each item of our RecyclerView "
},
{
"code": null,
"e": 3454,
"s": 3299,
"text": "Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as insta_feed_rv_item and add the below code to it. "
},
{
"code": null,
"e": 3458,
"s": 3454,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <LinearLayout android:id=\"@+id/idLLTopBar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:padding=\"4dp\"> <!--circle image for displaying the user image--> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/idCVAuthor\" android:layout_width=\"40dp\" android:layout_height=\"40dp\" android:layout_margin=\"5dp\" /> <!--text view for displaying user name--> <TextView android:id=\"@+id/idTVAuthorName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_margin=\"3dp\" android:padding=\"3dp\" android:text=\"geeks_for_geeks\" android:textColor=\"@color/black\" android:textStyle=\"bold\" /> </LinearLayout> <!--image view to display the post image--> <ImageView android:id=\"@+id/idIVPost\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_below=\"@id/idLLTopBar\" android:adjustViewBounds=\"true\" android:scaleType=\"centerCrop\" /> <!--text view to display likes count--> <TextView android:id=\"@+id/idTVLikes\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIVPost\" android:layout_margin=\"6dp\" android:padding=\"5dp\" android:text=\"likes\" android:textColor=\"@color/black\" android:textStyle=\"bold\" /> <!--text view to display the caption in instagram post--> <TextView android:id=\"@+id/idTVPostDesc\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVLikes\" android:layout_margin=\"6dp\" android:padding=\"5dp\" android:textColor=\"@color/black\" android:textSize=\"11sp\" /> </RelativeLayout>",
"e": 5719,
"s": 3458,
"text": null
},
{
"code": null,
"e": 5775,
"s": 5719,
"text": "Step 7: Create a Modal Class to store data for our Feed"
},
{
"code": null,
"e": 5903,
"s": 5775,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as InstaModal. "
},
{
"code": null,
"e": 5908,
"s": 5903,
"text": "Java"
},
{
"code": "public class InstaModal { // variables for storing data // of our recycler view item private String id; private String media_type; private String permalink; private String media_url; private String username; private String caption; private String timestamp; public String getAuthor_url() { return author_url; } public void setAuthor_url(String author_url) { this.author_url = author_url; } public int getLikesCount() { return likesCount; } public void setLikesCount(int likesCount) { this.likesCount = likesCount; } private String author_url; private int likesCount; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMedia_type() { return media_type; } public void setMedia_type(String media_type) { this.media_type = media_type; } public String getPermalink() { return permalink; } public void setPermalink(String permalink) { this.permalink = permalink; } public String getMedia_url() { return media_url; } public void setMedia_url(String media_url) { this.media_url = media_url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public InstaModal(String id, String media_type, String permalink, String media_url, String username, String caption, String timestamp, String author_url, int likesCount) { this.id = id; this.media_type = media_type; this.permalink = permalink; this.media_url = media_url; this.username = username; this.caption = caption; this.timestamp = timestamp; this.author_url = author_url; this.likesCount = likesCount; }}",
"e": 8114,
"s": 5908,
"text": null
},
{
"code": null,
"e": 8203,
"s": 8114,
"text": "Step 8: Creating an Adapter class for setting this data to each item of our RecyclerView"
},
{
"code": null,
"e": 8362,
"s": 8203,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name it as InstagramFeedRVAdapter and add the below code to it. "
},
{
"code": null,
"e": 8367,
"s": 8362,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class InstagramFeedRVAdapter extends RecyclerView.Adapter<InstagramFeedRVAdapter.ViewHolder> { private ArrayList<InstaModal> instaModalArrayList; private Context context; public InstagramFeedRVAdapter(ArrayList<InstaModal> instaModalArrayList, Context context) { this.instaModalArrayList = instaModalArrayList; this.context = context; } @NonNull @Override public InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout for item of recycler view item. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false); return new InstagramFeedRVAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) { InstaModal modal = instaModalArrayList.get(position); holder.authorTV.setText(modal.getUsername()); if (modal.getMedia_type().equals(\"IMAGE\")) { Picasso.get().load(modal.getMedia_url()).into(holder.postIV); } holder.desctv.setText(modal.getCaption()); holder.likeTV.setText(\"\" + modal.getLikesCount() + \" likes\"); Picasso.get().load(modal.getAuthor_url()).into(holder.authorIV); } @Override public int getItemCount() { return instaModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView authorIV; private TextView authorTV; private ImageView postIV; private TextView likeTV, desctv; public ViewHolder(@NonNull View itemView) { super(itemView); authorIV = itemView.findViewById(R.id.idCVAuthor); authorTV = itemView.findViewById(R.id.idTVAuthorName); postIV = itemView.findViewById(R.id.idIVPost); likeTV = itemView.findViewById(R.id.idTVLikes); desctv = itemView.findViewById(R.id.idTVPostDesc); } }}",
"e": 10766,
"s": 8367,
"text": null
},
{
"code": null,
"e": 10814,
"s": 10766,
"text": "Step 9: Working with the MainActivity.java file"
},
{
"code": null,
"e": 11004,
"s": 10814,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 11009,
"s": 11004,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our requestqueue, // array list, progressbar, edittext, // image button and our recycler view. private RequestQueue mRequestQueue; private ArrayList<InstaModal> instaModalArrayList; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views. progressBar = findViewById(R.id.idLoadingPB); instaModalArrayList = new ArrayList<>(); // calling method to load // data in recycler view. getInstagramData(); } private void getInstagramData() { // below line is use to initialize the variable for our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // below line is use to clear cache this will // be use when our data is being updated. mRequestQueue.getCache().clear(); // below is the url for getting data // from API in json format. String url = \"Enter your URL\"; // below line we are creating a new request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); try { JSONArray dataArray = response.getJSONArray(\"data\"); for (int i = 0; i < dataArray.length(); i++) { // below line is to extract data from JSON file. JSONObject dataObj = dataArray.getJSONObject(i); String id = dataObj.getString(\"id\"); String media_type = dataObj.getString(\"media_type\"); String permalink = dataObj.getString(\"permalink\"); String media_url = dataObj.getString(\"media_url\"); String username = dataObj.getString(\"username\"); String caption = dataObj.getString(\"caption\"); String timestamp = dataObj.getString(\"timestamp\"); // below line is to add a constant author image URL to our recycler view. String author_url = \"https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B\"; int likesCount = 100 + (i * 10); // below line is use to add data to our modal class. InstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount); // below line is use to add modal // class to our array list. instaModalArrayList.add(instaModal); // below line we are creating an adapter class and adding our array list in it. InstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this); RecyclerView instRV = findViewById(R.id.idRVInstaFeeds); // below line is for setting linear layout manager to our recycler view. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); // below line is to set layout manager to our recycler view. instRV.setLayoutManager(linearLayoutManager); // below line is to set adapter // to our recycler view. instRV.setAdapter(adapter); } } catch (JSONException e) { // handling error case. e.printStackTrace(); Toast.makeText(MainActivity.this, \"Fail to get Data..\" + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling error message. Toast.makeText(MainActivity.this, \"Fail to get Data..\" + error, Toast.LENGTH_SHORT).show(); } }); queue.add(jsonObjectRequest); }}",
"e": 16526,
"s": 11009,
"text": null
},
{
"code": null,
"e": 16575,
"s": 16526,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 16690,
"s": 16575,
"text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp/tree/InstagramCustomListVIew"
},
{
"code": null,
"e": 16700,
"s": 16690,
"text": "kalrap615"
},
{
"code": null,
"e": 16708,
"s": 16700,
"text": "android"
},
{
"code": null,
"e": 16732,
"s": 16708,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 16740,
"s": 16732,
"text": "Android"
},
{
"code": null,
"e": 16745,
"s": 16740,
"text": "Java"
},
{
"code": null,
"e": 16764,
"s": 16745,
"text": "Technical Scripter"
},
{
"code": null,
"e": 16769,
"s": 16764,
"text": "Java"
},
{
"code": null,
"e": 16777,
"s": 16769,
"text": "Android"
}
] |
JavaScript Comparison Operators
|
24 Mar, 2022
In this article, we will know about various comparison operators & their implementation in Javascript. The Comparison operators are mainly used to perform the logical operations that determine the equality or difference between the values.
Operators are used to performing specific mathematical and logical computations on operands. Like C, C++, Java, Python, and various other languages, JavaScript also supports Comparison operations. Comparison operators are used in logical expressions to determine their equality or differences in variables or values.
Example: Below is the example of the comparison operators.
Javascript
<script> function gfg() { let val1 = 5; // Equality Operators document.write(val1 == 5); document.write("<br>"); // Relational Operators document.write(val1 > 0); } gfg(); </script>
Output:
true
true
There are various comparison operators supported by JavaScript:
Equality Operators
Relational Operators
We will discuss both the operators sequentially through the examples.
Equality Operators:
Equality (==): This operator is used to compare the equality of two operands. If equal then the condition is true otherwise false.
Syntax:
x == y
Example 1: Below example illustrate the (==) operator in JavaScript.
Javascript
<script> // Illustration of (==) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 == 5); console.log(val2 == 5); console.log(val1 == val1); // Check against null and boolean value console.log(0 == false); console.log(0 == null);</script>
Output:
> true
> true
> true
> true
> false
Example 2: This example describes the equality operator to compare the 2 object’s values.
Javascript
<script> // Illustration of (==) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 == 'value'); console.log(obj1 == obj2); console.log(obj1.val1 == obj2.val2); // Check against undefined console.log(0 == undefined); console.log(null == undefined);</script>
Output:
> true
> false
> true
> false
> true
Inequality(!=): This operator is used to compare the inequality of two operands. If equal then the condition is false otherwise true.
Syntax:
x != y
Example 1: Below examples illustrate the (!=) operator in JavaScript.
Javascript
<script> // Illustration of (!=) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 != 6); console.log(val2 != '5'); console.log(val1 != val1); // Check against null and boolean value console.log(0 != false); console.log(0 != null);</script>
Output:
> true
> false
> false
> false
> true
Example 2: This example describes the inequality operator to compare the 2 values.
Javascript
<script> // Illustration of (!=) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 != 'value'); console.log(obj1 != obj2); console.log(obj1.val1 != obj2.val2); // Check against undefined console.log(0 != undefined); console.log(null != undefined);</script>
Output:
> false
> true
> false
> true
> false
Strict equality(===): This operator is used to compare the equality of two operands with type. If both value and type are equal then the condition is true otherwise false.
Syntax:
x === y
Example 1: Below examples illustrate the (===) operator in JavaScript.
Javascript
<script> // Illustration of (===) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 === 6); console.log(val2 === '5'); console.log(val1 === val1); // Check against null and boolean value console.log(0 === false); console.log(0 === null);</script>
Output:
> false
> true
> true
> false
> false
Example 2: This example describes the strict equality operator to compare the 2 values.
Javascript
<script> // Illustration of (===) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 === 'value'); console.log(obj1 === obj2); console.log(obj1.val1 === obj2.val2); // Check against undefined console.log(0 === undefined); console.log(null === undefined);</script>
Output:
> true
> false
> true
> false
> false
Please refer to the ‘===’ vs ‘==’ Comparison Operator article for the significant differences in them.
Strict inequality(!==): This operator is used to compare the inequality of two operands with type. If both value and type are not equal then the condition is true otherwise false.
Syntax:
x !== y
Example 1: Below examples illustrate the (!==) operator in JavaScript.
jscript
<script> // Illustration of (!==) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 !== 6); console.log(val2 !== '5'); console.log(val1 !== val1); // Check against null and boolean value console.log(0 !== false); console.log(0 !== null);</script>
Output:
> true
> false
> false
> true
> true
Example 2: This example describes the strict inequality operator to compare the 2 values.
Javascript
<script> // Illustration of (!==) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 !== 'value'); console.log(obj1 !== obj2); console.log(obj1.val1 !== obj2.val2); // Check against undefined console.log(0 !== undefined); console.log(null !== undefined);</script>
Output:
> false
> true
> false
> true
> true
Relational Operators:
Greater than operator(>): This operator is used to check whether the left-side value is greater than the right-side value. If the value is greater then the condition is true otherwise false.
Syntax:
x > y
Example 1: Below examples illustrate the (>) operator in JavaScript.
Javascript
<script> // Illustration of (>) operator let val1 = 5; let val2 = "5"; // Checking of operands console.log(val1 > 0); console.log(val2 > "10"); console.log(val1 > "10"); console.log(val2 > 0);</script>
Output:
> true
> true
> false
> true
Example 2: This example describes the greater than operator to compare the 2 values.
Javascript
<script> // Illustration of (>) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 > 0); console.log(obj1 > obj2); console.log(obj1.val1 > obj2.val2); console.log(obj2 > obj1); console.log(obj2.val2 > obj1.val1);</script>
Output:
> true
> false
> false
> false
> true
Greater than or equal operator(>=): This operator is used to check whether the left side operand is greater than or equal to the right side operand. If the value is greater than or equal then the condition is true otherwise false.
Syntax:
x >= y
Example 1: Below examples illustrate the (>=) operator in JavaScript.
Javascript
<script> // Illustration of (>=) operator let val1 = 5; let val2 = "5"; // Checking of operands console.log(val1 >= 5); console.log(val2 >= "15"); console.log(val1 >= "5"); console.log(val2 >= 15);</script>
Output:
> true
> true
> true
> false
Example 2: This example describes the greater than or equal operator to compare the 2 values.
Javascript
<script> // Illustration of (>=) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 >= 0); console.log(obj1 >= obj2); console.log(obj1.val1 >= obj2.val2); console.log(obj2 >= obj1); console.log(obj2.val2 >= obj1.val1);</script>
Output:
> true
> true
> false
> true
> true
Less than operator(<): This operator is used to check whether the left-side value is less than the right-side value. If yes then the condition is true otherwise false.
Syntax:
x < y
Example 1: Below examples illustrate the (<) operator in JavaScript.
Javascript
<script> // Illustration of (<) operator let val1 = 5; let val2 = "5"; // Checking of operands console.log(val1 < 15); console.log(val2 < "0"); console.log(val1 < "0"); console.log(val2 < 15);</script>
Output:
> true
> false
> false
> true
Example 2: This example describes the Less than operator to compare the 2 values.
Javascript
<script> // Illustration of (<) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 < 10); console.log(obj1 < obj2); console.log(obj1.val1 < obj2.val2); console.log(obj2 < obj1); console.log(obj2.val2 < obj1.val1);</script>
Output:
> true
> false
> true
> false
> false
Less than or equal operator(<=): This operator is used to check whether the left side operand value is less than or equal to the right side operand value. If yes then the condition is true otherwise false.
Syntax:
x <= y
Example 1: Below examples illustrate the (<=) operator in JavaScript.
Javascript
<script> // Illustration of (<=) operator let val1 = 5; let val2 = "5"; // Checking of operands console.log(val1 <= 15); console.log(val2 <= "0"); console.log(val1 <= "0"); console.log(val2 <= 15);</script>
Output:
> true
> false
> false
> true
Example 2: This example describes the Less than or equal to an operator to compare the 2 values.
Javascript
<script> // Illustration of (<=) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 <= 10); console.log(obj1 <= obj2); console.log(obj1.val1 <= obj2.val2); console.log(obj2 <= obj1); console.log(obj2.val2 <= obj1.val1);</script>
Output:
> true
> true
> true
> true
> false
Supported Browsers: The browsers supported by all JavaScript Comparison operators are listed below:
Google Chrome
Firefox
Opera
Safari
Microsoft Edge
Internet Explorer
bhaskargeeksforgeeks
javascript-operators
Picked
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
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 ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "In this article, we will know about various comparison operators & their implementation in Javascript. The Comparison operators are mainly used to perform the logical operations that determine the equality or difference between the values."
},
{
"code": null,
"e": 586,
"s": 268,
"text": "Operators are used to performing specific mathematical and logical computations on operands. Like C, C++, Java, Python, and various other languages, JavaScript also supports Comparison operations. Comparison operators are used in logical expressions to determine their equality or differences in variables or values. "
},
{
"code": null,
"e": 645,
"s": 586,
"text": "Example: Below is the example of the comparison operators."
},
{
"code": null,
"e": 656,
"s": 645,
"text": "Javascript"
},
{
"code": "<script> function gfg() { let val1 = 5; // Equality Operators document.write(val1 == 5); document.write(\"<br>\"); // Relational Operators document.write(val1 > 0); } gfg(); </script>",
"e": 881,
"s": 656,
"text": null
},
{
"code": null,
"e": 889,
"s": 881,
"text": "Output:"
},
{
"code": null,
"e": 899,
"s": 889,
"text": "true\ntrue"
},
{
"code": null,
"e": 963,
"s": 899,
"text": "There are various comparison operators supported by JavaScript:"
},
{
"code": null,
"e": 982,
"s": 963,
"text": "Equality Operators"
},
{
"code": null,
"e": 1003,
"s": 982,
"text": "Relational Operators"
},
{
"code": null,
"e": 1073,
"s": 1003,
"text": "We will discuss both the operators sequentially through the examples."
},
{
"code": null,
"e": 1093,
"s": 1073,
"text": "Equality Operators:"
},
{
"code": null,
"e": 1225,
"s": 1093,
"text": "Equality (==): This operator is used to compare the equality of two operands. If equal then the condition is true otherwise false."
},
{
"code": null,
"e": 1233,
"s": 1225,
"text": "Syntax:"
},
{
"code": null,
"e": 1240,
"s": 1233,
"text": "x == y"
},
{
"code": null,
"e": 1309,
"s": 1240,
"text": "Example 1: Below example illustrate the (==) operator in JavaScript."
},
{
"code": null,
"e": 1320,
"s": 1309,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (==) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 == 5); console.log(val2 == 5); console.log(val1 == val1); // Check against null and boolean value console.log(0 == false); console.log(0 == null);</script>",
"e": 1636,
"s": 1320,
"text": null
},
{
"code": null,
"e": 1644,
"s": 1636,
"text": "Output:"
},
{
"code": null,
"e": 1680,
"s": 1644,
"text": "> true\n> true\n> true\n> true\n> false"
},
{
"code": null,
"e": 1770,
"s": 1680,
"text": "Example 2: This example describes the equality operator to compare the 2 object’s values."
},
{
"code": null,
"e": 1781,
"s": 1770,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (==) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 == 'value'); console.log(obj1 == obj2); console.log(obj1.val1 == obj2.val2); // Check against undefined console.log(0 == undefined); console.log(null == undefined);</script>",
"e": 2150,
"s": 1781,
"text": null
},
{
"code": null,
"e": 2158,
"s": 2150,
"text": "Output:"
},
{
"code": null,
"e": 2195,
"s": 2158,
"text": "> true\n> false\n> true\n> false\n> true"
},
{
"code": null,
"e": 2329,
"s": 2195,
"text": "Inequality(!=): This operator is used to compare the inequality of two operands. If equal then the condition is false otherwise true."
},
{
"code": null,
"e": 2337,
"s": 2329,
"text": "Syntax:"
},
{
"code": null,
"e": 2344,
"s": 2337,
"text": "x != y"
},
{
"code": null,
"e": 2414,
"s": 2344,
"text": "Example 1: Below examples illustrate the (!=) operator in JavaScript."
},
{
"code": null,
"e": 2425,
"s": 2414,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (!=) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 != 6); console.log(val2 != '5'); console.log(val1 != val1); // Check against null and boolean value console.log(0 != false); console.log(0 != null);</script>",
"e": 2743,
"s": 2425,
"text": null
},
{
"code": null,
"e": 2751,
"s": 2743,
"text": "Output:"
},
{
"code": null,
"e": 2789,
"s": 2751,
"text": "> true\n> false\n> false\n> false\n> true"
},
{
"code": null,
"e": 2872,
"s": 2789,
"text": "Example 2: This example describes the inequality operator to compare the 2 values."
},
{
"code": null,
"e": 2883,
"s": 2872,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (!=) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 != 'value'); console.log(obj1 != obj2); console.log(obj1.val1 != obj2.val2); // Check against undefined console.log(0 != undefined); console.log(null != undefined);</script>",
"e": 3252,
"s": 2883,
"text": null
},
{
"code": null,
"e": 3260,
"s": 3252,
"text": "Output:"
},
{
"code": null,
"e": 3298,
"s": 3260,
"text": "> false\n> true\n> false\n> true\n> false"
},
{
"code": null,
"e": 3471,
"s": 3298,
"text": "Strict equality(===): This operator is used to compare the equality of two operands with type. If both value and type are equal then the condition is true otherwise false."
},
{
"code": null,
"e": 3479,
"s": 3471,
"text": "Syntax:"
},
{
"code": null,
"e": 3487,
"s": 3479,
"text": "x === y"
},
{
"code": null,
"e": 3558,
"s": 3487,
"text": "Example 1: Below examples illustrate the (===) operator in JavaScript."
},
{
"code": null,
"e": 3569,
"s": 3558,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (===) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 === 6); console.log(val2 === '5'); console.log(val1 === val1); // Check against null and boolean value console.log(0 === false); console.log(0 === null);</script>",
"e": 3893,
"s": 3569,
"text": null
},
{
"code": null,
"e": 3901,
"s": 3893,
"text": "Output:"
},
{
"code": null,
"e": 3939,
"s": 3901,
"text": "> false\n> true\n> true\n> false\n> false"
},
{
"code": null,
"e": 4027,
"s": 3939,
"text": "Example 2: This example describes the strict equality operator to compare the 2 values."
},
{
"code": null,
"e": 4038,
"s": 4027,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (===) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 === 'value'); console.log(obj1 === obj2); console.log(obj1.val1 === obj2.val2); // Check against undefined console.log(0 === undefined); console.log(null === undefined);</script>",
"e": 4413,
"s": 4038,
"text": null
},
{
"code": null,
"e": 4421,
"s": 4413,
"text": "Output:"
},
{
"code": null,
"e": 4459,
"s": 4421,
"text": "> true\n> false\n> true\n> false\n> false"
},
{
"code": null,
"e": 4562,
"s": 4459,
"text": "Please refer to the ‘===’ vs ‘==’ Comparison Operator article for the significant differences in them."
},
{
"code": null,
"e": 4742,
"s": 4562,
"text": "Strict inequality(!==): This operator is used to compare the inequality of two operands with type. If both value and type are not equal then the condition is true otherwise false."
},
{
"code": null,
"e": 4750,
"s": 4742,
"text": "Syntax:"
},
{
"code": null,
"e": 4758,
"s": 4750,
"text": "x !== y"
},
{
"code": null,
"e": 4829,
"s": 4758,
"text": "Example 1: Below examples illustrate the (!==) operator in JavaScript."
},
{
"code": null,
"e": 4837,
"s": 4829,
"text": "jscript"
},
{
"code": "<script> // Illustration of (!==) operator let val1 = 5; let val2 = '5'; // Checking of operands console.log(val1 !== 6); console.log(val2 !== '5'); console.log(val1 !== val1); // Check against null and boolean value console.log(0 !== false); console.log(0 !== null);</script>",
"e": 5129,
"s": 4837,
"text": null
},
{
"code": null,
"e": 5137,
"s": 5129,
"text": "Output:"
},
{
"code": null,
"e": 5174,
"s": 5137,
"text": "> true\n> false\n> false\n> true\n> true"
},
{
"code": null,
"e": 5264,
"s": 5174,
"text": "Example 2: This example describes the strict inequality operator to compare the 2 values."
},
{
"code": null,
"e": 5275,
"s": 5264,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (!==) operator let obj1 = {'val1': 'value'}; let obj2 = {'val2': 'value'}; // Checking of operands console.log(obj1.val1 !== 'value'); console.log(obj1 !== obj2); console.log(obj1.val1 !== obj2.val2); // Check against undefined console.log(0 !== undefined); console.log(null !== undefined);</script>",
"e": 5650,
"s": 5275,
"text": null
},
{
"code": null,
"e": 5658,
"s": 5650,
"text": "Output:"
},
{
"code": null,
"e": 5695,
"s": 5658,
"text": "> false\n> true\n> false\n> true\n> true"
},
{
"code": null,
"e": 5717,
"s": 5695,
"text": "Relational Operators:"
},
{
"code": null,
"e": 5909,
"s": 5717,
"text": "Greater than operator(>): This operator is used to check whether the left-side value is greater than the right-side value. If the value is greater then the condition is true otherwise false."
},
{
"code": null,
"e": 5917,
"s": 5909,
"text": "Syntax:"
},
{
"code": null,
"e": 5923,
"s": 5917,
"text": "x > y"
},
{
"code": null,
"e": 5992,
"s": 5923,
"text": "Example 1: Below examples illustrate the (>) operator in JavaScript."
},
{
"code": null,
"e": 6003,
"s": 5992,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (>) operator let val1 = 5; let val2 = \"5\"; // Checking of operands console.log(val1 > 0); console.log(val2 > \"10\"); console.log(val1 > \"10\"); console.log(val2 > 0);</script>",
"e": 6241,
"s": 6003,
"text": null
},
{
"code": null,
"e": 6249,
"s": 6241,
"text": "Output:"
},
{
"code": null,
"e": 6278,
"s": 6249,
"text": "> true\n> true\n> false\n> true"
},
{
"code": null,
"e": 6363,
"s": 6278,
"text": "Example 2: This example describes the greater than operator to compare the 2 values."
},
{
"code": null,
"e": 6374,
"s": 6363,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (>) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 > 0); console.log(obj1 > obj2); console.log(obj1.val1 > obj2.val2); console.log(obj2 > obj1); console.log(obj2.val2 > obj1.val1);</script>",
"e": 6687,
"s": 6374,
"text": null
},
{
"code": null,
"e": 6695,
"s": 6687,
"text": "Output:"
},
{
"code": null,
"e": 6733,
"s": 6695,
"text": "> true\n> false\n> false\n> false\n> true"
},
{
"code": null,
"e": 6964,
"s": 6733,
"text": "Greater than or equal operator(>=): This operator is used to check whether the left side operand is greater than or equal to the right side operand. If the value is greater than or equal then the condition is true otherwise false."
},
{
"code": null,
"e": 6972,
"s": 6964,
"text": "Syntax:"
},
{
"code": null,
"e": 6979,
"s": 6972,
"text": "x >= y"
},
{
"code": null,
"e": 7049,
"s": 6979,
"text": "Example 1: Below examples illustrate the (>=) operator in JavaScript."
},
{
"code": null,
"e": 7060,
"s": 7049,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (>=) operator let val1 = 5; let val2 = \"5\"; // Checking of operands console.log(val1 >= 5); console.log(val2 >= \"15\"); console.log(val1 >= \"5\"); console.log(val2 >= 15);</script>",
"e": 7279,
"s": 7060,
"text": null
},
{
"code": null,
"e": 7287,
"s": 7279,
"text": "Output:"
},
{
"code": null,
"e": 7316,
"s": 7287,
"text": "> true\n> true\n> true\n> false"
},
{
"code": null,
"e": 7410,
"s": 7316,
"text": "Example 2: This example describes the greater than or equal operator to compare the 2 values."
},
{
"code": null,
"e": 7421,
"s": 7410,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (>=) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 >= 0); console.log(obj1 >= obj2); console.log(obj1.val1 >= obj2.val2); console.log(obj2 >= obj1); console.log(obj2.val2 >= obj1.val1);</script>",
"e": 7740,
"s": 7421,
"text": null
},
{
"code": null,
"e": 7748,
"s": 7740,
"text": "Output:"
},
{
"code": null,
"e": 7784,
"s": 7748,
"text": "> true\n> true\n> false\n> true\n> true"
},
{
"code": null,
"e": 7952,
"s": 7784,
"text": "Less than operator(<): This operator is used to check whether the left-side value is less than the right-side value. If yes then the condition is true otherwise false."
},
{
"code": null,
"e": 7960,
"s": 7952,
"text": "Syntax:"
},
{
"code": null,
"e": 7966,
"s": 7960,
"text": "x < y"
},
{
"code": null,
"e": 8035,
"s": 7966,
"text": "Example 1: Below examples illustrate the (<) operator in JavaScript."
},
{
"code": null,
"e": 8046,
"s": 8035,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (<) operator let val1 = 5; let val2 = \"5\"; // Checking of operands console.log(val1 < 15); console.log(val2 < \"0\"); console.log(val1 < \"0\"); console.log(val2 < 15);</script>",
"e": 8260,
"s": 8046,
"text": null
},
{
"code": null,
"e": 8268,
"s": 8260,
"text": "Output:"
},
{
"code": null,
"e": 8298,
"s": 8268,
"text": "> true\n> false\n> false\n> true"
},
{
"code": null,
"e": 8380,
"s": 8298,
"text": "Example 2: This example describes the Less than operator to compare the 2 values."
},
{
"code": null,
"e": 8391,
"s": 8380,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (<) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 < 10); console.log(obj1 < obj2); console.log(obj1.val1 < obj2.val2); console.log(obj2 < obj1); console.log(obj2.val2 < obj1.val1);</script>",
"e": 8705,
"s": 8391,
"text": null
},
{
"code": null,
"e": 8713,
"s": 8705,
"text": "Output:"
},
{
"code": null,
"e": 8751,
"s": 8713,
"text": "> true\n> false\n> true\n> false\n> false"
},
{
"code": null,
"e": 8957,
"s": 8751,
"text": "Less than or equal operator(<=): This operator is used to check whether the left side operand value is less than or equal to the right side operand value. If yes then the condition is true otherwise false."
},
{
"code": null,
"e": 8965,
"s": 8957,
"text": "Syntax:"
},
{
"code": null,
"e": 8972,
"s": 8965,
"text": "x <= y"
},
{
"code": null,
"e": 9042,
"s": 8972,
"text": "Example 1: Below examples illustrate the (<=) operator in JavaScript."
},
{
"code": null,
"e": 9053,
"s": 9042,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (<=) operator let val1 = 5; let val2 = \"5\"; // Checking of operands console.log(val1 <= 15); console.log(val2 <= \"0\"); console.log(val1 <= \"0\"); console.log(val2 <= 15);</script>",
"e": 9296,
"s": 9053,
"text": null
},
{
"code": null,
"e": 9304,
"s": 9296,
"text": "Output:"
},
{
"code": null,
"e": 9334,
"s": 9304,
"text": "> true\n> false\n> false\n> true"
},
{
"code": null,
"e": 9431,
"s": 9334,
"text": "Example 2: This example describes the Less than or equal to an operator to compare the 2 values."
},
{
"code": null,
"e": 9442,
"s": 9431,
"text": "Javascript"
},
{
"code": "<script> // Illustration of (<=) operator let obj1 = {'val1': 1}; let obj2 = {'val2': 3}; // Checking of operands console.log(obj1.val1 <= 10); console.log(obj1 <= obj2); console.log(obj1.val1 <= obj2.val2); console.log(obj2 <= obj1); console.log(obj2.val2 <= obj1.val1);</script>",
"e": 9762,
"s": 9442,
"text": null
},
{
"code": null,
"e": 9770,
"s": 9762,
"text": "Output:"
},
{
"code": null,
"e": 9806,
"s": 9770,
"text": "> true\n> true\n> true\n> true\n> false"
},
{
"code": null,
"e": 9906,
"s": 9806,
"text": "Supported Browsers: The browsers supported by all JavaScript Comparison operators are listed below:"
},
{
"code": null,
"e": 9920,
"s": 9906,
"text": "Google Chrome"
},
{
"code": null,
"e": 9928,
"s": 9920,
"text": "Firefox"
},
{
"code": null,
"e": 9934,
"s": 9928,
"text": "Opera"
},
{
"code": null,
"e": 9941,
"s": 9934,
"text": "Safari"
},
{
"code": null,
"e": 9956,
"s": 9941,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 9974,
"s": 9956,
"text": "Internet Explorer"
},
{
"code": null,
"e": 9995,
"s": 9974,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 10016,
"s": 9995,
"text": "javascript-operators"
},
{
"code": null,
"e": 10023,
"s": 10016,
"text": "Picked"
},
{
"code": null,
"e": 10034,
"s": 10023,
"text": "JavaScript"
},
{
"code": null,
"e": 10051,
"s": 10034,
"text": "Web Technologies"
},
{
"code": null,
"e": 10149,
"s": 10051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10210,
"s": 10149,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10282,
"s": 10210,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 10322,
"s": 10282,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 10375,
"s": 10322,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 10417,
"s": 10375,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 10450,
"s": 10417,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 10512,
"s": 10450,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 10573,
"s": 10512,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10623,
"s": 10573,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
TreeMap descendingMap() Method in Java with Examples
|
15 Oct, 2020
The descendingMap() method is used to return a reverse order view of the mappings contained in this map. The reverse order or descending order of mappings are according to the descending order of keys. The descending map is backed by this map, so changes to the map are reflected in the descending map, and vice-versa.
Declaration Syntax:
public NavigableMap<K,V> descendingMap()
K : It is the type of keys maintained by this map.
V : It is the type of mapped values.
Parameters: Not Available
Return Value: A reverse order or descending order view of this map.
Example 1:
Java
// Java program to demonstrate descendingMap() method import java.util.*; public class Example1 { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Add the mappings to the tree map using put() treemap.put(2, "Two"); treemap.put(16, "Sixteen"); treemap.put(8, "Eight"); treemap.put(6, "Six"); treemap.put(10, "Ten"); // store the descending order of mappings in dmap NavigableMap dmap = treemap.descendingMap(); System.out.println("Reverse navigable map values: " + dmap); }}
Reverse navigable map values: {16=Sixteen, 10=Ten, 8=Eight, 6=Six, 2=Two}
Example 2 :
Java
// Java Program to demonstrate descendingMap() method import java.util.*; public class Example2 { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Add the mappings to the tree map using put() treemap.put(11, "Abhishek Rout"); treemap.put(9, "Akash Salvi"); treemap.put(2, "Hemant Koul"); treemap.put(8, "Vaibhav Kamble"); treemap.put(6, "Sagar Joshi"); treemap.put(10, "Onkar Dherange"); treemap.put(7, "Rajwardhan Shinde"); treemap.put(1, "Rahul Gavhane"); treemap.put(4, "Abhishek Gadge"); treemap.put(3, "Pratik Kulkarni"); treemap.put(5, "Raviraj Bugge"); // store the descending order of mappings in dmap NavigableMap dmap = treemap.descendingMap(); // print the mappings System.out.println( "List of students in reverse order: " + dmap); }}
List of students in reverse order: {11=Abhishek Rout, 10=Onkar Dherange, 9=Akash Salvi, 8=Vaibhav Kamble, 7=Rajwardhan Shinde, 6=Sagar Joshi, 5=Raviraj Bugge, 4=Abhishek Gadge, 3=Pratik Kulkarni, 2=Hemant Koul, 1=Rahul Gavhane}
Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "The descendingMap() method is used to return a reverse order view of the mappings contained in this map. The reverse order or descending order of mappings are according to the descending order of keys. The descending map is backed by this map, so changes to the map are reflected in the descending map, and vice-versa. "
},
{
"code": null,
"e": 368,
"s": 348,
"text": "Declaration Syntax:"
},
{
"code": null,
"e": 410,
"s": 368,
"text": "public NavigableMap<K,V> descendingMap()\n"
},
{
"code": null,
"e": 461,
"s": 410,
"text": "K : It is the type of keys maintained by this map."
},
{
"code": null,
"e": 498,
"s": 461,
"text": "V : It is the type of mapped values."
},
{
"code": null,
"e": 524,
"s": 498,
"text": "Parameters: Not Available"
},
{
"code": null,
"e": 592,
"s": 524,
"text": "Return Value: A reverse order or descending order view of this map."
},
{
"code": null,
"e": 604,
"s": 592,
"text": "Example 1: "
},
{
"code": null,
"e": 609,
"s": 604,
"text": "Java"
},
{
"code": "// Java program to demonstrate descendingMap() method import java.util.*; public class Example1 { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Add the mappings to the tree map using put() treemap.put(2, \"Two\"); treemap.put(16, \"Sixteen\"); treemap.put(8, \"Eight\"); treemap.put(6, \"Six\"); treemap.put(10, \"Ten\"); // store the descending order of mappings in dmap NavigableMap dmap = treemap.descendingMap(); System.out.println(\"Reverse navigable map values: \" + dmap); }}",
"e": 1326,
"s": 609,
"text": null
},
{
"code": null,
"e": 1403,
"s": 1326,
"text": "Reverse navigable map values: {16=Sixteen, 10=Ten, 8=Eight, 6=Six, 2=Two}\n\n\n"
},
{
"code": null,
"e": 1415,
"s": 1403,
"text": "Example 2 :"
},
{
"code": null,
"e": 1420,
"s": 1415,
"text": "Java"
},
{
"code": "// Java Program to demonstrate descendingMap() method import java.util.*; public class Example2 { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Add the mappings to the tree map using put() treemap.put(11, \"Abhishek Rout\"); treemap.put(9, \"Akash Salvi\"); treemap.put(2, \"Hemant Koul\"); treemap.put(8, \"Vaibhav Kamble\"); treemap.put(6, \"Sagar Joshi\"); treemap.put(10, \"Onkar Dherange\"); treemap.put(7, \"Rajwardhan Shinde\"); treemap.put(1, \"Rahul Gavhane\"); treemap.put(4, \"Abhishek Gadge\"); treemap.put(3, \"Pratik Kulkarni\"); treemap.put(5, \"Raviraj Bugge\"); // store the descending order of mappings in dmap NavigableMap dmap = treemap.descendingMap(); // print the mappings System.out.println( \"List of students in reverse order: \" + dmap); }}",
"e": 2444,
"s": 1420,
"text": null
},
{
"code": null,
"e": 2674,
"s": 2444,
"text": "List of students in reverse order: {11=Abhishek Rout, 10=Onkar Dherange, 9=Akash Salvi, 8=Vaibhav Kamble, 7=Rajwardhan Shinde, 6=Sagar Joshi, 5=Raviraj Bugge, 4=Abhishek Gadge, 3=Pratik Kulkarni, 2=Hemant Koul, 1=Rahul Gavhane}\n\n"
},
{
"code": null,
"e": 2691,
"s": 2674,
"text": "Java-Collections"
},
{
"code": null,
"e": 2704,
"s": 2691,
"text": "java-TreeMap"
},
{
"code": null,
"e": 2709,
"s": 2704,
"text": "Java"
},
{
"code": null,
"e": 2714,
"s": 2709,
"text": "Java"
},
{
"code": null,
"e": 2731,
"s": 2714,
"text": "Java-Collections"
},
{
"code": null,
"e": 2829,
"s": 2731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2844,
"s": 2829,
"text": "Stream In Java"
},
{
"code": null,
"e": 2865,
"s": 2844,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2886,
"s": 2865,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2905,
"s": 2886,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2922,
"s": 2905,
"text": "Generics in Java"
},
{
"code": null,
"e": 2952,
"s": 2922,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2978,
"s": 2952,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2994,
"s": 2978,
"text": "Strings in Java"
},
{
"code": null,
"e": 3031,
"s": 2994,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to set active class to nav menu from bootstrap ?
|
14 Dec, 2020
To set the active class to the navigation menu dynamically by scrolling or clicking on the navigation links, the active class is to be set on each section depending on the position of the webpage. To add methods and variables, JavaScript is used. To perform some action, the functions can be called on some events such as click and scroll.
Example: This example implements the approach mentioned above.
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> <style> html { /*For smooth scrolling behavior*/ scroll-behavior: smooth; } #home, #section1, #section2, #section3, #section4 { height: 70vh; text-align: center; font-size: 20px; padding-top: 50px; } #home { background-color: lightgreen; } #section1 { background-color: lightcoral; } #section2 { background-color: cyan; } #section3 { background-color: lightsalmon; } #section4 { background-color: lightseagreen; } </style></head> <body> <!-- Creating Nav Bar --> <section id="navigation"> <nav class="navbar navbar-expand-sm navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="#" style="color:greenyellow;"> Geeks for Geeks </a> <div class=" navbar-default"> <ul class="navbar-nav ml-auto"> <li class="nav-item "> <!--Initially active class is set to home link --> <a class="nav-link active" href="#"> Home </a> </li> <li class="nav-item"> <a class="nav-link" href="#section1"> Section 1 </a> </li> <li class="nav-item"> <a class="nav-link" href="#section2"> Section 2 </a> </li> <li class="nav-item"> <a class="nav-link" href="#section3"> Section 3 </a> </li> <li class="nav-item"> <a class="nav-link" href="#section4"> Section 4 </a> </li> </ul> </div> </div> </nav> <br><br> <!-- creating sections --> <section id="home" class="page-section"> Home </section> <section id="section1" class="page-section"> Section-1 </section> <section id="section2" class="page-section"> Section-2 </section> <section id="section3" class="page-section"> Section-3 </section> <section id="section4" class="page-section"> Section-4 </section> <!-- JavaScript code --> <script> /* Code for changing active link on clicking */ var btns = $("#navigation .navbar-nav .nav-link"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function () { var current = document .getElementsByClassName("active"); current[0].className = current[0] .className.replace(" active", ""); this.className += " active"; }); } /* Code for changing active link on Scrolling */ $(window).scroll(function () { var distance = $(window).scrollTop(); $('.page-section').each(function (i) { if ($(this).position().top <= distance + 250) { $('.navbar-nav a.active') .removeClass('active'); $('.navbar-nav a').eq(i) .addClass('active'); } }); }).scroll(); </script> </section></body> </html>
Output:
While scrolling the webpage:
While clicking on nav links:
Bootstrap-4
Bootstrap-Misc
HTML-Misc
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to set vertical alignment in Bootstrap ?
Tailwind CSS vs Bootstrap
How to toggle password visibility in forms using Bootstrap-icons ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 368,
"s": 28,
"text": "To set the active class to the navigation menu dynamically by scrolling or clicking on the navigation links, the active class is to be set on each section depending on the position of the webpage. To add methods and variables, JavaScript is used. To perform some action, the functions can be called on some events such as click and scroll."
},
{
"code": null,
"e": 431,
"s": 368,
"text": "Example: This example implements the approach mentioned above."
},
{
"code": null,
"e": 436,
"s": 431,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"> </script> <style> html { /*For smooth scrolling behavior*/ scroll-behavior: smooth; } #home, #section1, #section2, #section3, #section4 { height: 70vh; text-align: center; font-size: 20px; padding-top: 50px; } #home { background-color: lightgreen; } #section1 { background-color: lightcoral; } #section2 { background-color: cyan; } #section3 { background-color: lightsalmon; } #section4 { background-color: lightseagreen; } </style></head> <body> <!-- Creating Nav Bar --> <section id=\"navigation\"> <nav class=\"navbar navbar-expand-sm navbar-dark bg-dark fixed-top\"> <div class=\"container\"> <a class=\"navbar-brand\" href=\"#\" style=\"color:greenyellow;\"> Geeks for Geeks </a> <div class=\" navbar-default\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item \"> <!--Initially active class is set to home link --> <a class=\"nav-link active\" href=\"#\"> Home </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#section1\"> Section 1 </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#section2\"> Section 2 </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#section3\"> Section 3 </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#section4\"> Section 4 </a> </li> </ul> </div> </div> </nav> <br><br> <!-- creating sections --> <section id=\"home\" class=\"page-section\"> Home </section> <section id=\"section1\" class=\"page-section\"> Section-1 </section> <section id=\"section2\" class=\"page-section\"> Section-2 </section> <section id=\"section3\" class=\"page-section\"> Section-3 </section> <section id=\"section4\" class=\"page-section\"> Section-4 </section> <!-- JavaScript code --> <script> /* Code for changing active link on clicking */ var btns = $(\"#navigation .navbar-nav .nav-link\"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener(\"click\", function () { var current = document .getElementsByClassName(\"active\"); current[0].className = current[0] .className.replace(\" active\", \"\"); this.className += \" active\"; }); } /* Code for changing active link on Scrolling */ $(window).scroll(function () { var distance = $(window).scrollTop(); $('.page-section').each(function (i) { if ($(this).position().top <= distance + 250) { $('.navbar-nav a.active') .removeClass('active'); $('.navbar-nav a').eq(i) .addClass('active'); } }); }).scroll(); </script> </section></body> </html>",
"e": 5782,
"s": 436,
"text": null
},
{
"code": null,
"e": 5790,
"s": 5782,
"text": "Output:"
},
{
"code": null,
"e": 5819,
"s": 5790,
"text": "While scrolling the webpage:"
},
{
"code": null,
"e": 5848,
"s": 5819,
"text": "While clicking on nav links:"
},
{
"code": null,
"e": 5860,
"s": 5848,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 5875,
"s": 5860,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 5885,
"s": 5875,
"text": "HTML-Misc"
},
{
"code": null,
"e": 5895,
"s": 5885,
"text": "Bootstrap"
},
{
"code": null,
"e": 5900,
"s": 5895,
"text": "HTML"
},
{
"code": null,
"e": 5917,
"s": 5900,
"text": "Web Technologies"
},
{
"code": null,
"e": 5922,
"s": 5917,
"text": "HTML"
},
{
"code": null,
"e": 6020,
"s": 5922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6061,
"s": 6020,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 6094,
"s": 6061,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 6139,
"s": 6094,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 6165,
"s": 6139,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 6232,
"s": 6165,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 6280,
"s": 6232,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 6342,
"s": 6280,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6392,
"s": 6342,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 6416,
"s": 6392,
"text": "REST API (Introduction)"
}
] |
readdir() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <linux/types.h>
#include <linux/dirent.h>
int readdir(unsigned int fd, struct dirent *dirp,
unsigned int count);
int readdir(unsigned int fd, struct dirent *dirp,
unsigned int count);
readdir() reads one
dirent structure from the directory
pointed at by
fd into the memory area pointed to by
dirp. The parameter
count is ignored; at most one dirent structure is read.
The
dirent structure is declared as follows:
struct dirent
{
long d_ino; /* inode number */
off_t d_off; /* offset to this dirent */
unsigned short d_reclen; /* length of this d_name */
char d_name [NAME_MAX+1]; /* filename (null-terminated) */
}
d_ino is an inode number.
d_off is the distance from the start of the directory to this
dirent. d_reclen is the size of
d_name, not counting the null terminator.
d_name is a null-terminated filename.
|
[
{
"code": null,
"e": 1600,
"s": 1588,
"text": "Unix - Home"
},
{
"code": null,
"e": 1623,
"s": 1600,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1646,
"s": 1623,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1665,
"s": 1646,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1688,
"s": 1665,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1707,
"s": 1688,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1730,
"s": 1707,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1791,
"s": 1770,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1812,
"s": 1791,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1834,
"s": 1812,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1857,
"s": 1834,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1882,
"s": 1857,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1902,
"s": 1882,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1925,
"s": 1902,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1948,
"s": 1925,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1967,
"s": 1948,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1987,
"s": 1967,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 2014,
"s": 1987,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 2040,
"s": 2014,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 2063,
"s": 2040,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 2086,
"s": 2063,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 2106,
"s": 2086,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 2133,
"s": 2106,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2159,
"s": 2133,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2186,
"s": 2159,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2212,
"s": 2186,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2234,
"s": 2212,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2259,
"s": 2234,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2282,
"s": 2259,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2301,
"s": 2282,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2326,
"s": 2301,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2346,
"s": 2326,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2367,
"s": 2346,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2389,
"s": 2367,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2407,
"s": 2389,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2418,
"s": 2407,
"text": "Who is Who"
},
{
"code": null,
"e": 2453,
"s": 2418,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2593,
"s": 2453,
"text": "#include <linux/types.h> \n#include <linux/dirent.h> \n\nint readdir(unsigned int fd, struct dirent *dirp, \n unsigned int count); \n"
},
{
"code": null,
"e": 2680,
"s": 2593,
"text": "\nint readdir(unsigned int fd, struct dirent *dirp, \n unsigned int count); \n"
},
{
"code": null,
"e": 2866,
"s": 2680,
"text": "\nreaddir() reads one\ndirent structure from the directory\npointed at by\nfd into the memory area pointed to by\ndirp. The parameter\ncount is ignored; at most one dirent structure is read.\n"
},
{
"code": null,
"e": 2913,
"s": 2866,
"text": "\nThe\ndirent structure is declared as follows:\n"
},
{
"code": null,
"e": 3170,
"s": 2915,
"text": "struct dirent\n{\n long d_ino; /* inode number */\n off_t d_off; /* offset to this dirent */\n unsigned short d_reclen; /* length of this d_name */\n char d_name [NAME_MAX+1]; /* filename (null-terminated) */\n}\n"
}
] |
How to Download & Install NLTK on Windows?
|
16 Dec, 2021
NLTK is Natural Language Tool Kit. It is used to build python programming. It helps to work with human languages data. It gives a very easy user interface. It supports classification, steaming, tagging, etc.
In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed.
Step 1: Browse to the official site of python by clicking this link.
Step 2: Move the cursor to the Download button & then click on the latest python version.
Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.
Step 4: Click on Next.
Step 5: Click on Install.
Step 6: Wait till installation finish.
Step 7: Click on Close.
Step 8: Open Command Prompt & execute the following commands:
python --version
pip --version
pip install nltk
Hence, NLTK installation will start.
Step 9: Then you can see the successfully installed message.
Hence NLTK installation is successful
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "NLTK is Natural Language Tool Kit. It is used to build python programming. It helps to work with human languages data. It gives a very easy user interface. It supports classification, steaming, tagging, etc."
},
{
"code": null,
"e": 378,
"s": 236,
"text": "In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed."
},
{
"code": null,
"e": 447,
"s": 378,
"text": "Step 1: Browse to the official site of python by clicking this link."
},
{
"code": null,
"e": 537,
"s": 447,
"text": "Step 2: Move the cursor to the Download button & then click on the latest python version."
},
{
"code": null,
"e": 628,
"s": 537,
"text": "Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation."
},
{
"code": null,
"e": 651,
"s": 628,
"text": "Step 4: Click on Next."
},
{
"code": null,
"e": 677,
"s": 651,
"text": "Step 5: Click on Install."
},
{
"code": null,
"e": 716,
"s": 677,
"text": "Step 6: Wait till installation finish."
},
{
"code": null,
"e": 740,
"s": 716,
"text": "Step 7: Click on Close."
},
{
"code": null,
"e": 802,
"s": 740,
"text": "Step 8: Open Command Prompt & execute the following commands:"
},
{
"code": null,
"e": 850,
"s": 802,
"text": "python --version\npip --version\npip install nltk"
},
{
"code": null,
"e": 887,
"s": 850,
"text": "Hence, NLTK installation will start."
},
{
"code": null,
"e": 948,
"s": 887,
"text": "Step 9: Then you can see the successfully installed message."
},
{
"code": null,
"e": 986,
"s": 948,
"text": "Hence NLTK installation is successful"
},
{
"code": null,
"e": 1001,
"s": 986,
"text": "how-to-install"
},
{
"code": null,
"e": 1008,
"s": 1001,
"text": "Picked"
},
{
"code": null,
"e": 1015,
"s": 1008,
"text": "How To"
},
{
"code": null,
"e": 1034,
"s": 1015,
"text": "Installation Guide"
}
] |
Create Grouped Bar Chart using Altair in Python
|
16 Mar, 2021
Grouped bar charts are a handy tool to represent our data when we want to compare multiple sets of data items one against another. To make a grouped bar chart, we require at least three rows of three columns of data in our dataset. The three columns can be used as- one for values, one for series, and one for categories. In a grouped bar chart, the data values present in a series are represented side by side and are grouped under specific categories so that their values can be represented accordingly over the axis. All the data values belonging to a specific series will always be represented with the same color across all the categories.
Let’s take an example, suppose, we want to compare the runs made by two players across three formats. Here, runs scored by the players act as values, Player name acts as a series and the format of the game acts as the categories. Always, the runs scored by each player will have the same color representation across the different formats.
In this article, we will learn to create a grouped bar chart using Altair library in Python.
As we discussed, we need at least three rows/columns, we will begin with importing necessary libraries and then creating a dataset having three columns using pandas library.
Example 1:
Python
import altair as altimport pandas as pd # creating a custom dataframedata = pd.DataFrame([[264, 'Rohit', 'ODI'], [183, 'Virat', 'ODI'], [118, 'Rohit', 'T20'], [94, 'Virat', 'T20'], [212, 'Rohit','Test'], [254, 'Virat','Test']], columns=['Highest Score', 'Player', 'Format']) print(data)
Output:
Now, that we have a dataset containing three columns, where we want to compare the highest score (values) of two players (series) across different formats (categories).
Python
gp_chart = alt.Chart(data).mark_bar().encode( alt.Column('Format'), alt.X('Player'), alt.Y('Highest Score', axis=alt.Axis(grid=False)), alt.Color('Player')) gp_chart.display()
Output:
We can plot a group chart by calling the alt.Chart() method present inside Altair library. We want our categories to be displayed as the columns so, we can pass Format inside the alt.Column() method, our series (players) will be represented on the x-axis hence we pass Player in the alt.X() field, and our values (runs) should be displayed on y-axis so we pass Highest Score inside the alt.Y() field. Each player should have same color in all formats so, we pass Player inside the alt.Color() method.
Example 2:
Python3
# importing packageimport altair as altimport pandas as pd # create datadata = pd.DataFrame([['A', 10, 20], ['B', 5, 29], ['A', 15, 29], ['B', 15, 20]], columns=['Team', 'Round 1', 'Round 2'])# view dataprint(data) gp_chart = alt.Chart(data).mark_bar().encode( alt.Column('Round 2'), alt.X('Team'), alt.Y('Round 1', axis=alt.Axis(grid=False)), alt.Color('Team')) gp_chart.display()
Output:
Picked
Python-Altair
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 674,
"s": 28,
"text": "Grouped bar charts are a handy tool to represent our data when we want to compare multiple sets of data items one against another. To make a grouped bar chart, we require at least three rows of three columns of data in our dataset. The three columns can be used as- one for values, one for series, and one for categories. In a grouped bar chart, the data values present in a series are represented side by side and are grouped under specific categories so that their values can be represented accordingly over the axis. All the data values belonging to a specific series will always be represented with the same color across all the categories."
},
{
"code": null,
"e": 1013,
"s": 674,
"text": "Let’s take an example, suppose, we want to compare the runs made by two players across three formats. Here, runs scored by the players act as values, Player name acts as a series and the format of the game acts as the categories. Always, the runs scored by each player will have the same color representation across the different formats."
},
{
"code": null,
"e": 1106,
"s": 1013,
"text": "In this article, we will learn to create a grouped bar chart using Altair library in Python."
},
{
"code": null,
"e": 1280,
"s": 1106,
"text": "As we discussed, we need at least three rows/columns, we will begin with importing necessary libraries and then creating a dataset having three columns using pandas library."
},
{
"code": null,
"e": 1291,
"s": 1280,
"text": "Example 1:"
},
{
"code": null,
"e": 1298,
"s": 1291,
"text": "Python"
},
{
"code": "import altair as altimport pandas as pd # creating a custom dataframedata = pd.DataFrame([[264, 'Rohit', 'ODI'], [183, 'Virat', 'ODI'], [118, 'Rohit', 'T20'], [94, 'Virat', 'T20'], [212, 'Rohit','Test'], [254, 'Virat','Test']], columns=['Highest Score', 'Player', 'Format']) print(data)",
"e": 1710,
"s": 1298,
"text": null
},
{
"code": null,
"e": 1718,
"s": 1710,
"text": "Output:"
},
{
"code": null,
"e": 1887,
"s": 1718,
"text": "Now, that we have a dataset containing three columns, where we want to compare the highest score (values) of two players (series) across different formats (categories)."
},
{
"code": null,
"e": 1894,
"s": 1887,
"text": "Python"
},
{
"code": "gp_chart = alt.Chart(data).mark_bar().encode( alt.Column('Format'), alt.X('Player'), alt.Y('Highest Score', axis=alt.Axis(grid=False)), alt.Color('Player')) gp_chart.display()",
"e": 2075,
"s": 1894,
"text": null
},
{
"code": null,
"e": 2083,
"s": 2075,
"text": "Output:"
},
{
"code": null,
"e": 2585,
"s": 2083,
"text": "We can plot a group chart by calling the alt.Chart() method present inside Altair library. We want our categories to be displayed as the columns so, we can pass Format inside the alt.Column() method, our series (players) will be represented on the x-axis hence we pass Player in the alt.X() field, and our values (runs) should be displayed on y-axis so we pass Highest Score inside the alt.Y() field. Each player should have same color in all formats so, we pass Player inside the alt.Color() method. "
},
{
"code": null,
"e": 2596,
"s": 2585,
"text": "Example 2:"
},
{
"code": null,
"e": 2604,
"s": 2596,
"text": "Python3"
},
{
"code": "# importing packageimport altair as altimport pandas as pd # create datadata = pd.DataFrame([['A', 10, 20], ['B', 5, 29], ['A', 15, 29], ['B', 15, 20]], columns=['Team', 'Round 1', 'Round 2'])# view dataprint(data) gp_chart = alt.Chart(data).mark_bar().encode( alt.Column('Round 2'), alt.X('Team'), alt.Y('Round 1', axis=alt.Axis(grid=False)), alt.Color('Team')) gp_chart.display()",
"e": 3077,
"s": 2604,
"text": null
},
{
"code": null,
"e": 3085,
"s": 3077,
"text": "Output:"
},
{
"code": null,
"e": 3092,
"s": 3085,
"text": "Picked"
},
{
"code": null,
"e": 3106,
"s": 3092,
"text": "Python-Altair"
},
{
"code": null,
"e": 3113,
"s": 3106,
"text": "Python"
}
] |
Introduction to Processing | Java
|
07 May, 2020
Processing is an open-source low level animation and GUI library built on Java with additional simplifications like additional classes, aliased mathematical functions and operations. It also provides a GUI for simple compilation of the programs written in processing.
Features of Processing: The following are the features of processing:
It includes a sketchbook which is a minimalistic alternative to an IDE. This sketchbook can be used as a normal IDE to organize projects.
Every sketch drawn in processing is a subclass of the Java class(PApplet). This class implements almost all the features of processing.
Since processing inherits the properties of the class, all the additional classes defined in the sketch will be treated as an inner class when the code is being converted into a pure java code before compiling. Therefore, the use of static variables and methods is strictly prohibited in processing.
The processing language also gives the users an option to create own classes in the PApplet sketch. Therefore, this gives the users a chance to use a more complex data structures apart from the basic data types in java.
Installing Processing: In order to code in the processing language, the users can either download processing sketchbook from the official website. Apart from that, the users can also download the code jar file and set it up in any of the IDE to use processing.
Example: The following is an example to get an understanding of how to code in processing. Let’s see how to draw a circle in processing. In order to do this, we need to learn about the main function that processing invokes from its library. That means, we only have to define this function but not invoke it.
Below is a sample processing code which draws a circle:
// This function is called whenever we// start the app.void setup(){ // This function is a built in function // in processing which takes two // arguments: width and height // 400, 400 means a window of // length 400 pixels and width // 400 pixels size(400, 400);} // This function is called once per// frame. That is, if the frame rate// is 60, then this will be called// 60 times in one secondvoid draw(){ // This is also an inbuilt function // which can take 4, 3 or 1 argument // where each argument represents the // intensity of each colour like: // 4 = (red, green, blue alpha) // 3 = (red, green, blue) // 1 = (gray_scale_value) background(0); // This command draws the circle // on our canvas at x=width/2, // y=height/2, diameter=200 circle(width / 2, height / 2, 200);}
Output: The output for the above program is:
Algorithms
Java
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 May, 2020"
},
{
"code": null,
"e": 322,
"s": 54,
"text": "Processing is an open-source low level animation and GUI library built on Java with additional simplifications like additional classes, aliased mathematical functions and operations. It also provides a GUI for simple compilation of the programs written in processing."
},
{
"code": null,
"e": 392,
"s": 322,
"text": "Features of Processing: The following are the features of processing:"
},
{
"code": null,
"e": 530,
"s": 392,
"text": "It includes a sketchbook which is a minimalistic alternative to an IDE. This sketchbook can be used as a normal IDE to organize projects."
},
{
"code": null,
"e": 666,
"s": 530,
"text": "Every sketch drawn in processing is a subclass of the Java class(PApplet). This class implements almost all the features of processing."
},
{
"code": null,
"e": 966,
"s": 666,
"text": "Since processing inherits the properties of the class, all the additional classes defined in the sketch will be treated as an inner class when the code is being converted into a pure java code before compiling. Therefore, the use of static variables and methods is strictly prohibited in processing."
},
{
"code": null,
"e": 1186,
"s": 966,
"text": "The processing language also gives the users an option to create own classes in the PApplet sketch. Therefore, this gives the users a chance to use a more complex data structures apart from the basic data types in java."
},
{
"code": null,
"e": 1447,
"s": 1186,
"text": "Installing Processing: In order to code in the processing language, the users can either download processing sketchbook from the official website. Apart from that, the users can also download the code jar file and set it up in any of the IDE to use processing."
},
{
"code": null,
"e": 1756,
"s": 1447,
"text": "Example: The following is an example to get an understanding of how to code in processing. Let’s see how to draw a circle in processing. In order to do this, we need to learn about the main function that processing invokes from its library. That means, we only have to define this function but not invoke it."
},
{
"code": null,
"e": 1812,
"s": 1756,
"text": "Below is a sample processing code which draws a circle:"
},
{
"code": "// This function is called whenever we// start the app.void setup(){ // This function is a built in function // in processing which takes two // arguments: width and height // 400, 400 means a window of // length 400 pixels and width // 400 pixels size(400, 400);} // This function is called once per// frame. That is, if the frame rate// is 60, then this will be called// 60 times in one secondvoid draw(){ // This is also an inbuilt function // which can take 4, 3 or 1 argument // where each argument represents the // intensity of each colour like: // 4 = (red, green, blue alpha) // 3 = (red, green, blue) // 1 = (gray_scale_value) background(0); // This command draws the circle // on our canvas at x=width/2, // y=height/2, diameter=200 circle(width / 2, height / 2, 200);}",
"e": 2655,
"s": 1812,
"text": null
},
{
"code": null,
"e": 2700,
"s": 2655,
"text": "Output: The output for the above program is:"
},
{
"code": null,
"e": 2711,
"s": 2700,
"text": "Algorithms"
},
{
"code": null,
"e": 2716,
"s": 2711,
"text": "Java"
},
{
"code": null,
"e": 2721,
"s": 2716,
"text": "Java"
},
{
"code": null,
"e": 2732,
"s": 2721,
"text": "Algorithms"
}
] |
How to set active tab style with AngularJS?
|
19 Aug, 2020
To set an active tab style using AngularJS we need to use isActive and the ng-controller method .
Method 1:
The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions and variables that can be called on some event like click, etc to perform certain action.
Syntax:
<element ng-controller="expression"> Contents... </element>
Below example implements the above approach:
Let us look at this through a simple code. This is one of the simplest way to do it.
Example 1:
<!DOCTYPE html><html> <head> </head> <body> <div class="collapse navbar-collapse" ng-controller="HeaderController"> <ul class="nav navbar-nav"> <li ng-class="{ active: isActive('/')}"> <a href="/">Geeks For Geeks</a></li> <li ng-class="{ active: isActive('/html')}"> <a href="/html">HTML</a></li> <li ng-class="{ active: isActive('/js')}"> <a href="/js">JAVASCRIPT</a></li> </ul> </div> <div ng-view></div> <script> function HeaderController($scope, $location) { $scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; } </script> </body></html>
Output:
Method 2:
Here we will use the modular function in Angular JS to create a module. A module is created by using the AngularJS function angular.module .
Syntax for creating a module:
<div ng-app="myFirstApp">...</div>
<script>
var app = angular.module("myFirstApp", []);
//myFirstApp refers to HTML element in which application runs.
</script>
Syntax for adding a directive to the module:
<div ng-app="myApp"></div>
<script>
var my_app = angular.module("myFirstApp", []);
my_app.directive("DirectiveApp", function() {
return {
template : "Hello Geeks!!!"
};
});
</script>
Example 2:
<!DOCTYPE html><html><head></head><body> <div ng-app="link"> <a href="#Geeks For Geeks" active-link="active">Geeks For Geeks</a> <a href="#HTML" active-link="active">HTML</a> <a href="#JAVASCRIPT" active-link="active">JAVASCRIPT</a> </div> <script> angular.module('link', []).directive( 'Link', ['$location', function(location) { return { link: function(scope, element, attrs) { var active = attrs.activeLink; var path = attrs.href; path = path.substring(1); scope.location = location; scope.$watch( 'location.path()', function(newPath) { if (path === newPath) { element.addClass(active); } else { element.removeClass(active); } }); } }; }]); </script></body></html>
Output:
AngularJS-Misc
Picked
AngularJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
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
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "To set an active tab style using AngularJS we need to use isActive and the ng-controller method ."
},
{
"code": null,
"e": 136,
"s": 126,
"text": "Method 1:"
},
{
"code": null,
"e": 354,
"s": 136,
"text": "The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions and variables that can be called on some event like click, etc to perform certain action."
},
{
"code": null,
"e": 362,
"s": 354,
"text": "Syntax:"
},
{
"code": null,
"e": 422,
"s": 362,
"text": "<element ng-controller=\"expression\"> Contents... </element>"
},
{
"code": null,
"e": 467,
"s": 422,
"text": "Below example implements the above approach:"
},
{
"code": null,
"e": 552,
"s": 467,
"text": "Let us look at this through a simple code. This is one of the simplest way to do it."
},
{
"code": null,
"e": 563,
"s": 552,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <div class=\"collapse navbar-collapse\" ng-controller=\"HeaderController\"> <ul class=\"nav navbar-nav\"> <li ng-class=\"{ active: isActive('/')}\"> <a href=\"/\">Geeks For Geeks</a></li> <li ng-class=\"{ active: isActive('/html')}\"> <a href=\"/html\">HTML</a></li> <li ng-class=\"{ active: isActive('/js')}\"> <a href=\"/js\">JAVASCRIPT</a></li> </ul> </div> <div ng-view></div> <script> function HeaderController($scope, $location) { $scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; } </script> </body></html>",
"e": 1388,
"s": 563,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1406,
"s": 1396,
"text": "Method 2:"
},
{
"code": null,
"e": 1547,
"s": 1406,
"text": "Here we will use the modular function in Angular JS to create a module. A module is created by using the AngularJS function angular.module ."
},
{
"code": null,
"e": 1577,
"s": 1547,
"text": "Syntax for creating a module:"
},
{
"code": null,
"e": 1740,
"s": 1577,
"text": "<div ng-app=\"myFirstApp\">...</div>\n<script>\nvar app = angular.module(\"myFirstApp\", []);\n \n//myFirstApp refers to HTML element in which application runs.\n</script>"
},
{
"code": null,
"e": 1785,
"s": 1740,
"text": "Syntax for adding a directive to the module:"
},
{
"code": null,
"e": 1976,
"s": 1785,
"text": "<div ng-app=\"myApp\"></div>\n<script>\nvar my_app = angular.module(\"myFirstApp\", []);\nmy_app.directive(\"DirectiveApp\", function() {\n return {\n template : \"Hello Geeks!!!\"\n };\n});\n</script>"
},
{
"code": null,
"e": 1987,
"s": 1976,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html><head></head><body> <div ng-app=\"link\"> <a href=\"#Geeks For Geeks\" active-link=\"active\">Geeks For Geeks</a> <a href=\"#HTML\" active-link=\"active\">HTML</a> <a href=\"#JAVASCRIPT\" active-link=\"active\">JAVASCRIPT</a> </div> <script> angular.module('link', []).directive( 'Link', ['$location', function(location) { return { link: function(scope, element, attrs) { var active = attrs.activeLink; var path = attrs.href; path = path.substring(1); scope.location = location; scope.$watch( 'location.path()', function(newPath) { if (path === newPath) { element.addClass(active); } else { element.removeClass(active); } }); } }; }]); </script></body></html>",
"e": 3108,
"s": 1987,
"text": null
},
{
"code": null,
"e": 3116,
"s": 3108,
"text": "Output:"
},
{
"code": null,
"e": 3131,
"s": 3116,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3138,
"s": 3131,
"text": "Picked"
},
{
"code": null,
"e": 3148,
"s": 3138,
"text": "AngularJS"
},
{
"code": null,
"e": 3159,
"s": 3148,
"text": "JavaScript"
},
{
"code": null,
"e": 3176,
"s": 3159,
"text": "Web Technologies"
},
{
"code": null,
"e": 3274,
"s": 3176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3305,
"s": 3274,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 3329,
"s": 3305,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 3371,
"s": 3329,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 3406,
"s": 3371,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3480,
"s": 3406,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 3541,
"s": 3480,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3613,
"s": 3541,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3653,
"s": 3613,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3706,
"s": 3653,
"text": "Hide or show elements in HTML using display property"
}
] |
PostgreSQL – SELECT INTO
|
28 Aug, 2020
In PostgreSQL, the SELECT INTO statement allows users to create a new table and inserts data returned by a query. The new table columns have names and data types linked with the output columns of the SELECT clause. Unlike the SELECT statement, the SELECT INTO statement does not return data to the client.
Syntax:
SELECT
column_list
INTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] new_table_name
FROM
table_name
WHERE
condition;
In the process of creating a new table with the structure and data derived from a query result set, one has to specify the new table name in the INTO clause. The TEMP or TEMPORARY keyword is optional; it allows users to create a temporary table instead.The WHERE clause allows users to specify the data from the original tables that should be inserted into the new table. Besides the WHERE clause, one can use other clauses in the SELECT statement for the SELECT INTO statement such as INNER JOIN, LEFT JOIN, GROUP BY, and HAVING.
Now let’s look into some examples.For examples we will be using the sample database (ie, dvdrental).
Example 1:In this example, we will use the film table from the dvdrental database to create a new table named film_r that contains all films with the rating of R and has a 5-day rental duration using the below statement:
SELECT
film_id,
title,
rental_rate
INTO TABLE film_r
FROM
film
WHERE
rating = 'R'
AND rental_duration = 5
ORDER BY
title;
Now we can verify the created table using the below statement:
SELECT
*
FROM
film_r;
Output:
Example 2:In this example, we create a temporary table named short_film that has all films whose lengths are under 60 minutes using the below statement:
SELECT
film_id,
title,
length
INTO TEMP TABLE short_film
FROM
film
WHERE
length < 60
ORDER BY
title;
Now we verify the table short_film using the below statement:
SELECT
*
FROM
short_film;
Output:
Note: One cannot use the SELECT INTO statement in PL/pgSQL or ECPG because they interpret the INTO clause differently. In this case, you can use the CREATE TABLE AS statement which provides more functionality than the SELECT INTO statement.
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 334,
"s": 28,
"text": "In PostgreSQL, the SELECT INTO statement allows users to create a new table and inserts data returned by a query. The new table columns have names and data types linked with the output columns of the SELECT clause. Unlike the SELECT statement, the SELECT INTO statement does not return data to the client."
},
{
"code": null,
"e": 469,
"s": 334,
"text": "Syntax:\nSELECT\n column_list \nINTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] new_table_name\nFROM\n table_name\nWHERE\n condition;"
},
{
"code": null,
"e": 1000,
"s": 469,
"text": "In the process of creating a new table with the structure and data derived from a query result set, one has to specify the new table name in the INTO clause. The TEMP or TEMPORARY keyword is optional; it allows users to create a temporary table instead.The WHERE clause allows users to specify the data from the original tables that should be inserted into the new table. Besides the WHERE clause, one can use other clauses in the SELECT statement for the SELECT INTO statement such as INNER JOIN, LEFT JOIN, GROUP BY, and HAVING."
},
{
"code": null,
"e": 1101,
"s": 1000,
"text": "Now let’s look into some examples.For examples we will be using the sample database (ie, dvdrental)."
},
{
"code": null,
"e": 1322,
"s": 1101,
"text": "Example 1:In this example, we will use the film table from the dvdrental database to create a new table named film_r that contains all films with the rating of R and has a 5-day rental duration using the below statement:"
},
{
"code": null,
"e": 1468,
"s": 1322,
"text": "SELECT\n film_id,\n title,\n rental_rate\nINTO TABLE film_r\nFROM\n film\nWHERE\n rating = 'R'\nAND rental_duration = 5\nORDER BY\n title;"
},
{
"code": null,
"e": 1531,
"s": 1468,
"text": "Now we can verify the created table using the below statement:"
},
{
"code": null,
"e": 1561,
"s": 1531,
"text": "SELECT\n *\nFROM\n film_r;"
},
{
"code": null,
"e": 1569,
"s": 1561,
"text": "Output:"
},
{
"code": null,
"e": 1722,
"s": 1569,
"text": "Example 2:In this example, we create a temporary table named short_film that has all films whose lengths are under 60 minutes using the below statement:"
},
{
"code": null,
"e": 1848,
"s": 1722,
"text": "SELECT\n film_id,\n title,\n length \nINTO TEMP TABLE short_film\nFROM\n film\nWHERE\n length < 60\nORDER BY\n title;"
},
{
"code": null,
"e": 1910,
"s": 1848,
"text": "Now we verify the table short_film using the below statement:"
},
{
"code": null,
"e": 1944,
"s": 1910,
"text": "SELECT\n *\nFROM\n short_film;"
},
{
"code": null,
"e": 1952,
"s": 1944,
"text": "Output:"
},
{
"code": null,
"e": 2193,
"s": 1952,
"text": "Note: One cannot use the SELECT INTO statement in PL/pgSQL or ECPG because they interpret the INTO clause differently. In this case, you can use the CREATE TABLE AS statement which provides more functionality than the SELECT INTO statement."
},
{
"code": null,
"e": 2211,
"s": 2193,
"text": "postgreSQL-basics"
},
{
"code": null,
"e": 2222,
"s": 2211,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2320,
"s": 2222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2347,
"s": 2320,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 2379,
"s": 2347,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 2402,
"s": 2379,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 2442,
"s": 2402,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 2480,
"s": 2442,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2514,
"s": 2480,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 2538,
"s": 2514,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2593,
"s": 2538,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 2617,
"s": 2593,
"text": "PostgreSQL - Copy Table"
}
] |
Java Program to Find 2 Elements in the Array such that Difference Between them is Largest
|
26 Mar, 2021
An array is the most efficient data structure that is designed to store and access a group of objects. Given an array of integers, our task is to find out two elements from that array such that the difference between them is the maximum.
We will be discussing two approaches:
By comparing and checking the difference between every possible pair by running two loops.By calculating the min and max values of the array and returning the difference between them.
By comparing and checking the difference between every possible pair by running two loops.
By calculating the min and max values of the array and returning the difference between them.
Input : arr = {2, 3, 10, 6, 4, 8, 1}
Output : Two elements with largest difference: 10 and 1
Explanation : The maximum difference is between 10 and 1.
Input : arr = {-7, 9, 5, 6, 3, 2}
Output : Two elements with largest difference: 9 and -7
Explanation : The maximum difference is between 9 and -7.
Input : arr = {10, 11, 88, 2, 12, 120}
Output : Two elements with largest difference: 2 and 120
Explanation : The maximum difference is between 2 and 120.
Method 1: By comparing and checking the difference between every possible pair by running two loops
Use two loops. In the outer loop, pick elements one by one, and in the inner loop calculate the difference of the picked element with every other element in the array.
And simultaneously compare the difference with the maximum difference calculated so far.
Check for all possible differences between any 2 elements in the array and finally select the elements whose difference is the largest.
Below is the implementation of the above approach :
Java
// Java Program to Find 2// Elements in an array// such that the difference// between them is the largest import java.io.*; class Largest_Difference_GFG { public static int[] Maximum_Diff(int a[], int n) { int diff, greatest_diff = a[1] - a[0]; int ele1 = a[1], ele2 = a[0]; // Array to store the difference and the // two elements ele1 and ele2 . int res[] = new int[3]; // Check for all possible difference between // any 2 elements in the array and finally select // the elements whose difference is the largest for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { diff = Math.abs(a[i] - a[j]); if (diff > greatest_diff) { greatest_diff = diff; ele1 = a[i]; ele2 = a[j]; } } } res[0] = greatest_diff; res[1] = ele1; res[2] = ele2; return (res); } public static void main(String[] args) { int arr[] = { 10, 11, 88, 2, 12, 120 }; int size = arr.length; int[] result; result = Largest_Difference_GFG.Maximum_Diff(arr, size); System.out.println("Greatest Difference:" + result[0]); System.out.println( "Two elements with largest difference: " + result[1] + " and " + result[2]); }}
Greatest Difference:118
Two elements with largest difference: 2 and 120
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Method 2: By calculating the min and max values of the array and returning the difference between them
The Largest difference between 2 elements in an array will be always the absolute difference between the smallest and largest element present in that array.
Using 2 independent for loops, determine the min and max element of the array. Below is the implementation of the above approach :
Java
// Java Program to Find 2// Elements in an array// such that the difference// between them is the largestimport java.util.*;class GFG { public static void main(String args[]) { int array[] = new int[] { 10, 11, 88, 2, 12, 120 }; int len = array.length; Arrays.sort(array); // sorting the array int max_diff = array[len - 1] - array[0]; System.out.println("Maximum Difference is: " + max_diff); System.out.println( "Two elements with largest difference: " + array[0] + " and " + array[len - 1]); }}
Maximum Difference is: 118
Two elements with largest difference: 2 and 120
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: Both Minimum and Maximum element in the above code can also be determined in a single for loop by comparing every element of an array with the minValue and maxValue and update them accordingly. In this way, a single for loop can return both the minValue and maxValue, and the lines of code will be reduced.
akashroynet
Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 290,
"s": 52,
"text": "An array is the most efficient data structure that is designed to store and access a group of objects. Given an array of integers, our task is to find out two elements from that array such that the difference between them is the maximum."
},
{
"code": null,
"e": 328,
"s": 290,
"text": "We will be discussing two approaches:"
},
{
"code": null,
"e": 512,
"s": 328,
"text": "By comparing and checking the difference between every possible pair by running two loops.By calculating the min and max values of the array and returning the difference between them."
},
{
"code": null,
"e": 603,
"s": 512,
"text": "By comparing and checking the difference between every possible pair by running two loops."
},
{
"code": null,
"e": 697,
"s": 603,
"text": "By calculating the min and max values of the array and returning the difference between them."
},
{
"code": null,
"e": 1157,
"s": 697,
"text": "Input : arr = {2, 3, 10, 6, 4, 8, 1}\nOutput : Two elements with largest difference: 10 and 1\nExplanation : The maximum difference is between 10 and 1.\n \nInput : arr = {-7, 9, 5, 6, 3, 2}\nOutput : Two elements with largest difference: 9 and -7\nExplanation : The maximum difference is between 9 and -7.\n \nInput : arr = {10, 11, 88, 2, 12, 120}\nOutput : Two elements with largest difference: 2 and 120\nExplanation : The maximum difference is between 2 and 120."
},
{
"code": null,
"e": 1257,
"s": 1157,
"text": "Method 1: By comparing and checking the difference between every possible pair by running two loops"
},
{
"code": null,
"e": 1425,
"s": 1257,
"text": "Use two loops. In the outer loop, pick elements one by one, and in the inner loop calculate the difference of the picked element with every other element in the array."
},
{
"code": null,
"e": 1514,
"s": 1425,
"text": "And simultaneously compare the difference with the maximum difference calculated so far."
},
{
"code": null,
"e": 1650,
"s": 1514,
"text": "Check for all possible differences between any 2 elements in the array and finally select the elements whose difference is the largest."
},
{
"code": null,
"e": 1703,
"s": 1650,
"text": " Below is the implementation of the above approach :"
},
{
"code": null,
"e": 1708,
"s": 1703,
"text": "Java"
},
{
"code": "// Java Program to Find 2// Elements in an array// such that the difference// between them is the largest import java.io.*; class Largest_Difference_GFG { public static int[] Maximum_Diff(int a[], int n) { int diff, greatest_diff = a[1] - a[0]; int ele1 = a[1], ele2 = a[0]; // Array to store the difference and the // two elements ele1 and ele2 . int res[] = new int[3]; // Check for all possible difference between // any 2 elements in the array and finally select // the elements whose difference is the largest for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { diff = Math.abs(a[i] - a[j]); if (diff > greatest_diff) { greatest_diff = diff; ele1 = a[i]; ele2 = a[j]; } } } res[0] = greatest_diff; res[1] = ele1; res[2] = ele2; return (res); } public static void main(String[] args) { int arr[] = { 10, 11, 88, 2, 12, 120 }; int size = arr.length; int[] result; result = Largest_Difference_GFG.Maximum_Diff(arr, size); System.out.println(\"Greatest Difference:\" + result[0]); System.out.println( \"Two elements with largest difference: \" + result[1] + \" and \" + result[2]); }}",
"e": 3189,
"s": 1708,
"text": null
},
{
"code": null,
"e": 3262,
"s": 3189,
"text": "Greatest Difference:118\nTwo elements with largest difference: 2 and 120\n"
},
{
"code": null,
"e": 3286,
"s": 3262,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 3308,
"s": 3286,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3411,
"s": 3308,
"text": "Method 2: By calculating the min and max values of the array and returning the difference between them"
},
{
"code": null,
"e": 3568,
"s": 3411,
"text": "The Largest difference between 2 elements in an array will be always the absolute difference between the smallest and largest element present in that array."
},
{
"code": null,
"e": 3699,
"s": 3568,
"text": "Using 2 independent for loops, determine the min and max element of the array. Below is the implementation of the above approach :"
},
{
"code": null,
"e": 3704,
"s": 3699,
"text": "Java"
},
{
"code": "// Java Program to Find 2// Elements in an array// such that the difference// between them is the largestimport java.util.*;class GFG { public static void main(String args[]) { int array[] = new int[] { 10, 11, 88, 2, 12, 120 }; int len = array.length; Arrays.sort(array); // sorting the array int max_diff = array[len - 1] - array[0]; System.out.println(\"Maximum Difference is: \" + max_diff); System.out.println( \"Two elements with largest difference: \" + array[0] + \" and \" + array[len - 1]); }}",
"e": 4303,
"s": 3704,
"text": null
},
{
"code": null,
"e": 4379,
"s": 4303,
"text": "Maximum Difference is: 118\nTwo elements with largest difference: 2 and 120\n"
},
{
"code": null,
"e": 4401,
"s": 4379,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4423,
"s": 4401,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4736,
"s": 4423,
"text": "Note: Both Minimum and Maximum element in the above code can also be determined in a single for loop by comparing every element of an array with the minValue and maxValue and update them accordingly. In this way, a single for loop can return both the minValue and maxValue, and the lines of code will be reduced."
},
{
"code": null,
"e": 4748,
"s": 4736,
"text": "akashroynet"
},
{
"code": null,
"e": 4768,
"s": 4748,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 4773,
"s": 4768,
"text": "Java"
},
{
"code": null,
"e": 4787,
"s": 4773,
"text": "Java Programs"
},
{
"code": null,
"e": 4792,
"s": 4787,
"text": "Java"
}
] |
Nested Decorators in Python
|
25 Aug, 2021
Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value.
Nesting means placing or storing inside the other. Therefore, Nested Decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates the several effects together.
A function can be decorated multiple times. We need to define the decorator first that we want to wrap the output string with, and then apply them to the function using the ‘@’ . One simply needs to place the decorators above the desired function.
Syntax :
@function1
@function2
def function(name):
print(f"{name}")
Nested decorators follow a bottom to top approach i.e the reverse order. It can be related to a construction of building where we start the construction from the bottom (the ground) and then start building the floors.
Example :
Python3
# Python program to demonstrate# nested decorators def italic(func): def wrapper(): return '<i>' + func() + '</i>' return wrapper def strong(func): def wrapper(): return '<strong>' + func() + '</strong>' return wrapper @italic@strongdef introduction(): return 'This is a basic program' print(introduction())
Output:
<i><strong>This is a basic program</strong></i>
Explanation :
We have defined two decorators first, which are used in wrapping the output string of the decorated function in the ‘strong’ and ‘italic’ tags of HTML.Then we are applying the two decorators to our ‘introduction’ function by using just an “@” and the function name. For example in this program we are using @italic and @strong.The hierarchy that it follows is from bottom to top. Therefore according to it the string is wrapped with ‘strong’ first an then with ‘italic’.
We have defined two decorators first, which are used in wrapping the output string of the decorated function in the ‘strong’ and ‘italic’ tags of HTML.
Then we are applying the two decorators to our ‘introduction’ function by using just an “@” and the function name. For example in this program we are using @italic and @strong.
The hierarchy that it follows is from bottom to top. Therefore according to it the string is wrapped with ‘strong’ first an then with ‘italic’.
surinderdawra388
simmytarika5
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 352,
"s": 54,
"text": "Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. "
},
{
"code": null,
"e": 663,
"s": 352,
"text": "Nesting means placing or storing inside the other. Therefore, Nested Decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates the several effects together."
},
{
"code": null,
"e": 911,
"s": 663,
"text": "A function can be decorated multiple times. We need to define the decorator first that we want to wrap the output string with, and then apply them to the function using the ‘@’ . One simply needs to place the decorators above the desired function."
},
{
"code": null,
"e": 920,
"s": 911,
"text": "Syntax :"
},
{
"code": null,
"e": 985,
"s": 920,
"text": "@function1\n@function2\ndef function(name):\n print(f\"{name}\")"
},
{
"code": null,
"e": 1204,
"s": 985,
"text": "Nested decorators follow a bottom to top approach i.e the reverse order. It can be related to a construction of building where we start the construction from the bottom (the ground) and then start building the floors."
},
{
"code": null,
"e": 1214,
"s": 1204,
"text": "Example :"
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# nested decorators def italic(func): def wrapper(): return '<i>' + func() + '</i>' return wrapper def strong(func): def wrapper(): return '<strong>' + func() + '</strong>' return wrapper @italic@strongdef introduction(): return 'This is a basic program' print(introduction())",
"e": 1580,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1580,
"text": "Output:"
},
{
"code": null,
"e": 1636,
"s": 1588,
"text": "<i><strong>This is a basic program</strong></i>"
},
{
"code": null,
"e": 1650,
"s": 1636,
"text": "Explanation :"
},
{
"code": null,
"e": 2121,
"s": 1650,
"text": "We have defined two decorators first, which are used in wrapping the output string of the decorated function in the ‘strong’ and ‘italic’ tags of HTML.Then we are applying the two decorators to our ‘introduction’ function by using just an “@” and the function name. For example in this program we are using @italic and @strong.The hierarchy that it follows is from bottom to top. Therefore according to it the string is wrapped with ‘strong’ first an then with ‘italic’."
},
{
"code": null,
"e": 2273,
"s": 2121,
"text": "We have defined two decorators first, which are used in wrapping the output string of the decorated function in the ‘strong’ and ‘italic’ tags of HTML."
},
{
"code": null,
"e": 2450,
"s": 2273,
"text": "Then we are applying the two decorators to our ‘introduction’ function by using just an “@” and the function name. For example in this program we are using @italic and @strong."
},
{
"code": null,
"e": 2594,
"s": 2450,
"text": "The hierarchy that it follows is from bottom to top. Therefore according to it the string is wrapped with ‘strong’ first an then with ‘italic’."
},
{
"code": null,
"e": 2611,
"s": 2594,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2624,
"s": 2611,
"text": "simmytarika5"
},
{
"code": null,
"e": 2642,
"s": 2624,
"text": "Python Decorators"
},
{
"code": null,
"e": 2649,
"s": 2642,
"text": "Python"
},
{
"code": null,
"e": 2747,
"s": 2649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2765,
"s": 2747,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2807,
"s": 2765,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2829,
"s": 2807,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2864,
"s": 2829,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2890,
"s": 2864,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2922,
"s": 2890,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2951,
"s": 2922,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2981,
"s": 2951,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3008,
"s": 2981,
"text": "Python Classes and Objects"
}
] |
numpy.finfo() function – Python
|
18 Jun, 2020
numpy.finfo() function shows machine limits for floating point types.
Syntax : numpy.finfo(dtype)
Parameters :dtype : [float, dtype, or instance] Kind of floating point data-type about which to get information.Return : Machine parameters for floating point types.
Code #1 :
# Python program explaining# numpy.finfo() function # importing numpy as geek import numpy as geek gfg = geek.finfo(geek.float32) print (gfg)
Output :
Machine parameters for float32
---------------------------------------------------------------
precision = 6 resolution = 1.0000000e-06
machep = -23 eps = 1.1920929e-07
negep = -24 epsneg = 5.9604645e-08
minexp = -126 tiny = 1.1754944e-38
maxexp = 128 max = 3.4028235e+38
nexp = 8 min = -max
---------------------------------------------------------------
Code #2 :
# Python program explaining# numpy.finfo() function # importing numpy as geek import numpy as geek gfg = geek.finfo(geek.float64) print (gfg)
Output :
Machine parameters for float64
---------------------------------------------------------------
precision = 15 resolution = 1.0000000000000001e-15
machep = -52 eps = 2.2204460492503131e-16
negep = -53 epsneg = 1.1102230246251565e-16
minexp = -1022 tiny = 2.2250738585072014e-308
maxexp = 1024 max = 1.7976931348623157e+308
nexp = 11 min = -max
---------------------------------------------------------------
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 98,
"s": 28,
"text": "numpy.finfo() function shows machine limits for floating point types."
},
{
"code": null,
"e": 126,
"s": 98,
"text": "Syntax : numpy.finfo(dtype)"
},
{
"code": null,
"e": 292,
"s": 126,
"text": "Parameters :dtype : [float, dtype, or instance] Kind of floating point data-type about which to get information.Return : Machine parameters for floating point types."
},
{
"code": null,
"e": 302,
"s": 292,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.finfo() function # importing numpy as geek import numpy as geek gfg = geek.finfo(geek.float32) print (gfg)",
"e": 465,
"s": 302,
"text": null
},
{
"code": null,
"e": 474,
"s": 465,
"text": "Output :"
},
{
"code": null,
"e": 895,
"s": 474,
"text": "Machine parameters for float32\n---------------------------------------------------------------\nprecision = 6 resolution = 1.0000000e-06\nmachep = -23 eps = 1.1920929e-07\nnegep = -24 epsneg = 5.9604645e-08\nminexp = -126 tiny = 1.1754944e-38\nmaxexp = 128 max = 3.4028235e+38\nnexp = 8 min = -max\n---------------------------------------------------------------\n"
},
{
"code": null,
"e": 906,
"s": 895,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.finfo() function # importing numpy as geek import numpy as geek gfg = geek.finfo(geek.float64) print (gfg)",
"e": 1069,
"s": 906,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1069,
"text": "Output :"
},
{
"code": null,
"e": 1546,
"s": 1078,
"text": "Machine parameters for float64\n---------------------------------------------------------------\nprecision = 15 resolution = 1.0000000000000001e-15\nmachep = -52 eps = 2.2204460492503131e-16\nnegep = -53 epsneg = 1.1102230246251565e-16\nminexp = -1022 tiny = 2.2250738585072014e-308\nmaxexp = 1024 max = 1.7976931348623157e+308\nnexp = 11 min = -max\n---------------------------------------------------------------\n"
},
{
"code": null,
"e": 1559,
"s": 1546,
"text": "Python-numpy"
},
{
"code": null,
"e": 1566,
"s": 1559,
"text": "Python"
}
] |
Grouping and Aggregating with Pandas
|
15 Mar, 2021
In this article, we are going to see grouping and aggregating using pandas. Grouping and aggregating will help to achieve data analysis easily using various functions. These methods will help us to the group and summarize our data and make complex analysis comparatively easy.
Creating a sample dataset of marks of various subjects.
Python
# import moduleimport pandas as pd # Creating our datasetdf = pd.DataFrame([[9, 4, 8, 9], [8, 10, 7, 6], [7, 6, 8, 5]], columns=['Maths', 'English', 'Science', 'History']) # display datasetprint(df)
Output:
Aggregation in pandas provides various functions that perform a mathematical or logical operation on our dataset and returns a summary of that function. Aggregation can be used to get a summary of columns in our dataset like getting sum, minimum, maximum, etc. from a particular column of our dataset. The function used for aggregation is agg(), the parameter is the function we want to perform.
Some functions used in the aggregation are:
Function Description:
sum() :Compute sum of column values
min() :Compute min of column values
max() :Compute max of column values
mean() :Compute mean of column
size() :Compute column sizes
describe() :Generates descriptive statistics
first() :Compute first of group values
last() :Compute last of group values
count() :Compute count of column values
std() :Standard deviation of column
var() :Compute variance of column
sem() :Standard error of the mean of column
Examples:
The sum() function is used to calculate the sum of every value.
Python
df.sum()
Output:
The describe() function is used to get a summary of our dataset
Python
df.describe()
Output:
We used agg() function to calculate the sum, min, and max of each column in our dataset.
Python
df.agg(['sum', 'min', 'max'])
Output:
Grouping is used to group data using some criteria from our dataset. It is used as split-apply-combine strategy.
Splitting the data into groups based on some criteria.
Applying a function to each group independently.
Combining the results into a data structure.
Examples:
We use groupby() function to group the data on “Maths” value. It returns the object as result.
Python
df.groupby(by=['Maths'])
Output:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000012581821388>
Applying groupby() function to group the data on “Maths” value. To view result of formed groups use first() function.
Python
a = df.groupby('Maths')a.first()
Output:
First grouping based on “Maths” within each team we are grouping based on “Science”
Python
b = df.groupby(['Maths', 'Science'])b.first()
Output:
Here we are using a dataset of diamond information.
Python
# import moduleimport numpy as npimport pandas as pd # reading csv filedataset = pd.read_csv("diamonds.csv") # printing first 5 rowsprint(dataset.head(5))
Output:
We group by using cut and get the sum of all columns.
Python
dataset.groupby('cut').sum()
Output:
Here we are grouping using cut and color and getting minimum value for all other groups.
Python
dataset.groupby(['cut', 'color']).agg('min')
Output:
Here we are grouping using color and getting aggregate values like sum, mean, min, etc. for the price group.
Python
# dictionary having key as group name of price and# value as list of aggregation function # we want to perform on group priceagg_functions = { 'price': ['sum', 'mean', 'median', 'min', 'max', 'prod']} dataset.groupby(['color']).agg(agg_functions)
Output:
We can see that in the prod(product i.e. multiplication) column all values are inf, inf is the result of a numerical calculation that is mathematically infinite.
Picked
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "In this article, we are going to see grouping and aggregating using pandas. Grouping and aggregating will help to achieve data analysis easily using various functions. These methods will help us to the group and summarize our data and make complex analysis comparatively easy. "
},
{
"code": null,
"e": 363,
"s": 307,
"text": "Creating a sample dataset of marks of various subjects."
},
{
"code": null,
"e": 370,
"s": 363,
"text": "Python"
},
{
"code": "# import moduleimport pandas as pd # Creating our datasetdf = pd.DataFrame([[9, 4, 8, 9], [8, 10, 7, 6], [7, 6, 8, 5]], columns=['Maths', 'English', 'Science', 'History']) # display datasetprint(df)",
"e": 652,
"s": 370,
"text": null
},
{
"code": null,
"e": 660,
"s": 652,
"text": "Output:"
},
{
"code": null,
"e": 1056,
"s": 660,
"text": "Aggregation in pandas provides various functions that perform a mathematical or logical operation on our dataset and returns a summary of that function. Aggregation can be used to get a summary of columns in our dataset like getting sum, minimum, maximum, etc. from a particular column of our dataset. The function used for aggregation is agg(), the parameter is the function we want to perform."
},
{
"code": null,
"e": 1100,
"s": 1056,
"text": "Some functions used in the aggregation are:"
},
{
"code": null,
"e": 1122,
"s": 1100,
"text": "Function Description:"
},
{
"code": null,
"e": 1166,
"s": 1122,
"text": "sum() :Compute sum of column values"
},
{
"code": null,
"e": 1211,
"s": 1166,
"text": "min() :Compute min of column values"
},
{
"code": null,
"e": 1255,
"s": 1211,
"text": "max() :Compute max of column values"
},
{
"code": null,
"e": 1292,
"s": 1255,
"text": "mean() :Compute mean of column"
},
{
"code": null,
"e": 1330,
"s": 1292,
"text": "size() :Compute column sizes"
},
{
"code": null,
"e": 1376,
"s": 1330,
"text": "describe() :Generates descriptive statistics"
},
{
"code": null,
"e": 1424,
"s": 1376,
"text": "first() :Compute first of group values"
},
{
"code": null,
"e": 1470,
"s": 1424,
"text": "last() :Compute last of group values"
},
{
"code": null,
"e": 1516,
"s": 1470,
"text": "count() :Compute count of column values"
},
{
"code": null,
"e": 1562,
"s": 1516,
"text": "std() :Standard deviation of column"
},
{
"code": null,
"e": 1606,
"s": 1562,
"text": "var() :Compute variance of column"
},
{
"code": null,
"e": 1658,
"s": 1606,
"text": "sem() :Standard error of the mean of column"
},
{
"code": null,
"e": 1668,
"s": 1658,
"text": "Examples:"
},
{
"code": null,
"e": 1732,
"s": 1668,
"text": "The sum() function is used to calculate the sum of every value."
},
{
"code": null,
"e": 1739,
"s": 1732,
"text": "Python"
},
{
"code": "df.sum()",
"e": 1748,
"s": 1739,
"text": null
},
{
"code": null,
"e": 1756,
"s": 1748,
"text": "Output:"
},
{
"code": null,
"e": 1820,
"s": 1756,
"text": "The describe() function is used to get a summary of our dataset"
},
{
"code": null,
"e": 1827,
"s": 1820,
"text": "Python"
},
{
"code": "df.describe()",
"e": 1841,
"s": 1827,
"text": null
},
{
"code": null,
"e": 1849,
"s": 1841,
"text": "Output:"
},
{
"code": null,
"e": 1938,
"s": 1849,
"text": "We used agg() function to calculate the sum, min, and max of each column in our dataset."
},
{
"code": null,
"e": 1945,
"s": 1938,
"text": "Python"
},
{
"code": "df.agg(['sum', 'min', 'max'])",
"e": 1975,
"s": 1945,
"text": null
},
{
"code": null,
"e": 1983,
"s": 1975,
"text": "Output:"
},
{
"code": null,
"e": 2096,
"s": 1983,
"text": "Grouping is used to group data using some criteria from our dataset. It is used as split-apply-combine strategy."
},
{
"code": null,
"e": 2151,
"s": 2096,
"text": "Splitting the data into groups based on some criteria."
},
{
"code": null,
"e": 2200,
"s": 2151,
"text": "Applying a function to each group independently."
},
{
"code": null,
"e": 2245,
"s": 2200,
"text": "Combining the results into a data structure."
},
{
"code": null,
"e": 2255,
"s": 2245,
"text": "Examples:"
},
{
"code": null,
"e": 2350,
"s": 2255,
"text": "We use groupby() function to group the data on “Maths” value. It returns the object as result."
},
{
"code": null,
"e": 2357,
"s": 2350,
"text": "Python"
},
{
"code": "df.groupby(by=['Maths'])",
"e": 2382,
"s": 2357,
"text": null
},
{
"code": null,
"e": 2390,
"s": 2382,
"text": "Output:"
},
{
"code": null,
"e": 2466,
"s": 2390,
"text": "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000012581821388>"
},
{
"code": null,
"e": 2584,
"s": 2466,
"text": "Applying groupby() function to group the data on “Maths” value. To view result of formed groups use first() function."
},
{
"code": null,
"e": 2591,
"s": 2584,
"text": "Python"
},
{
"code": "a = df.groupby('Maths')a.first()",
"e": 2624,
"s": 2591,
"text": null
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "Output:"
},
{
"code": null,
"e": 2717,
"s": 2632,
"text": "First grouping based on “Maths” within each team we are grouping based on “Science” "
},
{
"code": null,
"e": 2724,
"s": 2717,
"text": "Python"
},
{
"code": "b = df.groupby(['Maths', 'Science'])b.first()",
"e": 2770,
"s": 2724,
"text": null
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Output:"
},
{
"code": null,
"e": 2830,
"s": 2778,
"text": "Here we are using a dataset of diamond information."
},
{
"code": null,
"e": 2837,
"s": 2830,
"text": "Python"
},
{
"code": "# import moduleimport numpy as npimport pandas as pd # reading csv filedataset = pd.read_csv(\"diamonds.csv\") # printing first 5 rowsprint(dataset.head(5))",
"e": 2994,
"s": 2837,
"text": null
},
{
"code": null,
"e": 3002,
"s": 2994,
"text": "Output:"
},
{
"code": null,
"e": 3056,
"s": 3002,
"text": "We group by using cut and get the sum of all columns."
},
{
"code": null,
"e": 3063,
"s": 3056,
"text": "Python"
},
{
"code": "dataset.groupby('cut').sum()",
"e": 3092,
"s": 3063,
"text": null
},
{
"code": null,
"e": 3100,
"s": 3092,
"text": "Output:"
},
{
"code": null,
"e": 3189,
"s": 3100,
"text": "Here we are grouping using cut and color and getting minimum value for all other groups."
},
{
"code": null,
"e": 3196,
"s": 3189,
"text": "Python"
},
{
"code": "dataset.groupby(['cut', 'color']).agg('min')",
"e": 3241,
"s": 3196,
"text": null
},
{
"code": null,
"e": 3249,
"s": 3241,
"text": "Output:"
},
{
"code": null,
"e": 3358,
"s": 3249,
"text": "Here we are grouping using color and getting aggregate values like sum, mean, min, etc. for the price group."
},
{
"code": null,
"e": 3365,
"s": 3358,
"text": "Python"
},
{
"code": "# dictionary having key as group name of price and# value as list of aggregation function # we want to perform on group priceagg_functions = { 'price': ['sum', 'mean', 'median', 'min', 'max', 'prod']} dataset.groupby(['color']).agg(agg_functions)",
"e": 3619,
"s": 3365,
"text": null
},
{
"code": null,
"e": 3627,
"s": 3619,
"text": "Output:"
},
{
"code": null,
"e": 3789,
"s": 3627,
"text": "We can see that in the prod(product i.e. multiplication) column all values are inf, inf is the result of a numerical calculation that is mathematically infinite."
},
{
"code": null,
"e": 3796,
"s": 3789,
"text": "Picked"
},
{
"code": null,
"e": 3810,
"s": 3796,
"text": "Python-pandas"
},
{
"code": null,
"e": 3817,
"s": 3810,
"text": "Python"
},
{
"code": null,
"e": 3915,
"s": 3817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3947,
"s": 3915,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3974,
"s": 3947,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3995,
"s": 3974,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4018,
"s": 3995,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4049,
"s": 4018,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4105,
"s": 4049,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4147,
"s": 4105,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4189,
"s": 4147,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4228,
"s": 4189,
"text": "Python | Get unique values from a list"
}
] |
Reverse an array using Stack
|
18 Jan, 2021
Given an array arr[] of size N, the task to reverse the array using Stack.
Examples:
Input: arr[] = { 10, 20, 30, 40, 50 }Output: 50 40 30 20 10Explanation:Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 }Therefore, the required output is 50 40 30 20 10.
Input: arr[] = { 1 }Output: 1
Iterative and Recursive Approach: Refer the article reverse an array to solve this problem iteratively or recursively.Time Complexity: O(N)Auxiliary Space: O(1)
Stack-based Approach: Follow the steps below to solve the problem:
Initialize a Stack to store the array elements.
Traverse the array and push all the array elements into the stack.
Finally, print the array.
Below is the implementation of the above approach:
C++
C
Java
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of stackclass Stack {public: // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int* array;}; // Function to Initialize a stack// of given capacity.Stack* createStack(unsigned capacity){ Stack* stack = new Stack(); stack->capacity = capacity; stack->top = -1; stack->array = new int[(stack->capacity * sizeof(int))]; return stack;} // Function to check if// the stack is full or notint isFull(Stack* stack){ return stack->top == stack->capacity - 1;} // Function to check if// the stack is empty or notint isEmpty(Stack* stack){ return stack->top == -1;} // Function to insert an element// into the stack.void push(Stack* stack, int item){ // If stack is full if (isFull(stack)) return; // Insert element into stack stack->array[++stack->top] = item;} // Function to remove an element// from stack.int pop(Stack* stack){ // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--];} // Function to reverse the array elementsvoid reverseArray(int arr[], int n){ // Initialize a stack of capacity n Stack* stack = createStack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = { 100, 200, 300, 400 }; int N = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, N); return 0;}
// C program to implement// the above approach#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure of stackstruct Stack { // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int* array;}; // Function to Initialize a stack// of given capacity.struct Stack* createStack(unsigned capacity){ struct Stack* stack = (struct Stack*)malloc( sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*)malloc( stack->capacity * sizeof(int)); return stack;} // Function to check if// the stack is full or notint isFull(struct Stack* stack){ return stack->top == stack->capacity - 1;} // Function to check if// the stack is empty or notint isEmpty(struct Stack* stack){ return stack->top == -1;} // Function to insert an element// into the stack.void push(struct Stack* stack, int item){ // If stack is full if (isFull(stack)) return; // Insert element into stack stack->array[++stack->top] = item;} // Function to remove an element// from stack.int pop(struct Stack* stack){ // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--];} // Function to reverse the array elementsvoid reverseArray(int arr[], int n){ // Initialize a stack of capacity n struct Stack* stack = createStack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for (int i = 0; i < n; i++) printf("%d ", arr[i]);} // Driver Codeint main(){ int arr[] = { 100, 200, 300, 400 }; int N = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, N); return 0;}
// Java program to implement// the above approachimport java.util.*; // Structure of stackclass Stack { // Stores maximum count of // elements stored in a stack int size; // Stores index of top // element of a stack int top; // Stores address of // array element int[] a; // Function to check if // the stack is empty or not boolean isEmpty() { return (top < 0); } // Function to Initialize // a stack of given capacity. Stack(int n) { top = -1; size = n; a = new int[size]; } // Function to push // an element into Stack boolean push(int x) { // If Stack is full if (top >= size) { System.out.println( "Stack Overflow"); return false; } else { // Insert element // into stack a[++top] = x; return true; } } // Function to remove an element // from stack. int pop() { // If stack is empty if (top < 0) { System.out.println( "Stack Underflow"); return 0; } // Pop element from stack else { int x = a[top--]; return x; } }} // Driver Codeclass Main { // Function to reverse the array elements public static void reverse(int arr[], int n) { // Initialize a stack of capacity n Stack obj = new Stack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack obj.push(arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = obj.pop(); } // Print array elements for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } } // Driver function public static void main(String args[]) { int n = 4; // Create a new array int[] a = new int[] { 100, 200, 300, 400 }; // Call reverse method reverse(a, n); }}
400 300 200 100
Time Complexity: O(N)Auxiliary Space: O(N).
Reverse
Technical Scripter 2020
Arrays
Stack
Technical Scripter
Arrays
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Queue using Stacks
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "Given an array arr[] of size N, the task to reverse the array using Stack."
},
{
"code": null,
"e": 113,
"s": 103,
"text": "Examples:"
},
{
"code": null,
"e": 294,
"s": 113,
"text": "Input: arr[] = { 10, 20, 30, 40, 50 }Output: 50 40 30 20 10Explanation:Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 }Therefore, the required output is 50 40 30 20 10."
},
{
"code": null,
"e": 324,
"s": 294,
"text": "Input: arr[] = { 1 }Output: 1"
},
{
"code": null,
"e": 485,
"s": 324,
"text": "Iterative and Recursive Approach: Refer the article reverse an array to solve this problem iteratively or recursively.Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 552,
"s": 485,
"text": "Stack-based Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 600,
"s": 552,
"text": "Initialize a Stack to store the array elements."
},
{
"code": null,
"e": 667,
"s": 600,
"text": "Traverse the array and push all the array elements into the stack."
},
{
"code": null,
"e": 693,
"s": 667,
"text": "Finally, print the array."
},
{
"code": null,
"e": 744,
"s": 693,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 748,
"s": 744,
"text": "C++"
},
{
"code": null,
"e": 750,
"s": 748,
"text": "C"
},
{
"code": null,
"e": 755,
"s": 750,
"text": "Java"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of stackclass Stack {public: // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int* array;}; // Function to Initialize a stack// of given capacity.Stack* createStack(unsigned capacity){ Stack* stack = new Stack(); stack->capacity = capacity; stack->top = -1; stack->array = new int[(stack->capacity * sizeof(int))]; return stack;} // Function to check if// the stack is full or notint isFull(Stack* stack){ return stack->top == stack->capacity - 1;} // Function to check if// the stack is empty or notint isEmpty(Stack* stack){ return stack->top == -1;} // Function to insert an element// into the stack.void push(Stack* stack, int item){ // If stack is full if (isFull(stack)) return; // Insert element into stack stack->array[++stack->top] = item;} // Function to remove an element// from stack.int pop(Stack* stack){ // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--];} // Function to reverse the array elementsvoid reverseArray(int arr[], int n){ // Initialize a stack of capacity n Stack* stack = createStack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = { 100, 200, 300, 400 }; int N = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, N); return 0;}",
"e": 2685,
"s": 755,
"text": null
},
{
"code": "// C program to implement// the above approach#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure of stackstruct Stack { // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int* array;}; // Function to Initialize a stack// of given capacity.struct Stack* createStack(unsigned capacity){ struct Stack* stack = (struct Stack*)malloc( sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*)malloc( stack->capacity * sizeof(int)); return stack;} // Function to check if// the stack is full or notint isFull(struct Stack* stack){ return stack->top == stack->capacity - 1;} // Function to check if// the stack is empty or notint isEmpty(struct Stack* stack){ return stack->top == -1;} // Function to insert an element// into the stack.void push(struct Stack* stack, int item){ // If stack is full if (isFull(stack)) return; // Insert element into stack stack->array[++stack->top] = item;} // Function to remove an element// from stack.int pop(struct Stack* stack){ // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--];} // Function to reverse the array elementsvoid reverseArray(int arr[], int n){ // Initialize a stack of capacity n struct Stack* stack = createStack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for (int i = 0; i < n; i++) printf(\"%d \", arr[i]);} // Driver Codeint main(){ int arr[] = { 100, 200, 300, 400 }; int N = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, N); return 0;}",
"e": 4746,
"s": 2685,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; // Structure of stackclass Stack { // Stores maximum count of // elements stored in a stack int size; // Stores index of top // element of a stack int top; // Stores address of // array element int[] a; // Function to check if // the stack is empty or not boolean isEmpty() { return (top < 0); } // Function to Initialize // a stack of given capacity. Stack(int n) { top = -1; size = n; a = new int[size]; } // Function to push // an element into Stack boolean push(int x) { // If Stack is full if (top >= size) { System.out.println( \"Stack Overflow\"); return false; } else { // Insert element // into stack a[++top] = x; return true; } } // Function to remove an element // from stack. int pop() { // If stack is empty if (top < 0) { System.out.println( \"Stack Underflow\"); return 0; } // Pop element from stack else { int x = a[top--]; return x; } }} // Driver Codeclass Main { // Function to reverse the array elements public static void reverse(int arr[], int n) { // Initialize a stack of capacity n Stack obj = new Stack(n); for (int i = 0; i < n; i++) { // Insert arr[i] into the stack obj.push(arr[i]); } // Reverse the array elements for (int i = 0; i < n; i++) { // Update arr[i] arr[i] = obj.pop(); } // Print array elements for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } } // Driver function public static void main(String args[]) { int n = 4; // Create a new array int[] a = new int[] { 100, 200, 300, 400 }; // Call reverse method reverse(a, n); }}",
"e": 6855,
"s": 4746,
"text": null
},
{
"code": null,
"e": 6872,
"s": 6855,
"text": "400 300 200 100\n"
},
{
"code": null,
"e": 6916,
"s": 6872,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)."
},
{
"code": null,
"e": 6924,
"s": 6916,
"text": "Reverse"
},
{
"code": null,
"e": 6948,
"s": 6924,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6955,
"s": 6948,
"text": "Arrays"
},
{
"code": null,
"e": 6961,
"s": 6955,
"text": "Stack"
},
{
"code": null,
"e": 6980,
"s": 6961,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6987,
"s": 6980,
"text": "Arrays"
},
{
"code": null,
"e": 6993,
"s": 6987,
"text": "Stack"
},
{
"code": null,
"e": 7001,
"s": 6993,
"text": "Reverse"
},
{
"code": null,
"e": 7099,
"s": 7001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7131,
"s": 7099,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7156,
"s": 7131,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7203,
"s": 7156,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7267,
"s": 7203,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7298,
"s": 7267,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7314,
"s": 7298,
"text": "Stack in Python"
},
{
"code": null,
"e": 7334,
"s": 7314,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 7409,
"s": 7334,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 7441,
"s": 7409,
"text": "Introduction to Data Structures"
}
] |
How to avoid NullPointerException in Java using Optional class?
|
23 May, 2019
In order to learn how to avoid an error, we must first understand the error.
NullPointerException
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.
These can be:
Invoking a method from a null object.
Accessing or modifying a null object’s field.
Taking the length of null, as if it were an array.
Accessing or modifying the slots of null object, as if it were an array.
Throwing null, as if it were a Throwable value.
When you try to synchronize over a null object.
Example:
// Java program to show NullPointerException public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // The String is empty // So a[1] will have null at present String upcase = a[1].toUpperCase(); System.out.print(upcase); }}
Output:
Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:4)
How to avoid NullPointerException with Optional Class?:Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.
Optional ClassOptional is a container object that can contain a non-null or null value. It basically checks whether the memory address has an object or not. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if value, not present and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are:
Final and immutable (though may contain references to mutable objects).
Considered equal solely based on equals(), not based on reference equality(==).
Do not have accessible constructors.
Syntax:
Optional is a generic type of type T.
Optional<T>
Rectifying the code for the above NullPointerException using Optional Class:
// Java program to avoid NullPointerException// using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If the value in the current instance is null, // it will return false, else true if (check.isPresent()) { // The String is empty // So a[1] will have null at present String upcase = a[1].toUpperCase(); System.out.print(upcase); } else // As the current value is null System.out.println("String value is not present"); }}
String value is not present
Note: Hence this can be understood as an exception handling method for NullPointerException
NullPointerException Handling using Optional class:
// Java program to handle NullPointerException// using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Define the a[1] element a[1] = "geeksforgeeks"; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If the value in the current instance is null, // it will return false, else true if (check.isPresent()) { // The String is not empty // So a[1] will have a value at present String upcase = a[1].toUpperCase(); System.out.print(upcase); } else // If the current value is null System.out.println("String value is not present"); }}
GEEKSFORGEEKS
SohomPramanick
java-basics
Java-Exception Handling
Java-Exceptions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "In order to learn how to avoid an error, we must first understand the error."
},
{
"code": null,
"e": 126,
"s": 105,
"text": "NullPointerException"
},
{
"code": null,
"e": 345,
"s": 126,
"text": "NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value."
},
{
"code": null,
"e": 359,
"s": 345,
"text": "These can be:"
},
{
"code": null,
"e": 397,
"s": 359,
"text": "Invoking a method from a null object."
},
{
"code": null,
"e": 443,
"s": 397,
"text": "Accessing or modifying a null object’s field."
},
{
"code": null,
"e": 494,
"s": 443,
"text": "Taking the length of null, as if it were an array."
},
{
"code": null,
"e": 567,
"s": 494,
"text": "Accessing or modifying the slots of null object, as if it were an array."
},
{
"code": null,
"e": 615,
"s": 567,
"text": "Throwing null, as if it were a Throwable value."
},
{
"code": null,
"e": 663,
"s": 615,
"text": "When you try to synchronize over a null object."
},
{
"code": null,
"e": 672,
"s": 663,
"text": "Example:"
},
{
"code": "// Java program to show NullPointerException public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // The String is empty // So a[1] will have null at present String upcase = a[1].toUpperCase(); System.out.print(upcase); }}",
"e": 1023,
"s": 672,
"text": null
},
{
"code": null,
"e": 1031,
"s": 1023,
"text": "Output:"
},
{
"code": null,
"e": 1126,
"s": 1031,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n at Example.main(Example.java:4)\n"
},
{
"code": null,
"e": 1508,
"s": 1126,
"text": "How to avoid NullPointerException with Optional Class?:Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer."
},
{
"code": null,
"e": 2038,
"s": 1508,
"text": "Optional ClassOptional is a container object that can contain a non-null or null value. It basically checks whether the memory address has an object or not. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if value, not present and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are:"
},
{
"code": null,
"e": 2110,
"s": 2038,
"text": "Final and immutable (though may contain references to mutable objects)."
},
{
"code": null,
"e": 2190,
"s": 2110,
"text": "Considered equal solely based on equals(), not based on reference equality(==)."
},
{
"code": null,
"e": 2227,
"s": 2190,
"text": "Do not have accessible constructors."
},
{
"code": null,
"e": 2235,
"s": 2227,
"text": "Syntax:"
},
{
"code": null,
"e": 2287,
"s": 2235,
"text": "Optional is a generic type of type T.\n\nOptional<T>\n"
},
{
"code": null,
"e": 2364,
"s": 2287,
"text": "Rectifying the code for the above NullPointerException using Optional Class:"
},
{
"code": "// Java program to avoid NullPointerException// using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If the value in the current instance is null, // it will return false, else true if (check.isPresent()) { // The String is empty // So a[1] will have null at present String upcase = a[1].toUpperCase(); System.out.print(upcase); } else // As the current value is null System.out.println(\"String value is not present\"); }}",
"e": 3216,
"s": 2364,
"text": null
},
{
"code": null,
"e": 3245,
"s": 3216,
"text": "String value is not present\n"
},
{
"code": null,
"e": 3337,
"s": 3245,
"text": "Note: Hence this can be understood as an exception handling method for NullPointerException"
},
{
"code": null,
"e": 3389,
"s": 3337,
"text": "NullPointerException Handling using Optional class:"
},
{
"code": "// Java program to handle NullPointerException// using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Define the a[1] element a[1] = \"geeksforgeeks\"; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If the value in the current instance is null, // it will return false, else true if (check.isPresent()) { // The String is not empty // So a[1] will have a value at present String upcase = a[1].toUpperCase(); System.out.print(upcase); } else // If the current value is null System.out.println(\"String value is not present\"); }}",
"e": 4316,
"s": 3389,
"text": null
},
{
"code": null,
"e": 4331,
"s": 4316,
"text": "GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 4346,
"s": 4331,
"text": "SohomPramanick"
},
{
"code": null,
"e": 4358,
"s": 4346,
"text": "java-basics"
},
{
"code": null,
"e": 4382,
"s": 4358,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 4398,
"s": 4382,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4405,
"s": 4398,
"text": "Picked"
},
{
"code": null,
"e": 4410,
"s": 4405,
"text": "Java"
},
{
"code": null,
"e": 4415,
"s": 4410,
"text": "Java"
},
{
"code": null,
"e": 4513,
"s": 4415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4528,
"s": 4513,
"text": "Stream In Java"
},
{
"code": null,
"e": 4549,
"s": 4528,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4570,
"s": 4549,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4589,
"s": 4570,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4606,
"s": 4589,
"text": "Generics in Java"
},
{
"code": null,
"e": 4636,
"s": 4606,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4662,
"s": 4636,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4678,
"s": 4662,
"text": "Strings in Java"
},
{
"code": null,
"e": 4715,
"s": 4678,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to Implement TextWatcher in Android?
|
24 Nov, 2020
If there is an application containing a login form to be filled by the user, the login button should be disabled (meaning: it shouldn’t be clickable). When the user enters the credentials of the form the button should be enabled to click for the user. So in this article, we are implementing a TextWatcher to the EditText field. Have a look at the following image to get an idea of what is the TextWatcher and how that may increase user interactivity. Note that we are going to implement this project using the Java language.
Step 1: Create an Empty Activity project
Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?
Note that select Java as the programming language.
Step 2: Working with the activity_main.xml
Implement the Two edit text fields, one for email and one for the password.
Invoke the following code inside the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--this is the email edittext field--> <EditText android:id="@+id/etEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:layout_marginEnd="16dp" android:hint="Email" android:inputType="textEmailAddress" /> <!--this is the email password field--> <EditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/etEmail" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:hint="Password" android:inputType="textPassword" /> <!--login button which set to be false for the enabled attribute--> <Button android:id="@+id/loginButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/etPassword" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:enabled="false" android:text="LOGIN" /> </RelativeLayout>
Output UI:
Step 3: Working with the MainAcitvity.java file
We can also handle both the EditTexts separately. But in this case, to reduce the lines of code, the callback listener TextWatcher is implemented, and the callback listener object is passed to the addTextChangedListener method for each of the edit text.
Invoke the following code inside the MainActivity.java file comments are added for better understanding.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity { // two edit text fields EditText etEmail, etPassword; // one login button Button bLogin; // implement the TextWatcher callback listener private TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // get the content of both the edit text String emailInput = etEmail.getText().toString(); String passwordInput = etPassword.getText().toString(); // check whether both the fields are empty or not bLogin.setEnabled(!emailInput.isEmpty() && !passwordInput.isEmpty()); } @Override public void afterTextChanged(Editable s) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register all the UI elements // with their appropriate IDs etEmail = findViewById(R.id.etEmail); etPassword = findViewById(R.id.etPassword); bLogin = findViewById(R.id.loginButton); // set the TextChange Listener for both // the edit text fields etEmail.addTextChangedListener(textWatcher); etPassword.addTextChangedListener(textWatcher); }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 580,
"s": 53,
"text": "If there is an application containing a login form to be filled by the user, the login button should be disabled (meaning: it shouldn’t be clickable). When the user enters the credentials of the form the button should be enabled to click for the user. So in this article, we are implementing a TextWatcher to the EditText field. Have a look at the following image to get an idea of what is the TextWatcher and how that may increase user interactivity. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 621,
"s": 580,
"text": "Step 1: Create an Empty Activity project"
},
{
"code": null,
"e": 742,
"s": 621,
"text": "Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 793,
"s": 742,
"text": "Note that select Java as the programming language."
},
{
"code": null,
"e": 836,
"s": 793,
"text": "Step 2: Working with the activity_main.xml"
},
{
"code": null,
"e": 912,
"s": 836,
"text": "Implement the Two edit text fields, one for email and one for the password."
},
{
"code": null,
"e": 973,
"s": 912,
"text": "Invoke the following code inside the activity_main.xml file."
},
{
"code": null,
"e": 977,
"s": 973,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--this is the email edittext field--> <EditText android:id=\"@+id/etEmail\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Email\" android:inputType=\"textEmailAddress\" /> <!--this is the email password field--> <EditText android:id=\"@+id/etPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/etEmail\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Password\" android:inputType=\"textPassword\" /> <!--login button which set to be false for the enabled attribute--> <Button android:id=\"@+id/loginButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/etPassword\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"16dp\" android:enabled=\"false\" android:text=\"LOGIN\" /> </RelativeLayout>",
"e": 2457,
"s": 977,
"text": null
},
{
"code": null,
"e": 2468,
"s": 2457,
"text": "Output UI:"
},
{
"code": null,
"e": 2516,
"s": 2468,
"text": "Step 3: Working with the MainAcitvity.java file"
},
{
"code": null,
"e": 2770,
"s": 2516,
"text": "We can also handle both the EditTexts separately. But in this case, to reduce the lines of code, the callback listener TextWatcher is implemented, and the callback listener object is passed to the addTextChangedListener method for each of the edit text."
},
{
"code": null,
"e": 2875,
"s": 2770,
"text": "Invoke the following code inside the MainActivity.java file comments are added for better understanding."
},
{
"code": null,
"e": 2880,
"s": 2875,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity { // two edit text fields EditText etEmail, etPassword; // one login button Button bLogin; // implement the TextWatcher callback listener private TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // get the content of both the edit text String emailInput = etEmail.getText().toString(); String passwordInput = etPassword.getText().toString(); // check whether both the fields are empty or not bLogin.setEnabled(!emailInput.isEmpty() && !passwordInput.isEmpty()); } @Override public void afterTextChanged(Editable s) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register all the UI elements // with their appropriate IDs etEmail = findViewById(R.id.etEmail); etPassword = findViewById(R.id.etPassword); bLogin = findViewById(R.id.loginButton); // set the TextChange Listener for both // the edit text fields etEmail.addTextChangedListener(textWatcher); etPassword.addTextChangedListener(textWatcher); }}",
"e": 4565,
"s": 2880,
"text": null
},
{
"code": null,
"e": 4573,
"s": 4565,
"text": "android"
},
{
"code": null,
"e": 4597,
"s": 4573,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4605,
"s": 4597,
"text": "Android"
},
{
"code": null,
"e": 4610,
"s": 4605,
"text": "Java"
},
{
"code": null,
"e": 4629,
"s": 4610,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4634,
"s": 4629,
"text": "Java"
},
{
"code": null,
"e": 4642,
"s": 4634,
"text": "Android"
},
{
"code": null,
"e": 4740,
"s": 4642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4809,
"s": 4740,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 4840,
"s": 4809,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 4883,
"s": 4840,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 4915,
"s": 4883,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 4954,
"s": 4915,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 4990,
"s": 4954,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5015,
"s": 4990,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5066,
"s": 5015,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5088,
"s": 5066,
"text": "For-each loop in Java"
}
] |
Shell in a Box – Remote Linux Server via Web Browser
|
23 Jun, 2021
For accessing Linux-based machines, Secure Shell (SSH) is used and for accessing Windows-based machines, Remote Desktop Protocol (RDP) is used. Putty is the most famous SSH client in windows. Just like that, SSH can be used for accessing the Linux server remotely via a web browser using shellinabox application.
Shellinabox is a free, open-source, web-based terminal emulator that uses Ajax technology to provide the appearance of a native shell. It was developed by Markus Gutschke. It has the following features:
Shellinabox has a built-in web server that lets you run a web-based SSH client on a specified port.A web terminal emulator will be provided for remotely accessing the Linux Server SSH Shell from any web browser that supports AJAX/JavaScript and CSS without using any extra browser plugins like FireSSH.If SSL/TLS certificates are installed, then all client-server communications are encrypted. When shellinabox is installed, at that time a new self-signed SSL certificate will be installed, the details can be found in /var/lib/shellinabox (to use HTTPS). One can install own SSL certificate.
Shellinabox has a built-in web server that lets you run a web-based SSH client on a specified port.
A web terminal emulator will be provided for remotely accessing the Linux Server SSH Shell from any web browser that supports AJAX/JavaScript and CSS without using any extra browser plugins like FireSSH.
If SSL/TLS certificates are installed, then all client-server communications are encrypted. When shellinabox is installed, at that time a new self-signed SSL certificate will be installed, the details can be found in /var/lib/shellinabox (to use HTTPS). One can install own SSL certificate.
For installing shellinabox on a Debian/Ubuntu-based system, follow the given command:
$ sudo apt-get install shellinabox
After successful installation, let’s see the next steps to follow for using shellinabox:
Step 1- Start the shellinabox daemon using the following command:
$ sudo /etc/init.d/shellinabox start
Step 2- By default, shellinaboxd listens on TCP port 4200, but it is possible to change it. For changing the port number, edit the port number using the following command:
$ sudo vi /etc/default/shellinabox
Step 3- Restart the shellinabox daemon using the following command:
$ sudo /etc/init.d/shellinabox restart
Step 4- Now verify whether Shellinabox is running on the port that was changed or not using the following command:
sudo netstat -nap | grep shellinabox
Step 5- Next step is to open a web browser, and navigate to “https://server_ip_address:port_number”. A web-based SSH terminal can be seen on the screen that will tell to log in using your username and password like this:
Step 6- Right-click in the browser to get different features, and if you are inactive for some time, the sessions get disconnected. Connect again by clicking on connect the button.
Note: DO NOT forget to secure the shellinabox with a firewall and open the assigned port(default one or the manual port you gave) for only specific IP Addresses to access your Linux shell remotely. This will protect from attackers.
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "For accessing Linux-based machines, Secure Shell (SSH) is used and for accessing Windows-based machines, Remote Desktop Protocol (RDP) is used. Putty is the most famous SSH client in windows. Just like that, SSH can be used for accessing the Linux server remotely via a web browser using shellinabox application."
},
{
"code": null,
"e": 544,
"s": 341,
"text": "Shellinabox is a free, open-source, web-based terminal emulator that uses Ajax technology to provide the appearance of a native shell. It was developed by Markus Gutschke. It has the following features:"
},
{
"code": null,
"e": 1137,
"s": 544,
"text": "Shellinabox has a built-in web server that lets you run a web-based SSH client on a specified port.A web terminal emulator will be provided for remotely accessing the Linux Server SSH Shell from any web browser that supports AJAX/JavaScript and CSS without using any extra browser plugins like FireSSH.If SSL/TLS certificates are installed, then all client-server communications are encrypted. When shellinabox is installed, at that time a new self-signed SSL certificate will be installed, the details can be found in /var/lib/shellinabox (to use HTTPS). One can install own SSL certificate."
},
{
"code": null,
"e": 1237,
"s": 1137,
"text": "Shellinabox has a built-in web server that lets you run a web-based SSH client on a specified port."
},
{
"code": null,
"e": 1441,
"s": 1237,
"text": "A web terminal emulator will be provided for remotely accessing the Linux Server SSH Shell from any web browser that supports AJAX/JavaScript and CSS without using any extra browser plugins like FireSSH."
},
{
"code": null,
"e": 1732,
"s": 1441,
"text": "If SSL/TLS certificates are installed, then all client-server communications are encrypted. When shellinabox is installed, at that time a new self-signed SSL certificate will be installed, the details can be found in /var/lib/shellinabox (to use HTTPS). One can install own SSL certificate."
},
{
"code": null,
"e": 1818,
"s": 1732,
"text": "For installing shellinabox on a Debian/Ubuntu-based system, follow the given command:"
},
{
"code": null,
"e": 1853,
"s": 1818,
"text": "$ sudo apt-get install shellinabox"
},
{
"code": null,
"e": 1942,
"s": 1853,
"text": "After successful installation, let’s see the next steps to follow for using shellinabox:"
},
{
"code": null,
"e": 2008,
"s": 1942,
"text": "Step 1- Start the shellinabox daemon using the following command:"
},
{
"code": null,
"e": 2045,
"s": 2008,
"text": "$ sudo /etc/init.d/shellinabox start"
},
{
"code": null,
"e": 2217,
"s": 2045,
"text": "Step 2- By default, shellinaboxd listens on TCP port 4200, but it is possible to change it. For changing the port number, edit the port number using the following command:"
},
{
"code": null,
"e": 2252,
"s": 2217,
"text": "$ sudo vi /etc/default/shellinabox"
},
{
"code": null,
"e": 2320,
"s": 2252,
"text": "Step 3- Restart the shellinabox daemon using the following command:"
},
{
"code": null,
"e": 2359,
"s": 2320,
"text": "$ sudo /etc/init.d/shellinabox restart"
},
{
"code": null,
"e": 2474,
"s": 2359,
"text": "Step 4- Now verify whether Shellinabox is running on the port that was changed or not using the following command:"
},
{
"code": null,
"e": 2511,
"s": 2474,
"text": "sudo netstat -nap | grep shellinabox"
},
{
"code": null,
"e": 2732,
"s": 2511,
"text": "Step 5- Next step is to open a web browser, and navigate to “https://server_ip_address:port_number”. A web-based SSH terminal can be seen on the screen that will tell to log in using your username and password like this:"
},
{
"code": null,
"e": 2913,
"s": 2732,
"text": "Step 6- Right-click in the browser to get different features, and if you are inactive for some time, the sessions get disconnected. Connect again by clicking on connect the button."
},
{
"code": null,
"e": 3145,
"s": 2913,
"text": "Note: DO NOT forget to secure the shellinabox with a firewall and open the assigned port(default one or the manual port you gave) for only specific IP Addresses to access your Linux shell remotely. This will protect from attackers."
},
{
"code": null,
"e": 3152,
"s": 3145,
"text": "Picked"
},
{
"code": null,
"e": 3163,
"s": 3152,
"text": "Linux-Unix"
}
] |
How to set the collapsing borders model for a table ?
|
01 Apr, 2021
CSS describes the way HTML elements should be displayed. There are various CSS properties that can add magic to the basic HTML document.
This article is focused on setting the collapsing borders model for the table element of HTML.
HTML tables allow us to arrange our data using rows and columns. The <table> tag defines an HTML table. Each table row is defined with a <tr> tag. Each table header is defined with a <th> tag. Each table data/cell is defined with a <td> tag. Let us see how we can construct a table that can represent the marks of four students in respective subjects and set the collapsed borders for it as shown below.
Example 1: This example describes the basic example of HTML table.
HTML
<!DOCTYPE html><html> <head> <title>css collapse borders</title></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>
Output:
HTML Table
Example 2: In this example, we will add some borders to it using the CSS border property as shown in the below example.
HTML
<!DOCTYPE html><html> <head> <title>CSS border collapse</title> <style> table, tr, th, td { border: 2px solid black; border-spacing: 5px; } </style></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>
Output:
HTML table with borders
On adding the borders to our table, we get the output as shown above. But this may not be the required output, So let us try to collapse these borders to get a more unified output using the border-collapse property and setting its value to collapse as shown in the next example.
Example 3:
HTML
<!DOCTYPE html><html> <head> <title>CSS border collapse</title> <style> table, tr, th, td { border: 2px solid black; border-collapse: collapse; border-spacing: 5px; } </style></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>
Output:
Table with collapsed borders
This is our required output, So finally we have learned how to set the collapsed borders for a table. The point to remember is that the border-spacing property will have no effect on the border-collapse property when set to collapse value.
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "CSS describes the way HTML elements should be displayed. There are various CSS properties that can add magic to the basic HTML document."
},
{
"code": null,
"e": 261,
"s": 165,
"text": "This article is focused on setting the collapsing borders model for the table element of HTML. "
},
{
"code": null,
"e": 665,
"s": 261,
"text": "HTML tables allow us to arrange our data using rows and columns. The <table> tag defines an HTML table. Each table row is defined with a <tr> tag. Each table header is defined with a <th> tag. Each table data/cell is defined with a <td> tag. Let us see how we can construct a table that can represent the marks of four students in respective subjects and set the collapsed borders for it as shown below."
},
{
"code": null,
"e": 732,
"s": 665,
"text": "Example 1: This example describes the basic example of HTML table."
},
{
"code": null,
"e": 737,
"s": 732,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>css collapse borders</title></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>",
"e": 1598,
"s": 737,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1598,
"text": "Output:"
},
{
"code": null,
"e": 1617,
"s": 1606,
"text": "HTML Table"
},
{
"code": null,
"e": 1737,
"s": 1617,
"text": "Example 2: In this example, we will add some borders to it using the CSS border property as shown in the below example."
},
{
"code": null,
"e": 1742,
"s": 1737,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS border collapse</title> <style> table, tr, th, td { border: 2px solid black; border-spacing: 5px; } </style></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>",
"e": 2750,
"s": 1742,
"text": null
},
{
"code": null,
"e": 2758,
"s": 2750,
"text": "Output:"
},
{
"code": null,
"e": 2782,
"s": 2758,
"text": "HTML table with borders"
},
{
"code": null,
"e": 3061,
"s": 2782,
"text": "On adding the borders to our table, we get the output as shown above. But this may not be the required output, So let us try to collapse these borders to get a more unified output using the border-collapse property and setting its value to collapse as shown in the next example."
},
{
"code": null,
"e": 3072,
"s": 3061,
"text": "Example 3:"
},
{
"code": null,
"e": 3077,
"s": 3072,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS border collapse</title> <style> table, tr, th, td { border: 2px solid black; border-collapse: collapse; border-spacing: 5px; } </style></head> <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> <tr> <td>100</td> <td>Tanmay</td> <td>98</td> <td>96</td> <td>93</td> </tr> <tr> <td>101</td> <td>Sunaina</td> <td>90</td> <td>92</td> <td>91</td> </tr> <tr> <td>102</td> <td>Tanisha</td> <td>89</td> <td>86</td> <td>83</td> </tr> <tr> <td>103</td> <td>David</td> <td>97</td> <td>95</td> <td>94</td> </tr> </table></body> </html>",
"e": 4123,
"s": 3077,
"text": null
},
{
"code": null,
"e": 4131,
"s": 4123,
"text": "Output:"
},
{
"code": null,
"e": 4160,
"s": 4131,
"text": "Table with collapsed borders"
},
{
"code": null,
"e": 4401,
"s": 4160,
"text": "This is our required output, So finally we have learned how to set the collapsed borders for a table. The point to remember is that the border-spacing property will have no effect on the border-collapse property when set to collapse value. "
},
{
"code": null,
"e": 4416,
"s": 4401,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4430,
"s": 4416,
"text": "CSS-Questions"
},
{
"code": null,
"e": 4445,
"s": 4430,
"text": "HTML-Questions"
},
{
"code": null,
"e": 4455,
"s": 4445,
"text": "HTML-Tags"
},
{
"code": null,
"e": 4462,
"s": 4455,
"text": "Picked"
},
{
"code": null,
"e": 4466,
"s": 4462,
"text": "CSS"
},
{
"code": null,
"e": 4471,
"s": 4466,
"text": "HTML"
},
{
"code": null,
"e": 4488,
"s": 4471,
"text": "Web Technologies"
},
{
"code": null,
"e": 4493,
"s": 4488,
"text": "HTML"
},
{
"code": null,
"e": 4591,
"s": 4493,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4630,
"s": 4591,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4669,
"s": 4630,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4708,
"s": 4669,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4745,
"s": 4708,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 4774,
"s": 4745,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4798,
"s": 4774,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4851,
"s": 4798,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4911,
"s": 4851,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4972,
"s": 4911,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python | Split multiple characters from string
|
11 Nov, 2019
While coding or improvising your programming skill, you surely must have come across many scenarios where you wished to use .split() in Python not to split on only one character but multiple characters at once. Consider this for an example:
"GeeksforGeeks, is an-awesome! website"
Using .split() on the above will result in
['GeeksforGeeks, ', 'is', 'an-awesome!', 'website']
whereas the desired result should be
['GeeksforGeeks', 'is', 'an', 'awesome', 'website']
In this article, we will look at some ways in which we can achieve the same.
This is the most efficient and commonly used method to split on multiple characters at once. It makes use of regex(regular expressions) in order to this.
# Python3 code to demonstrate working of # Splitting operators in String # Using re.split() import re # initializing stringdata = "GeeksforGeeks, is_an-awesome ! website" # printing original string print("The original string is : " + data) # Using re.split() # Splitting characters in String res = re.split(', |_|-|!', data) # printing result print("The list after performing split functionality : " + str(res))
Output:
The original string is : GeeksforGeeks, is_an-awesome ! websiteThe list after performing split functionality : [‘GeeksforGeeks’, ‘is’, ‘an’, ‘awesome ‘, ‘ website’]
The line re.split(', |_|-|!', data) tells Python to split the variable data on the characters: , or _ or – or !. The symbol “|” represents or.
There are some symbols in regex which are treated as special symbols and have different functions. If you wish to split on such a symbol, you need to escape it using a “\“(back-slash). List of special characters that needs to be escaped before using them:
. \ + * ? [ ^ ] $ ( ) { } = ! | : -
For example:
import renewData = "GeeksforGeeks, is_an-awesome ! app + too" # To split "+" use backslashprint(re.split(', |_|-|!|\+', newData))
Output:
['GeeksforGeeks', ' is', 'an', 'awesome', ' app', 'too']
Note: To know more about regex click here.
This is a bit more arcane form but saves time. It also makes use of regex like above but instead of .split() method, it uses a method called .findall(). This method finds all the matching instances and returns each of them in a list. This way of splitting is best used when you don’t know the exact characters you want to split upon.
# Python3 code to demonstrate working of # Splitting operators in String # Using re.findall() import re # initializing string data = "This, is - another : example?!" # printing original string print("The original string is : " + data) # Using re.findall() # Splitting characters in String res = re.findall(r"[\w']+", data) # printing result print("The list after performing split functionality : " + str(res))
Output:
The original string is : This, is – another : example?!The list after performing split functionality : [‘This’, ‘is’, ‘another’, ‘example’]
Here the keyword [\w']+ indicates that it will find all the instances of alphabets or underscore(_) one or more and return them in a list.Note: [\w']+ won’t split upon an underscore(_) as it searches for alphabets as well as underscores.For example:
import retestData = "This, is - underscored _ example?!"print(re.findall(r"[\w']+", testData))
Output:
['This', 'is', 'underscored', '_', 'example']
This is a very rookie way of doing the split. It does not make use of regex and is inefficient but still worth a try. If you know the characters you want to split upon, just replace them with a space and then use .split():
# Python code to demonstrate # to split strings # Initial stringdata = "Let's_try, this now" # printing original string print("The original string is : " + data) # Using replace() and split() # Splitting characters in String res = data.replace('_', ' ').replace(', ', ' ').split() # Printing resultprint("The list after performing split functionality : " + str(res))
Output:
The original string is : Let’s_try, this nowThe list after performing split functionality : [“Let’s”, ‘try’, ‘this’, ‘now’]
Regex cheat-sheet on character description
Python string-programs
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "While coding or improvising your programming skill, you surely must have come across many scenarios where you wished to use .split() in Python not to split on only one character but multiple characters at once. Consider this for an example:"
},
{
"code": null,
"e": 309,
"s": 269,
"text": "\"GeeksforGeeks, is an-awesome! website\""
},
{
"code": null,
"e": 352,
"s": 309,
"text": "Using .split() on the above will result in"
},
{
"code": null,
"e": 404,
"s": 352,
"text": "['GeeksforGeeks, ', 'is', 'an-awesome!', 'website']"
},
{
"code": null,
"e": 441,
"s": 404,
"text": "whereas the desired result should be"
},
{
"code": null,
"e": 493,
"s": 441,
"text": "['GeeksforGeeks', 'is', 'an', 'awesome', 'website']"
},
{
"code": null,
"e": 570,
"s": 493,
"text": "In this article, we will look at some ways in which we can achieve the same."
},
{
"code": null,
"e": 724,
"s": 570,
"text": "This is the most efficient and commonly used method to split on multiple characters at once. It makes use of regex(regular expressions) in order to this."
},
{
"code": "# Python3 code to demonstrate working of # Splitting operators in String # Using re.split() import re # initializing stringdata = \"GeeksforGeeks, is_an-awesome ! website\" # printing original string print(\"The original string is : \" + data) # Using re.split() # Splitting characters in String res = re.split(', |_|-|!', data) # printing result print(\"The list after performing split functionality : \" + str(res)) ",
"e": 1146,
"s": 724,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1146,
"text": "Output:"
},
{
"code": null,
"e": 1319,
"s": 1154,
"text": "The original string is : GeeksforGeeks, is_an-awesome ! websiteThe list after performing split functionality : [‘GeeksforGeeks’, ‘is’, ‘an’, ‘awesome ‘, ‘ website’]"
},
{
"code": null,
"e": 1462,
"s": 1319,
"text": "The line re.split(', |_|-|!', data) tells Python to split the variable data on the characters: , or _ or – or !. The symbol “|” represents or."
},
{
"code": null,
"e": 1718,
"s": 1462,
"text": "There are some symbols in regex which are treated as special symbols and have different functions. If you wish to split on such a symbol, you need to escape it using a “\\“(back-slash). List of special characters that needs to be escaped before using them:"
},
{
"code": null,
"e": 1755,
"s": 1718,
"text": ". \\ + * ? [ ^ ] $ ( ) { } = ! | : -"
},
{
"code": null,
"e": 1768,
"s": 1755,
"text": "For example:"
},
{
"code": "import renewData = \"GeeksforGeeks, is_an-awesome ! app + too\" # To split \"+\" use backslashprint(re.split(', |_|-|!|\\+', newData))",
"e": 1899,
"s": 1768,
"text": null
},
{
"code": null,
"e": 1907,
"s": 1899,
"text": "Output:"
},
{
"code": null,
"e": 1964,
"s": 1907,
"text": "['GeeksforGeeks', ' is', 'an', 'awesome', ' app', 'too']"
},
{
"code": null,
"e": 2007,
"s": 1964,
"text": "Note: To know more about regex click here."
},
{
"code": null,
"e": 2341,
"s": 2007,
"text": "This is a bit more arcane form but saves time. It also makes use of regex like above but instead of .split() method, it uses a method called .findall(). This method finds all the matching instances and returns each of them in a list. This way of splitting is best used when you don’t know the exact characters you want to split upon."
},
{
"code": "# Python3 code to demonstrate working of # Splitting operators in String # Using re.findall() import re # initializing string data = \"This, is - another : example?!\" # printing original string print(\"The original string is : \" + data) # Using re.findall() # Splitting characters in String res = re.findall(r\"[\\w']+\", data) # printing result print(\"The list after performing split functionality : \" + str(res)) ",
"e": 2762,
"s": 2341,
"text": null
},
{
"code": null,
"e": 2770,
"s": 2762,
"text": "Output:"
},
{
"code": null,
"e": 2910,
"s": 2770,
"text": "The original string is : This, is – another : example?!The list after performing split functionality : [‘This’, ‘is’, ‘another’, ‘example’]"
},
{
"code": null,
"e": 3160,
"s": 2910,
"text": "Here the keyword [\\w']+ indicates that it will find all the instances of alphabets or underscore(_) one or more and return them in a list.Note: [\\w']+ won’t split upon an underscore(_) as it searches for alphabets as well as underscores.For example:"
},
{
"code": "import retestData = \"This, is - underscored _ example?!\"print(re.findall(r\"[\\w']+\", testData))",
"e": 3255,
"s": 3160,
"text": null
},
{
"code": null,
"e": 3263,
"s": 3255,
"text": "Output:"
},
{
"code": null,
"e": 3309,
"s": 3263,
"text": "['This', 'is', 'underscored', '_', 'example']"
},
{
"code": null,
"e": 3532,
"s": 3309,
"text": "This is a very rookie way of doing the split. It does not make use of regex and is inefficient but still worth a try. If you know the characters you want to split upon, just replace them with a space and then use .split():"
},
{
"code": "# Python code to demonstrate # to split strings # Initial stringdata = \"Let's_try, this now\" # printing original string print(\"The original string is : \" + data) # Using replace() and split() # Splitting characters in String res = data.replace('_', ' ').replace(', ', ' ').split() # Printing resultprint(\"The list after performing split functionality : \" + str(res)) ",
"e": 3909,
"s": 3532,
"text": null
},
{
"code": null,
"e": 3917,
"s": 3909,
"text": "Output:"
},
{
"code": null,
"e": 4041,
"s": 3917,
"text": "The original string is : Let’s_try, this nowThe list after performing split functionality : [“Let’s”, ‘try’, ‘this’, ‘now’]"
},
{
"code": null,
"e": 4084,
"s": 4041,
"text": "Regex cheat-sheet on character description"
},
{
"code": null,
"e": 4107,
"s": 4084,
"text": "Python string-programs"
},
{
"code": null,
"e": 4121,
"s": 4107,
"text": "python-string"
},
{
"code": null,
"e": 4128,
"s": 4121,
"text": "Python"
}
] |
How to select rows of an R data frame that are non-NA?
|
To select rows of an R data frame that are non-Na, we can use complete.cases function with single square brackets. For example, if we have a data frame called that contains some missing values (NA) then the selection of rows that are non-NA can be done by using the command df[complete.cases(df),].
Consider the below data frame −
Live Demo
> x1<-sample(c(1,NA),20,replace=TRUE)
> x2<-sample(c(5,NA),20,replace=TRUE)
> x3<-sample(c(3,NA),20,replace=TRUE)
> df1<-data.frame(x1,x2,x3)
> df1
x1 x2 x3
1 1 NA NA
2 NA 5 3
3 1 5 NA
4 1 NA NA
5 NA 5 NA
6 NA 5 3
7 NA 5 NA
8 1 NA 3
9 NA 5 NA
10 NA 5 NA
11 NA NA NA
12 1 5 3
13 NA 5 3
14 NA NA NA
15 1 NA NA
16 NA 5 3
17 NA NA 3
18 NA NA NA
19 1 NA 3
20 NA NA 3
x1 x2 x3
1 1 NA NA
2 NA 5 3
3 1 5 NA
4 1 NA NA
5 NA 5 NA
6 NA 5 3
7 NA 5 NA
8 1 NA 3
9 NA 5 NA
10 NA 5 NA
11 NA NA NA
12 1 5 3
13 NA 5 3
14 NA NA NA
15 1 NA NA
16 NA 5 3
17 NA NA 3
18 NA NA NA
19 1 NA 3
20 NA NA 3
Selecting rows of df1 that do not contain any NA −
> df1[complete.cases(df1),]
x1 x2 x3
12 1 5 3
x1 x2 x3
12 1 5 3
Live Demo
> y1<-sample(c(rnorm(2),NA),20,replace=TRUE)
> y2<-sample(c(rnorm(2),NA),20,replace=TRUE)
> df2<-data.frame(y1,y2)
> df2
y1 y2
1 0.15079115 -0.626630
2 0.15079115 NA
3 NA -0.626630
4 0.15079115 -0.626630
5 0.15079115 NA
6 0.15079115 -0.626630
7 0.15079115 NA
8 0.15079115 -1.691553
9 NA -1.691553
10 NA -0.626630
11 0.15079115 -1.691553
12 0.15079115 NA
13 NA -1.691553
14 NA -1.691553
15 0.15079115 -1.691553
16 NA -0.626630
17 0.01495388 -0.626630
18 0.01495388 -1.691553
19 0.15079115 -1.691553
20 NA NA
Selecting rows of df2 that do not contain any NA −
> df2[complete.cases(df2),]
y1 y2
1 0.15079115 -0.626630
4 0.15079115 -0.626630
6 0.15079115 -0.626630
8 0.15079115 -1.691553
11 0.15079115 -1.691553
15 0.15079115 -1.691553
17 0.01495388 -0.626630
18 0.01495388 -1.691553
19 0.15079115 -1.691553
Live Demo
> z1<-sample(c("A",NA),20,replace=TRUE)
> z2<-sample(c("B",NA),20,replace=TRUE)
> z3<-sample(c("C",NA),20,replace=TRUE)
> df3<-data.frame(z1,z2,z3)
> df3
z1 z2 z3
1 A <NA> C
2 <NA> B C
3 <NA> <NA> <NA>
4 A B <NA>
5 <NA> <NA> C
6 A <NA> C
7 A B C
8 <NA> B C
9 <NA> <NA> C
10 <NA> <NA> C
11 A <NA> C
12 <NA> <NA> C
13 A B C
14 A B C
15 <NA> <NA> <NA>
16 A B C
17 <NA> <NA> <NA>
18 <NA> <NA> C
19 A B C
20 <NA> <NA> <NA>
Selecting rows of df3 that do not contain any NA −
> df3[complete.cases(df3),]
z1 z2 z3
7 A B C
13 A B C
14 A B C
16 A B C
19 A B C
|
[
{
"code": null,
"e": 1361,
"s": 1062,
"text": "To select rows of an R data frame that are non-Na, we can use complete.cases function with single square brackets. For example, if we have a data frame called that contains some missing values (NA) then the selection of rows that are non-NA can be done by using the command df[complete.cases(df),]."
},
{
"code": null,
"e": 1393,
"s": 1361,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1403,
"s": 1393,
"text": "Live Demo"
},
{
"code": null,
"e": 1551,
"s": 1403,
"text": "> x1<-sample(c(1,NA),20,replace=TRUE)\n> x2<-sample(c(5,NA),20,replace=TRUE)\n> x3<-sample(c(3,NA),20,replace=TRUE)\n> df1<-data.frame(x1,x2,x3)\n> df1"
},
{
"code": null,
"e": 1803,
"s": 1551,
"text": " x1 x2 x3\n1 1 NA NA\n2 NA 5 3\n3 1 5 NA\n4 1 NA NA\n5 NA 5 NA\n6 NA 5 3\n7 NA 5 NA\n8 1 NA 3\n9 NA 5 NA\n10 NA 5 NA\n11 NA NA NA\n12 1 5 3\n13 NA 5 3\n14 NA NA NA\n15 1 NA NA\n16 NA 5 3\n17 NA NA 3\n18 NA NA NA\n19 1 NA 3\n20 NA NA 3"
},
{
"code": null,
"e": 2055,
"s": 1803,
"text": " x1 x2 x3\n1 1 NA NA\n2 NA 5 3\n3 1 5 NA\n4 1 NA NA\n5 NA 5 NA\n6 NA 5 3\n7 NA 5 NA\n8 1 NA 3\n9 NA 5 NA\n10 NA 5 NA\n11 NA NA NA\n12 1 5 3\n13 NA 5 3\n14 NA NA NA\n15 1 NA NA\n16 NA 5 3\n17 NA NA 3\n18 NA NA NA\n19 1 NA 3\n20 NA NA 3"
},
{
"code": null,
"e": 2106,
"s": 2055,
"text": "Selecting rows of df1 that do not contain any NA −"
},
{
"code": null,
"e": 2134,
"s": 2106,
"text": "> df1[complete.cases(df1),]"
},
{
"code": null,
"e": 2158,
"s": 2134,
"text": " x1 x2 x3\n12 1 5 3"
},
{
"code": null,
"e": 2182,
"s": 2158,
"text": " x1 x2 x3\n12 1 5 3"
},
{
"code": null,
"e": 2192,
"s": 2182,
"text": "Live Demo"
},
{
"code": null,
"e": 2313,
"s": 2192,
"text": "> y1<-sample(c(rnorm(2),NA),20,replace=TRUE)\n> y2<-sample(c(rnorm(2),NA),20,replace=TRUE)\n> df2<-data.frame(y1,y2)\n> df2"
},
{
"code": null,
"e": 2817,
"s": 2313,
"text": " y1 y2\n1 0.15079115 -0.626630\n2 0.15079115 NA\n3 NA -0.626630\n4 0.15079115 -0.626630\n5 0.15079115 NA\n6 0.15079115 -0.626630\n7 0.15079115 NA\n8 0.15079115 -1.691553\n9 NA -1.691553\n10 NA -0.626630\n11 0.15079115 -1.691553\n12 0.15079115 NA\n13 NA -1.691553\n14 NA -1.691553\n15 0.15079115 -1.691553\n16 NA -0.626630\n17 0.01495388 -0.626630\n18 0.01495388 -1.691553\n19 0.15079115 -1.691553\n20 NA NA"
},
{
"code": null,
"e": 2868,
"s": 2817,
"text": "Selecting rows of df2 that do not contain any NA −"
},
{
"code": null,
"e": 2896,
"s": 2868,
"text": "> df2[complete.cases(df2),]"
},
{
"code": null,
"e": 3136,
"s": 2896,
"text": " y1 y2\n1 0.15079115 -0.626630\n4 0.15079115 -0.626630\n6 0.15079115 -0.626630\n8 0.15079115 -1.691553\n11 0.15079115 -1.691553\n15 0.15079115 -1.691553\n17 0.01495388 -0.626630\n18 0.01495388 -1.691553\n19 0.15079115 -1.691553"
},
{
"code": null,
"e": 3146,
"s": 3136,
"text": "Live Demo"
},
{
"code": null,
"e": 3300,
"s": 3146,
"text": "> z1<-sample(c(\"A\",NA),20,replace=TRUE)\n> z2<-sample(c(\"B\",NA),20,replace=TRUE)\n> z3<-sample(c(\"C\",NA),20,replace=TRUE)\n> df3<-data.frame(z1,z2,z3)\n> df3"
},
{
"code": null,
"e": 3678,
"s": 3300,
"text": " z1 z2 z3\n1 A <NA> C\n2 <NA> B C\n3 <NA> <NA> <NA>\n4 A B <NA>\n5 <NA> <NA> C\n6 A <NA> C\n7 A B C\n8 <NA> B C\n9 <NA> <NA> C\n10 <NA> <NA> C\n11 A <NA> C\n12 <NA> <NA> C\n13 A B C\n14 A B C\n15 <NA> <NA> <NA>\n16 A B C\n17 <NA> <NA> <NA>\n18 <NA> <NA> C\n19 A B C\n20 <NA> <NA> <NA>"
},
{
"code": null,
"e": 3729,
"s": 3678,
"text": "Selecting rows of df3 that do not contain any NA −"
},
{
"code": null,
"e": 3757,
"s": 3729,
"text": "> df3[complete.cases(df3),]"
},
{
"code": null,
"e": 3829,
"s": 3757,
"text": " z1 z2 z3\n7 A B C\n13 A B C\n14 A B C\n16 A B C\n19 A B C"
}
] |
Wildcard matching of string JavaScript
|
We are required to write a JavaScript function that accepts two strings and a number n. The
function matches the two strings i.e., it checks if the two strings contains the same characters.
The function should return true if both the strings contain the same character irrespective of
their order or if they contain at most n different characters, otherwise the function should return
false.
Let's write the code for this function −
const str1 = 'first string';
const str2 = 'second string';
const wildcardMatching = (first, second, num) => {
let count = 0;
for(let i = 0; i < first.length; i++){
if(!second.includes(first[i])){
count++;
};
if(count > num){
return false;
};
};
return true;
};
console.log(wildcardMatching(str1, str2, 2));
console.log(wildcardMatching(str1, str2, 1));
console.log(wildcardMatching(str1, str2, 0));
The output in the console will be −
true
true
false
|
[
{
"code": null,
"e": 1454,
"s": 1062,
"text": "We are required to write a JavaScript function that accepts two strings and a number n. The\nfunction matches the two strings i.e., it checks if the two strings contains the same characters.\nThe function should return true if both the strings contain the same character irrespective of\ntheir order or if they contain at most n different characters, otherwise the function should return\nfalse."
},
{
"code": null,
"e": 1495,
"s": 1454,
"text": "Let's write the code for this function −"
},
{
"code": null,
"e": 1948,
"s": 1495,
"text": "const str1 = 'first string';\nconst str2 = 'second string';\nconst wildcardMatching = (first, second, num) => {\n let count = 0;\n for(let i = 0; i < first.length; i++){\n if(!second.includes(first[i])){\n count++;\n };\n if(count > num){\n return false;\n };\n };\n return true;\n};\nconsole.log(wildcardMatching(str1, str2, 2));\nconsole.log(wildcardMatching(str1, str2, 1));\nconsole.log(wildcardMatching(str1, str2, 0));"
},
{
"code": null,
"e": 1984,
"s": 1948,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2000,
"s": 1984,
"text": "true\ntrue\nfalse"
}
] |
Assigning Panel Data to Training, Testing and Validation Groups for Machine Learning Models | by Shad Griffin | Towards Data Science
|
Make sure your groups are independent and avoid deployment disasters
github.com
Cross-Sectional data includes individual entities measured in one time period. For example, 10,000 people measured once is cross-sectional data.
Time series includes one entity measured over multiple time periods. For example, a single machine measured every day for ten years is a time-series.
Panel data includes multiple entities measured over multiple time periods. For example, 1,000 consumers measured monthly over ten months is panel data. Or, 100 machines measured daily for 100 days, is panel data.
Panel data is quite common in data science. Sometimes, it is called cross-sectional time-series data. I have also heard it referred to as pooled time series data. Whatever you want to call it, as a practicing data scientist, you’ll more than likely have to deal with it.
It is standard procedure when building machine learning models to assign records in your data to modeling groups. Typically, we randomly sub-set the data into Training, Testing and Validation groups. Random, in this case, means that each record in the data set has an equal chance of being assigned to one of the three groups.
When you are working with Panel Data, however, it makes sense to alter the normal process a little.
In this notebook, I walk through a simple example of how to do this.
Import all of the relevant Python Libraries
import numpy as npimport numpy.dual as dualimport pandas as pd
Import the data from GitHub
#Remove the data if you run this notebook more than once!rm equipment_failure_data_1.csv#import first half from github!wget https://raw.githubusercontent.com/shadgriffin/machine_failure/master/equipment_failure_data_1.csv# Convert csv to pandas dataframepd_data_1 = pd.read_csv("equipment_failure_data_1.csv", sep=",", header=0)#Remove the data if you run this notebook more than once!rm equipment_failure_data_2.csv#Import the second half from github!wget https://raw.githubusercontent.com/shadgriffin/machine_failure/master/equipment_failure_data_2.csv# convert to pandas dataframepd_data_2 = pd.read_csv("equipment_failure_data_2.csv", sep=",", header=0)#concatenate the two data files into one dataframepd_data=pd.concat([pd_data_1, pd_data_2])
pd_data.head()
Here is a description of the fields in the data set.
ID — ID field that represents a specific machine.
DATE — The date of the observation.
REGION_CLUSTER — a field that represents the region in which the machine is located.
MAINTENANCE_VENDOR — a field that represents the company that provides maintenance and service to the machine.
MANUFACTURER — the company that manufactured the equipment in question.
WELL_GROUP — a field representing the type of Machine.
EQUIPMENT_AGE — Age of the machine, in days.
S15 — A Sensor Value.
S17 — A Sensor Value.
S13 — A Sensor Value.
S16 — A Sensor Value.
S19 — A Sensor Value.
S18 — A Sensor Value.
S8 — A Sensor Value.
EQUIPMENT_FAILURE — A ‘1’ means that the equipment failed. A ‘0’ means the equipment did not fail.
This data represents a panel data set. We have multiple machines measured over mulitple time periods. ID represents the machine and DATE represents the date. Now, let’s examine how many machines and how many dates we have.
Examine the number of rows and columns. The data has 307,751 rows and 16 columns
pd_data.shape
There are 421 machines in the data set.
xxxx = pd.DataFrame(pd_data.groupby(['ID']).agg(['count']))xxxx.shape
There are 731 unique dates in the data set.
xxxx = pd.DataFrame(pd_data.groupby(['DATE']).agg(['count']))xxxx.shape
We could just randomly assign each record to either the training, testing or validation group. While that could work, I wouldn’t recommend it. I would recommend assigning records to groups at an entity level (machine in this case).
Why?
Well, I could use some multi-syllabic words (like auto-correlation, boomerang or mayonnaise) to describe why, but let’s just think about it.
Why do we separate the data into training, testing and validation groups?
We want to ensure that our model is not over-fit. In other words, we want to make sure that our model applies to new data as it comes available.
For example, let’s pretend that we built a model that predicts what happened last year with 100% accuracy. Good job, right? Well, it really doesn’t matter how well the model predicts last year. We need it to predict today, tomorrow and the day after that. So, if a model predicts last year with 100% accuracy but fails to predict tomorrow, it kind of sucks.
Building a model on the training data and verifying the accuracy on the testing and validation data set reduces the chances of over-fitting (Note, it is still possible but I will save that discussion for another day).
In order to prevent over-fitting, our training, testing and validation groups must be independent. That is, the data in the training group must be different than the testing and validation groups. Or, at least as different as possible.
So what happens if we just randomly assign each record in a panel data set to each of the groups?
We end up with records from each entity in each group.
For example with a simple random selection method, if we are dealing with 100 machines measured daily over 100 days, it is probable that the machine physically sitting beside the break room will appear in the training, testing and validation groups. Likewise, if you are dealing with individuals (one of whom is named Steve Wakahookie), it is probable that Steve Wakahookie will appear in all three groups.
In other words, your training, testing and validation groups ARE NOT independent because good ol’ Steve and the machine beside the break room are present in all three groups.
Steve is in the testing. Steve is in the training. Steve is in the validation. If he is lurking in all three groups, the three groups are not independent.
Now, if we assign group membership based on entity, all of the Steve’s records will be in either the training, testing or validation group. Likewise, all of the records associated with the machine by the break room will be in only one of the three groups.
If Steve is in the training, but not the testing or validation, the groups ARE independent.
If the machine by the break room is in the testing, but not in the training or validation, the groups ARE independent.
Here is a few lines of python code to that ensure that your training, testing and validation groups are independent.
Get a Unique List of All IDs (machines).
aa=pd_datapd_id=aa.drop_duplicates(subset='ID')pd_id=pd_id[['ID']]pd_id.shape
Create a new variable with a random number between 0 and .
np.random.seed(42)pd_id['wookie'] = (np.random.randint(0, 10000, pd_id.shape[0]))/10000pd_id=pd_id[['ID', 'wookie']]
Give each machine a 30% chance of being in the validation, a 35% chance of being in the testing and a 35% chance of being in the training data set.
pd_id['MODELING_GROUP'] = np.where(((pd_id.wookie <= 0.35)), 'TRAINING', np.where(((pd_id.wookie <= 0.65)), 'VALIDATION', 'TESTING'))
This is how many machines fall in each group.
tips_summed = pd_id.groupby([‘MODELING_GROUP’])[‘wookie’].count()tips_summed
Append the Group of each id to each individual record.
pd_data=pd_data.sort_values(by=['ID'], ascending=[True])pd_id=pd_id.sort_values(by=['ID'], ascending=[True])pd_data =pd_data.merge(pd_id, on=['ID'], how='inner')pd_data.head()
This is how many records are in each group.
tips_summed = pd_data.groupby(['MODELING_GROUP'])['wookie'].count()tips_summed
So, there you go. Now, we are ready to build a machine learning model. By placing entities and not records into your training, testing and validation groups you can ensure independence between the groups and build models that work yesterday, today and tomorrow.
Shad Griffin is a Data Scientist at IBM
|
[
{
"code": null,
"e": 240,
"s": 171,
"text": "Make sure your groups are independent and avoid deployment disasters"
},
{
"code": null,
"e": 251,
"s": 240,
"text": "github.com"
},
{
"code": null,
"e": 396,
"s": 251,
"text": "Cross-Sectional data includes individual entities measured in one time period. For example, 10,000 people measured once is cross-sectional data."
},
{
"code": null,
"e": 546,
"s": 396,
"text": "Time series includes one entity measured over multiple time periods. For example, a single machine measured every day for ten years is a time-series."
},
{
"code": null,
"e": 759,
"s": 546,
"text": "Panel data includes multiple entities measured over multiple time periods. For example, 1,000 consumers measured monthly over ten months is panel data. Or, 100 machines measured daily for 100 days, is panel data."
},
{
"code": null,
"e": 1030,
"s": 759,
"text": "Panel data is quite common in data science. Sometimes, it is called cross-sectional time-series data. I have also heard it referred to as pooled time series data. Whatever you want to call it, as a practicing data scientist, you’ll more than likely have to deal with it."
},
{
"code": null,
"e": 1357,
"s": 1030,
"text": "It is standard procedure when building machine learning models to assign records in your data to modeling groups. Typically, we randomly sub-set the data into Training, Testing and Validation groups. Random, in this case, means that each record in the data set has an equal chance of being assigned to one of the three groups."
},
{
"code": null,
"e": 1457,
"s": 1357,
"text": "When you are working with Panel Data, however, it makes sense to alter the normal process a little."
},
{
"code": null,
"e": 1526,
"s": 1457,
"text": "In this notebook, I walk through a simple example of how to do this."
},
{
"code": null,
"e": 1570,
"s": 1526,
"text": "Import all of the relevant Python Libraries"
},
{
"code": null,
"e": 1633,
"s": 1570,
"text": "import numpy as npimport numpy.dual as dualimport pandas as pd"
},
{
"code": null,
"e": 1661,
"s": 1633,
"text": "Import the data from GitHub"
},
{
"code": null,
"e": 2410,
"s": 1661,
"text": "#Remove the data if you run this notebook more than once!rm equipment_failure_data_1.csv#import first half from github!wget https://raw.githubusercontent.com/shadgriffin/machine_failure/master/equipment_failure_data_1.csv# Convert csv to pandas dataframepd_data_1 = pd.read_csv(\"equipment_failure_data_1.csv\", sep=\",\", header=0)#Remove the data if you run this notebook more than once!rm equipment_failure_data_2.csv#Import the second half from github!wget https://raw.githubusercontent.com/shadgriffin/machine_failure/master/equipment_failure_data_2.csv# convert to pandas dataframepd_data_2 = pd.read_csv(\"equipment_failure_data_2.csv\", sep=\",\", header=0)#concatenate the two data files into one dataframepd_data=pd.concat([pd_data_1, pd_data_2])"
},
{
"code": null,
"e": 2425,
"s": 2410,
"text": "pd_data.head()"
},
{
"code": null,
"e": 2478,
"s": 2425,
"text": "Here is a description of the fields in the data set."
},
{
"code": null,
"e": 2528,
"s": 2478,
"text": "ID — ID field that represents a specific machine."
},
{
"code": null,
"e": 2564,
"s": 2528,
"text": "DATE — The date of the observation."
},
{
"code": null,
"e": 2649,
"s": 2564,
"text": "REGION_CLUSTER — a field that represents the region in which the machine is located."
},
{
"code": null,
"e": 2760,
"s": 2649,
"text": "MAINTENANCE_VENDOR — a field that represents the company that provides maintenance and service to the machine."
},
{
"code": null,
"e": 2832,
"s": 2760,
"text": "MANUFACTURER — the company that manufactured the equipment in question."
},
{
"code": null,
"e": 2887,
"s": 2832,
"text": "WELL_GROUP — a field representing the type of Machine."
},
{
"code": null,
"e": 2932,
"s": 2887,
"text": "EQUIPMENT_AGE — Age of the machine, in days."
},
{
"code": null,
"e": 2954,
"s": 2932,
"text": "S15 — A Sensor Value."
},
{
"code": null,
"e": 2976,
"s": 2954,
"text": "S17 — A Sensor Value."
},
{
"code": null,
"e": 2998,
"s": 2976,
"text": "S13 — A Sensor Value."
},
{
"code": null,
"e": 3020,
"s": 2998,
"text": "S16 — A Sensor Value."
},
{
"code": null,
"e": 3042,
"s": 3020,
"text": "S19 — A Sensor Value."
},
{
"code": null,
"e": 3064,
"s": 3042,
"text": "S18 — A Sensor Value."
},
{
"code": null,
"e": 3085,
"s": 3064,
"text": "S8 — A Sensor Value."
},
{
"code": null,
"e": 3184,
"s": 3085,
"text": "EQUIPMENT_FAILURE — A ‘1’ means that the equipment failed. A ‘0’ means the equipment did not fail."
},
{
"code": null,
"e": 3407,
"s": 3184,
"text": "This data represents a panel data set. We have multiple machines measured over mulitple time periods. ID represents the machine and DATE represents the date. Now, let’s examine how many machines and how many dates we have."
},
{
"code": null,
"e": 3488,
"s": 3407,
"text": "Examine the number of rows and columns. The data has 307,751 rows and 16 columns"
},
{
"code": null,
"e": 3502,
"s": 3488,
"text": "pd_data.shape"
},
{
"code": null,
"e": 3542,
"s": 3502,
"text": "There are 421 machines in the data set."
},
{
"code": null,
"e": 3612,
"s": 3542,
"text": "xxxx = pd.DataFrame(pd_data.groupby(['ID']).agg(['count']))xxxx.shape"
},
{
"code": null,
"e": 3656,
"s": 3612,
"text": "There are 731 unique dates in the data set."
},
{
"code": null,
"e": 3728,
"s": 3656,
"text": "xxxx = pd.DataFrame(pd_data.groupby(['DATE']).agg(['count']))xxxx.shape"
},
{
"code": null,
"e": 3960,
"s": 3728,
"text": "We could just randomly assign each record to either the training, testing or validation group. While that could work, I wouldn’t recommend it. I would recommend assigning records to groups at an entity level (machine in this case)."
},
{
"code": null,
"e": 3965,
"s": 3960,
"text": "Why?"
},
{
"code": null,
"e": 4106,
"s": 3965,
"text": "Well, I could use some multi-syllabic words (like auto-correlation, boomerang or mayonnaise) to describe why, but let’s just think about it."
},
{
"code": null,
"e": 4180,
"s": 4106,
"text": "Why do we separate the data into training, testing and validation groups?"
},
{
"code": null,
"e": 4325,
"s": 4180,
"text": "We want to ensure that our model is not over-fit. In other words, we want to make sure that our model applies to new data as it comes available."
},
{
"code": null,
"e": 4683,
"s": 4325,
"text": "For example, let’s pretend that we built a model that predicts what happened last year with 100% accuracy. Good job, right? Well, it really doesn’t matter how well the model predicts last year. We need it to predict today, tomorrow and the day after that. So, if a model predicts last year with 100% accuracy but fails to predict tomorrow, it kind of sucks."
},
{
"code": null,
"e": 4901,
"s": 4683,
"text": "Building a model on the training data and verifying the accuracy on the testing and validation data set reduces the chances of over-fitting (Note, it is still possible but I will save that discussion for another day)."
},
{
"code": null,
"e": 5137,
"s": 4901,
"text": "In order to prevent over-fitting, our training, testing and validation groups must be independent. That is, the data in the training group must be different than the testing and validation groups. Or, at least as different as possible."
},
{
"code": null,
"e": 5235,
"s": 5137,
"text": "So what happens if we just randomly assign each record in a panel data set to each of the groups?"
},
{
"code": null,
"e": 5290,
"s": 5235,
"text": "We end up with records from each entity in each group."
},
{
"code": null,
"e": 5697,
"s": 5290,
"text": "For example with a simple random selection method, if we are dealing with 100 machines measured daily over 100 days, it is probable that the machine physically sitting beside the break room will appear in the training, testing and validation groups. Likewise, if you are dealing with individuals (one of whom is named Steve Wakahookie), it is probable that Steve Wakahookie will appear in all three groups."
},
{
"code": null,
"e": 5872,
"s": 5697,
"text": "In other words, your training, testing and validation groups ARE NOT independent because good ol’ Steve and the machine beside the break room are present in all three groups."
},
{
"code": null,
"e": 6027,
"s": 5872,
"text": "Steve is in the testing. Steve is in the training. Steve is in the validation. If he is lurking in all three groups, the three groups are not independent."
},
{
"code": null,
"e": 6283,
"s": 6027,
"text": "Now, if we assign group membership based on entity, all of the Steve’s records will be in either the training, testing or validation group. Likewise, all of the records associated with the machine by the break room will be in only one of the three groups."
},
{
"code": null,
"e": 6375,
"s": 6283,
"text": "If Steve is in the training, but not the testing or validation, the groups ARE independent."
},
{
"code": null,
"e": 6494,
"s": 6375,
"text": "If the machine by the break room is in the testing, but not in the training or validation, the groups ARE independent."
},
{
"code": null,
"e": 6611,
"s": 6494,
"text": "Here is a few lines of python code to that ensure that your training, testing and validation groups are independent."
},
{
"code": null,
"e": 6652,
"s": 6611,
"text": "Get a Unique List of All IDs (machines)."
},
{
"code": null,
"e": 6730,
"s": 6652,
"text": "aa=pd_datapd_id=aa.drop_duplicates(subset='ID')pd_id=pd_id[['ID']]pd_id.shape"
},
{
"code": null,
"e": 6789,
"s": 6730,
"text": "Create a new variable with a random number between 0 and ."
},
{
"code": null,
"e": 6906,
"s": 6789,
"text": "np.random.seed(42)pd_id['wookie'] = (np.random.randint(0, 10000, pd_id.shape[0]))/10000pd_id=pd_id[['ID', 'wookie']]"
},
{
"code": null,
"e": 7054,
"s": 6906,
"text": "Give each machine a 30% chance of being in the validation, a 35% chance of being in the testing and a 35% chance of being in the training data set."
},
{
"code": null,
"e": 7188,
"s": 7054,
"text": "pd_id['MODELING_GROUP'] = np.where(((pd_id.wookie <= 0.35)), 'TRAINING', np.where(((pd_id.wookie <= 0.65)), 'VALIDATION', 'TESTING'))"
},
{
"code": null,
"e": 7234,
"s": 7188,
"text": "This is how many machines fall in each group."
},
{
"code": null,
"e": 7311,
"s": 7234,
"text": "tips_summed = pd_id.groupby([‘MODELING_GROUP’])[‘wookie’].count()tips_summed"
},
{
"code": null,
"e": 7366,
"s": 7311,
"text": "Append the Group of each id to each individual record."
},
{
"code": null,
"e": 7542,
"s": 7366,
"text": "pd_data=pd_data.sort_values(by=['ID'], ascending=[True])pd_id=pd_id.sort_values(by=['ID'], ascending=[True])pd_data =pd_data.merge(pd_id, on=['ID'], how='inner')pd_data.head()"
},
{
"code": null,
"e": 7586,
"s": 7542,
"text": "This is how many records are in each group."
},
{
"code": null,
"e": 7665,
"s": 7586,
"text": "tips_summed = pd_data.groupby(['MODELING_GROUP'])['wookie'].count()tips_summed"
},
{
"code": null,
"e": 7927,
"s": 7665,
"text": "So, there you go. Now, we are ready to build a machine learning model. By placing entities and not records into your training, testing and validation groups you can ensure independence between the groups and build models that work yesterday, today and tomorrow."
}
] |
Change Cursor Color with CSS caret-color
|
For changing the color of insertion caret, CSS caret-color property is used.
The following examples illustrate the CSS caret-color property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
form {
padding: 2%;
margin: 2%;
text-align: center;
}
form:focus-within {
box-shadow: 0 0 10px rgba(0,0,0,0.6);
background-color: beige;
}
input {
font-size: 3em;
caret-color: chartreuse;
margin: 2%;
}
</style>
</head>
<body>
<form>
<input value="Check the caret color!" />
<button>Hit!</button>
</form>
</body>
</html>
This will produce the following result −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
form {
padding: 2%;
margin: 2%;
background-color: thistle;
}
form:focus-within {
box-shadow: 0 0 10px rgba(0,0,0,0.6);
}
textarea {
caret-color: transparent;
}
</style>
</head>
<body>
<form>
<input type="radio" />1
<input type="radio" />2
<textarea placeholder="Invisible"></textarea>
</form>
</body>
</html>
This will produce the following result −
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "For changing the color of insertion caret, CSS caret-color property is used."
},
{
"code": null,
"e": 1203,
"s": 1139,
"text": "The following examples illustrate the CSS caret-color property."
},
{
"code": null,
"e": 1214,
"s": 1203,
"text": " Live Demo"
},
{
"code": null,
"e": 1596,
"s": 1214,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nform {\n padding: 2%;\n margin: 2%;\n text-align: center;\n}\nform:focus-within {\n box-shadow: 0 0 10px rgba(0,0,0,0.6);\n background-color: beige;\n}\ninput {\n font-size: 3em;\n caret-color: chartreuse;\n margin: 2%;\n}\n</style>\n</head>\n<body>\n<form>\n<input value=\"Check the caret color!\" />\n<button>Hit!</button>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 1637,
"s": 1596,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": " Live Demo"
},
{
"code": null,
"e": 2010,
"s": 1648,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nform {\n padding: 2%;\n margin: 2%;\n background-color: thistle;\n}\nform:focus-within {\n box-shadow: 0 0 10px rgba(0,0,0,0.6);\n}\ntextarea {\n caret-color: transparent;\n}\n</style>\n</head>\n<body>\n<form>\n<input type=\"radio\" />1\n<input type=\"radio\" />2\n<textarea placeholder=\"Invisible\"></textarea>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2051,
"s": 2010,
"text": "This will produce the following result −"
}
] |
How to select the maximum value of a column in MySQL?
|
You can use ORDER BY clause or aggregate function MAX() to select the maximum value.
Following is the syntax −
select yourColumnName from yourTableName order by yourColumnName desc limit 0,1;
Let us first create a table −
mysql> create table DemoTable
(
Number int
);
Query OK, 0 rows affected (0.52 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(790);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(746);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(480);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(880);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(879);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------+
| Number |
+--------+
| 790 |
| 746 |
| 480 |
| 880 |
| 879 |
+--------+
5 rows in set (0.00 sec)
Following is the query to select the maximum value of a column in MySQL −
mysql> select Number from DemoTable order by Number desc limit 0,1;
This will produce the following output −
+--------+
| Number |
+--------+
| 880 |
+--------+
1 row in set (0.00 sec)
You can also use aggregate function MAX() for this −
mysql> select MAX(Number) from DemoTable;
This will produce the following output −
+-------------+
| MAX(Number) |
+-------------+
| 880 |
+-------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "You can use ORDER BY clause or aggregate function MAX() to select the maximum value."
},
{
"code": null,
"e": 1173,
"s": 1147,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1254,
"s": 1173,
"text": "select yourColumnName from yourTableName order by yourColumnName desc limit 0,1;"
},
{
"code": null,
"e": 1284,
"s": 1254,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1376,
"s": 1284,
"text": "mysql> create table DemoTable\n (\n Number int\n );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1427,
"s": 1376,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1817,
"s": 1427,
"text": "mysql> insert into DemoTable values(790);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(746);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values(480);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(880);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(879);\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 1877,
"s": 1817,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1909,
"s": 1877,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1950,
"s": 1909,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2074,
"s": 1950,
"text": "+--------+\n| Number |\n+--------+\n| 790 |\n| 746 |\n| 480 |\n| 880 |\n| 879 |\n+--------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2148,
"s": 2074,
"text": "Following is the query to select the maximum value of a column in MySQL −"
},
{
"code": null,
"e": 2216,
"s": 2148,
"text": "mysql> select Number from DemoTable order by Number desc limit 0,1;"
},
{
"code": null,
"e": 2257,
"s": 2216,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2336,
"s": 2257,
"text": "+--------+\n| Number |\n+--------+\n| 880 |\n+--------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2389,
"s": 2336,
"text": "You can also use aggregate function MAX() for this −"
},
{
"code": null,
"e": 2431,
"s": 2389,
"text": "mysql> select MAX(Number) from DemoTable;"
},
{
"code": null,
"e": 2472,
"s": 2431,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2576,
"s": 2472,
"text": "+-------------+\n| MAX(Number) |\n+-------------+\n| 880 |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
Recovering Lost Commits in Git - GeeksforGeeks
|
10 May, 2020
Git is a very powerful tool, and with great power comes great responsibilities. If not used and handles properly, It might cause you to lose your commits. There might be situations when you may find all of your work missing at once.
If you have regularly committed your work, there is a way to recover these lost commits.This tutorial will aim at using the
git reflog
and the
git cherry-pick
commands to recover your lost commits in Git.
Note: Using the reflog will only work for a certain amount of time after the commits are lost. Git cleans the reflog periodically, so don’t wait too long!
The first step to recovering your lost commits is to recover the list of all your previous commits and actions done on the repository.
Note: Keep in mind that the given commit hashes and signatures may differ from that of your local repository. Replace all relevant information with the info corresponding to your log.
Run this command
git reflog
After running the command this is what you will see as the output.
$ git reflog
c9f9669 HEAD@{0}: commit: Fixed test cases to run on Unix
b3ca8a4 HEAD@{1}: pull: Fast-forward
54ba188 HEAD@{2}: pull origin master: Fast-forward
e659a21 HEAD@{3}: reset: moving to HEAD~1
12944d8 HEAD@{4}: reset: moving to HEAD~1
6f40152 HEAD@{5}: reset: moving to HEAD~1
3de61ba HEAD@{6}: pull: Fast-forward
e659a21 HEAD@{7}: reset: moving to HEAD^1
12944d8 HEAD@{8}: reset: moving to HEAD^1
6f40152 HEAD@{9}: reset: moving to HEAD^1
3de61ba HEAD@{10}: commit: Removed Query object
6f40152 HEAD@{11}: pull: Merge made by the 'recursive' strategy.
12944d8 HEAD@{12}: commit: API touchups --- We want to recover this commit.
e659a21 HEAD@{13}: commit: Test enhancements
07419e1 HEAD@{14}: pull: Fast-forward
Find of the Hash of the commit you want to recover, For ex-12944d8.Now use the following command to bring your lost commit back.
git cherry-pick 12944d8
That’s it! Your work should be recovered soon with the following success commands:
Finished one cherry-pick.
[master 12944d8] API touchups
3 files changed, 36 insertions(+), 3 deletions(-)
If there is a merge conflict, the following message will show up.
error: could not apply 12944d8... API touchups
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add ' or 'git rm '
hint: and commit the result with 'git commit'
using the git status command can help you identify what has to be done.
Picked
Git
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Set Git Username and Password in GitBash?
Difference Between Git Push Origin and Git Push Origin Master
How to Undo a Commit in Git ?
How to Push Git Branch to Remote?
Deleting a Local GitHub Repository
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24527,
"s": 24294,
"text": "Git is a very powerful tool, and with great power comes great responsibilities. If not used and handles properly, It might cause you to lose your commits. There might be situations when you may find all of your work missing at once."
},
{
"code": null,
"e": 24651,
"s": 24527,
"text": "If you have regularly committed your work, there is a way to recover these lost commits.This tutorial will aim at using the"
},
{
"code": null,
"e": 24663,
"s": 24651,
"text": " git reflog"
},
{
"code": null,
"e": 24671,
"s": 24663,
"text": "and the"
},
{
"code": null,
"e": 24687,
"s": 24671,
"text": "git cherry-pick"
},
{
"code": null,
"e": 24733,
"s": 24687,
"text": "commands to recover your lost commits in Git."
},
{
"code": null,
"e": 24888,
"s": 24733,
"text": "Note: Using the reflog will only work for a certain amount of time after the commits are lost. Git cleans the reflog periodically, so don’t wait too long!"
},
{
"code": null,
"e": 25023,
"s": 24888,
"text": "The first step to recovering your lost commits is to recover the list of all your previous commits and actions done on the repository."
},
{
"code": null,
"e": 25207,
"s": 25023,
"text": "Note: Keep in mind that the given commit hashes and signatures may differ from that of your local repository. Replace all relevant information with the info corresponding to your log."
},
{
"code": null,
"e": 25224,
"s": 25207,
"text": "Run this command"
},
{
"code": null,
"e": 25235,
"s": 25224,
"text": "git reflog"
},
{
"code": null,
"e": 25302,
"s": 25235,
"text": "After running the command this is what you will see as the output."
},
{
"code": null,
"e": 26028,
"s": 25302,
"text": "$ git reflog\nc9f9669 HEAD@{0}: commit: Fixed test cases to run on Unix\nb3ca8a4 HEAD@{1}: pull: Fast-forward\n54ba188 HEAD@{2}: pull origin master: Fast-forward\ne659a21 HEAD@{3}: reset: moving to HEAD~1\n12944d8 HEAD@{4}: reset: moving to HEAD~1\n6f40152 HEAD@{5}: reset: moving to HEAD~1\n3de61ba HEAD@{6}: pull: Fast-forward\ne659a21 HEAD@{7}: reset: moving to HEAD^1\n12944d8 HEAD@{8}: reset: moving to HEAD^1\n6f40152 HEAD@{9}: reset: moving to HEAD^1\n3de61ba HEAD@{10}: commit: Removed Query object \n6f40152 HEAD@{11}: pull: Merge made by the 'recursive' strategy.\n12944d8 HEAD@{12}: commit: API touchups --- We want to recover this commit.\ne659a21 HEAD@{13}: commit: Test enhancements\n07419e1 HEAD@{14}: pull: Fast-forward\n"
},
{
"code": null,
"e": 26157,
"s": 26028,
"text": "Find of the Hash of the commit you want to recover, For ex-12944d8.Now use the following command to bring your lost commit back."
},
{
"code": null,
"e": 26183,
"s": 26157,
"text": " git cherry-pick 12944d8 "
},
{
"code": null,
"e": 26266,
"s": 26183,
"text": "That’s it! Your work should be recovered soon with the following success commands:"
},
{
"code": null,
"e": 26373,
"s": 26266,
"text": "Finished one cherry-pick.\n[master 12944d8] API touchups\n3 files changed, 36 insertions(+), 3 deletions(-)\n"
},
{
"code": null,
"e": 26439,
"s": 26373,
"text": "If there is a merge conflict, the following message will show up."
},
{
"code": null,
"e": 26630,
"s": 26439,
"text": "error: could not apply 12944d8... API touchups\nhint: after resolving the conflicts, mark the corrected paths\nhint: with 'git add ' or 'git rm '\nhint: and commit the result with 'git commit'\n"
},
{
"code": null,
"e": 26702,
"s": 26630,
"text": "using the git status command can help you identify what has to be done."
},
{
"code": null,
"e": 26709,
"s": 26702,
"text": "Picked"
},
{
"code": null,
"e": 26713,
"s": 26709,
"text": "Git"
},
{
"code": null,
"e": 26729,
"s": 26713,
"text": "Write From Home"
},
{
"code": null,
"e": 26827,
"s": 26729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26836,
"s": 26827,
"text": "Comments"
},
{
"code": null,
"e": 26849,
"s": 26836,
"text": "Old Comments"
},
{
"code": null,
"e": 26898,
"s": 26849,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26960,
"s": 26898,
"text": "Difference Between Git Push Origin and Git Push Origin Master"
},
{
"code": null,
"e": 26990,
"s": 26960,
"text": "How to Undo a Commit in Git ?"
},
{
"code": null,
"e": 27024,
"s": 26990,
"text": "How to Push Git Branch to Remote?"
},
{
"code": null,
"e": 27059,
"s": 27024,
"text": "Deleting a Local GitHub Repository"
},
{
"code": null,
"e": 27095,
"s": 27059,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27131,
"s": 27095,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27192,
"s": 27131,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27208,
"s": 27192,
"text": "Python infinity"
}
] |
How to Calculate a Five Number Summary in Excel? - GeeksforGeeks
|
18 Jul, 2021
In statistics, the five-number summary is mostly used as it gives a rough idea about the dataset. It is basically a summary of the dataset describing some key features in statistics. The five key features are :
Minimum value: It is the minimum value in the data setFirst Quartile, Q1: It is also known as the lower quartile where 25% of the scores fall below it.Median (middle value) or second quartile: It is basically the mid-value in the dataset.Third Quartile, Q3: It is also known as the Upper quartile in which 25% of the data is above it and the rest 75% falls below it.Maximum value: It is the maximum value in the dataset.
Minimum value: It is the minimum value in the data set
First Quartile, Q1: It is also known as the lower quartile where 25% of the scores fall below it.
Median (middle value) or second quartile: It is basically the mid-value in the dataset.
Third Quartile, Q3: It is also known as the Upper quartile in which 25% of the data is above it and the rest 75% falls below it.
Maximum value: It is the maximum value in the dataset.
It is important to note that we can find the Five-number summary only for a single variable dataset. It is meaningless to calculate the Five-number summary for two variables data also known as bivariate.
These five number summaries give a concise inference about the distribution of the dataset. Using these quartiles we can find the Interquartile Range and create a Box Plot out of it. For more details refer Creating Box Plots in Excel.
In this article, we are going to discuss how to calculate the Five-number summary in Excel using a suitable example.
The following Excel in-built functions can be used to calculate the above quartiles.
QUARTILE(Array,quart) // Used in Excel 2007 version and lower
Array : Cell range
quart : The five quart values from 0 to 4
0- Minimum value
1- First Quartile (25 percent)
2- Median Value (50 percentile)
3- Third Quartile (75 percentile)
4- Maximum value
In the latest version of Excel, we use the function
QUARTILE.INC(Array,quart)
The parameters and quart values are the same as discussed above.
To calculate the minimum, maximum, and median values we can also use the following functions :
=MIN(Array) //to calculate minimum value
=MAX(Array) //to calculate maximum value
=MEDIAN(Array) //to calculate second quartile or the median
Example: Consider the dataset which consists of information about the BMI of 10 geeks.
Dataset
1. Minimum and Maximum Value
It can either be calculated using the MIN, MAX functions or using the QUARTILE function with quart value as 0 for minimum and 4 for maximum.
The dataset is stored in column “A” of the worksheet and the observations are stored from cell A2 to A11.
So the array will start from A2 and end at A11.
Minimum BMI
Similarly, we can find the maximum value.
Maximum BMI
2. Median value or Second Quartile
The Excel function MEDIAN can be used or we can use the QUARTILE function with quart value as 2.
3. Quartiles Q1 and Q3
The function QUARTILE or QUARTILE.INC is used to calculate these quartile values with quart values 1 for Q1 and 3 for Q3.
Quartile 1
Quartile 3
To calculate all the Five-number summary :
Five-Number Summary
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Easily Calculate the Dot Product in Excel?
|
[
{
"code": null,
"e": 25044,
"s": 25016,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25255,
"s": 25044,
"text": "In statistics, the five-number summary is mostly used as it gives a rough idea about the dataset. It is basically a summary of the dataset describing some key features in statistics. The five key features are :"
},
{
"code": null,
"e": 25677,
"s": 25255,
"text": "Minimum value: It is the minimum value in the data setFirst Quartile, Q1: It is also known as the lower quartile where 25% of the scores fall below it.Median (middle value) or second quartile: It is basically the mid-value in the dataset.Third Quartile, Q3: It is also known as the Upper quartile in which 25% of the data is above it and the rest 75% falls below it.Maximum value: It is the maximum value in the dataset. "
},
{
"code": null,
"e": 25732,
"s": 25677,
"text": "Minimum value: It is the minimum value in the data set"
},
{
"code": null,
"e": 25830,
"s": 25732,
"text": "First Quartile, Q1: It is also known as the lower quartile where 25% of the scores fall below it."
},
{
"code": null,
"e": 25918,
"s": 25830,
"text": "Median (middle value) or second quartile: It is basically the mid-value in the dataset."
},
{
"code": null,
"e": 26047,
"s": 25918,
"text": "Third Quartile, Q3: It is also known as the Upper quartile in which 25% of the data is above it and the rest 75% falls below it."
},
{
"code": null,
"e": 26103,
"s": 26047,
"text": "Maximum value: It is the maximum value in the dataset. "
},
{
"code": null,
"e": 26307,
"s": 26103,
"text": "It is important to note that we can find the Five-number summary only for a single variable dataset. It is meaningless to calculate the Five-number summary for two variables data also known as bivariate."
},
{
"code": null,
"e": 26542,
"s": 26307,
"text": "These five number summaries give a concise inference about the distribution of the dataset. Using these quartiles we can find the Interquartile Range and create a Box Plot out of it. For more details refer Creating Box Plots in Excel."
},
{
"code": null,
"e": 26659,
"s": 26542,
"text": "In this article, we are going to discuss how to calculate the Five-number summary in Excel using a suitable example."
},
{
"code": null,
"e": 26744,
"s": 26659,
"text": "The following Excel in-built functions can be used to calculate the above quartiles."
},
{
"code": null,
"e": 27000,
"s": 26744,
"text": "QUARTILE(Array,quart) // Used in Excel 2007 version and lower\n\nArray : Cell range\nquart : The five quart values from 0 to 4\n\n0- Minimum value\n1- First Quartile (25 percent)\n2- Median Value (50 percentile)\n3- Third Quartile (75 percentile)\n4- Maximum value"
},
{
"code": null,
"e": 27053,
"s": 27000,
"text": "In the latest version of Excel, we use the function "
},
{
"code": null,
"e": 27079,
"s": 27053,
"text": "QUARTILE.INC(Array,quart)"
},
{
"code": null,
"e": 27144,
"s": 27079,
"text": "The parameters and quart values are the same as discussed above."
},
{
"code": null,
"e": 27239,
"s": 27144,
"text": "To calculate the minimum, maximum, and median values we can also use the following functions :"
},
{
"code": null,
"e": 27398,
"s": 27239,
"text": "=MIN(Array) //to calculate minimum value\n=MAX(Array) //to calculate maximum value\n=MEDIAN(Array) //to calculate second quartile or the median"
},
{
"code": null,
"e": 27485,
"s": 27398,
"text": "Example: Consider the dataset which consists of information about the BMI of 10 geeks."
},
{
"code": null,
"e": 27493,
"s": 27485,
"text": "Dataset"
},
{
"code": null,
"e": 27522,
"s": 27493,
"text": "1. Minimum and Maximum Value"
},
{
"code": null,
"e": 27663,
"s": 27522,
"text": "It can either be calculated using the MIN, MAX functions or using the QUARTILE function with quart value as 0 for minimum and 4 for maximum."
},
{
"code": null,
"e": 27770,
"s": 27663,
"text": "The dataset is stored in column “A” of the worksheet and the observations are stored from cell A2 to A11. "
},
{
"code": null,
"e": 27818,
"s": 27770,
"text": "So the array will start from A2 and end at A11."
},
{
"code": null,
"e": 27830,
"s": 27818,
"text": "Minimum BMI"
},
{
"code": null,
"e": 27872,
"s": 27830,
"text": "Similarly, we can find the maximum value."
},
{
"code": null,
"e": 27884,
"s": 27872,
"text": "Maximum BMI"
},
{
"code": null,
"e": 27920,
"s": 27884,
"text": "2. Median value or Second Quartile "
},
{
"code": null,
"e": 28017,
"s": 27920,
"text": "The Excel function MEDIAN can be used or we can use the QUARTILE function with quart value as 2."
},
{
"code": null,
"e": 28040,
"s": 28017,
"text": "3. Quartiles Q1 and Q3"
},
{
"code": null,
"e": 28162,
"s": 28040,
"text": "The function QUARTILE or QUARTILE.INC is used to calculate these quartile values with quart values 1 for Q1 and 3 for Q3."
},
{
"code": null,
"e": 28173,
"s": 28162,
"text": "Quartile 1"
},
{
"code": null,
"e": 28184,
"s": 28173,
"text": "Quartile 3"
},
{
"code": null,
"e": 28227,
"s": 28184,
"text": "To calculate all the Five-number summary :"
},
{
"code": null,
"e": 28247,
"s": 28227,
"text": "Five-Number Summary"
},
{
"code": null,
"e": 28254,
"s": 28247,
"text": "Picked"
},
{
"code": null,
"e": 28260,
"s": 28254,
"text": "Excel"
},
{
"code": null,
"e": 28358,
"s": 28260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28386,
"s": 28358,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 28441,
"s": 28386,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 28482,
"s": 28441,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 28540,
"s": 28482,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 28596,
"s": 28540,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
},
{
"code": null,
"e": 28630,
"s": 28596,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 28646,
"s": 28630,
"text": "Macros in Excel"
},
{
"code": null,
"e": 28697,
"s": 28646,
"text": "How to Extract the Last Word From a Cell in Excel?"
},
{
"code": null,
"e": 28761,
"s": 28697,
"text": "How to Sum Values Based on Criteria in Another Column in Excel?"
}
] |
Filter column value by the first character in MySQL
|
You can use LEFT() from MySQL. Let us first create a −
mysql> create table DemoTable1428
-> (
-> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> EmployeeName varchar(20)
-> );
Query OK, 0 rows affected (1.05 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1428(EmployeeName) values('Chris Brown');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Bob Brown');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Smith');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1428(EmployeeName) values('David Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Doe');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Carol Johnson');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select −
mysql> select * from DemoTable1428;
This will produce the following output −
+------------+---------------+
| EmployeeId | EmployeeName |
+------------+---------------+
| 1 | Chris Brown |
| 2 | Bob Brown |
| 3 | John Smith |
| 4 | David Miller |
| 5 | John Doe |
| 6 | Carol Johnson |
+------------+---------------+
6 rows in set (0.00 sec)
Following is the query to filter column value by the first character −
mysql> select * from DemoTable1428 where left(EmployeeName,1)='J';
This will produce the following output −
+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 3 | John Smith |
| 5 | John Doe |
+------------+--------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "You can use LEFT() from MySQL. Let us first create a −"
},
{
"code": null,
"e": 1294,
"s": 1117,
"text": "mysql> create table DemoTable1428\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> EmployeeName varchar(20)\n -> );\nQuery OK, 0 rows affected (1.05 sec)"
},
{
"code": null,
"e": 1342,
"s": 1294,
"text": "Insert some records in the table using insert −"
},
{
"code": null,
"e": 1975,
"s": 1342,
"text": "mysql> insert into DemoTable1428(EmployeeName) values('Chris Brown');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1428(EmployeeName) values('Bob Brown');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1428(EmployeeName) values('John Smith');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable1428(EmployeeName) values('David Miller');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable1428(EmployeeName) values('John Doe');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable1428(EmployeeName) values('Carol Johnson');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2025,
"s": 1975,
"text": "Display all records from the table using select −"
},
{
"code": null,
"e": 2061,
"s": 2025,
"text": "mysql> select * from DemoTable1428;"
},
{
"code": null,
"e": 2102,
"s": 2061,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2437,
"s": 2102,
"text": "+------------+---------------+\n| EmployeeId | EmployeeName |\n+------------+---------------+\n| 1 | Chris Brown |\n| 2 | Bob Brown |\n| 3 | John Smith |\n| 4 | David Miller |\n| 5 | John Doe |\n| 6 | Carol Johnson |\n+------------+---------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2508,
"s": 2437,
"text": "Following is the query to filter column value by the first character −"
},
{
"code": null,
"e": 2575,
"s": 2508,
"text": "mysql> select * from DemoTable1428 where left(EmployeeName,1)='J';"
},
{
"code": null,
"e": 2616,
"s": 2575,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2821,
"s": 2616,
"text": "+------------+--------------+\n| EmployeeId | EmployeeName |\n+------------+--------------+\n| 3 | John Smith |\n| 5 | John Doe |\n+------------+--------------+\n2 rows in set (0.00 sec)"
}
] |
Amazon Interview | Set 18 - GeeksforGeeks
|
14 Jun, 2019
Amazon visited our campus on 16,17 and 18 Dec.
WRITTEN ROUND(1.5 hrs)
20 MCQ + 2 CODEMCQ- mainly Aptitude, C-output questions, OS- unix related and DBMS
CODE-...1) Binary complement of a number....2) Easy question related to bets
42 out of around 200 students were shortlisted after this round.
ROUND 1:Around 15 min discussion on my image processing project
Finding an element in rotated sorted array.
12 students were shortlisted after this round
ROUND 2:1) Convert postfix to infix in which the result must be having minimum number of braces i.e apply braces whenever necessary.2) Given a binary tree print the sum of elements on same axis (for all axis).Elements on same axis are for e.g.: root, root->right->left, root->left->right3) Design hash table with following operations you are given with a good hashing function..:insert() –O(1)find()-O(1)delete()-O(1)traverse()-O(n)..(where n is the number of elements in hash not the size of hash)4) Given an array find a sub-array with sum=05)
for(i=0;i<n;i++) for(j=0;j<n;j++) cout<<a[i][j]; for(i=0;i<n;i++) for(j=0;j<n;j++) cout<<a[i][j];
out of these 2 which one will be betterI was asked to write the complete code for all the questions.
6 students were shortlisted after this round
ROUND 3:1) Given memory in the form of chunks if one process is reading any chunk, then any other process is not allowed to write but it can read, if write lock is on, then any other process is not allowed to read or write, now process can have lock on any number of chunks (continues) and other process requesting read or write can even request for memory that does not have the same starting address as the process who has locked the continues chunk memory.
Now we have to design a DS for representing memory and then design isRead() and isWrite()which will return Boolean values true-if read/write can be performed vice versa.2) Permutation of a string with and without repetition of characters.3) Given an array of numbers if we start deleting numbers from end of array, then we have to tell the maximum element of the array after deletion in O(1).I was asked to code all the questions.
4 students were shortlisted after this round.
ROUND 4:1) Around half hour discussion on my intern project which was with an e-commerce company.2) Given a linked list with one extra arbit pointer we I was asked to make copy of linked list.
He asked me to write the full code for method 1 in the above link.
In the end 3 students were hired and I was one of them..
I am very thankful to geeksforgeeks It really helped me a lot for my preparation. Keep up the good work guys
This article is compiled by Sahil. Many Many congratulations to Sahil for his selection. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Amazon
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Directi Interview | Set 7 (Programming Questions)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience (Off-Campus) 2022
Zoho Interview | Set 3 (Off-Campus)
Amazon Interview Experience for SDE-1(Off-Campus)
|
[
{
"code": null,
"e": 24596,
"s": 24568,
"text": "\n14 Jun, 2019"
},
{
"code": null,
"e": 24643,
"s": 24596,
"text": "Amazon visited our campus on 16,17 and 18 Dec."
},
{
"code": null,
"e": 24666,
"s": 24643,
"text": "WRITTEN ROUND(1.5 hrs)"
},
{
"code": null,
"e": 24749,
"s": 24666,
"text": "20 MCQ + 2 CODEMCQ- mainly Aptitude, C-output questions, OS- unix related and DBMS"
},
{
"code": null,
"e": 24826,
"s": 24749,
"text": "CODE-...1) Binary complement of a number....2) Easy question related to bets"
},
{
"code": null,
"e": 24891,
"s": 24826,
"text": "42 out of around 200 students were shortlisted after this round."
},
{
"code": null,
"e": 24955,
"s": 24891,
"text": "ROUND 1:Around 15 min discussion on my image processing project"
},
{
"code": null,
"e": 24999,
"s": 24955,
"text": "Finding an element in rotated sorted array."
},
{
"code": null,
"e": 25045,
"s": 24999,
"text": "12 students were shortlisted after this round"
},
{
"code": null,
"e": 25591,
"s": 25045,
"text": "ROUND 2:1) Convert postfix to infix in which the result must be having minimum number of braces i.e apply braces whenever necessary.2) Given a binary tree print the sum of elements on same axis (for all axis).Elements on same axis are for e.g.: root, root->right->left, root->left->right3) Design hash table with following operations you are given with a good hashing function..:insert() –O(1)find()-O(1)delete()-O(1)traverse()-O(n)..(where n is the number of elements in hash not the size of hash)4) Given an array find a sub-array with sum=05)"
},
{
"code": "for(i=0;i<n;i++) for(j=0;j<n;j++) cout<<a[i][j]; for(i=0;i<n;i++) for(j=0;j<n;j++) cout<<a[i][j];",
"e": 25695,
"s": 25591,
"text": null
},
{
"code": null,
"e": 25796,
"s": 25695,
"text": "out of these 2 which one will be betterI was asked to write the complete code for all the questions."
},
{
"code": null,
"e": 25841,
"s": 25796,
"text": "6 students were shortlisted after this round"
},
{
"code": null,
"e": 26301,
"s": 25841,
"text": "ROUND 3:1) Given memory in the form of chunks if one process is reading any chunk, then any other process is not allowed to write but it can read, if write lock is on, then any other process is not allowed to read or write, now process can have lock on any number of chunks (continues) and other process requesting read or write can even request for memory that does not have the same starting address as the process who has locked the continues chunk memory."
},
{
"code": null,
"e": 26732,
"s": 26301,
"text": "Now we have to design a DS for representing memory and then design isRead() and isWrite()which will return Boolean values true-if read/write can be performed vice versa.2) Permutation of a string with and without repetition of characters.3) Given an array of numbers if we start deleting numbers from end of array, then we have to tell the maximum element of the array after deletion in O(1).I was asked to code all the questions."
},
{
"code": null,
"e": 26778,
"s": 26732,
"text": "4 students were shortlisted after this round."
},
{
"code": null,
"e": 26971,
"s": 26778,
"text": "ROUND 4:1) Around half hour discussion on my intern project which was with an e-commerce company.2) Given a linked list with one extra arbit pointer we I was asked to make copy of linked list."
},
{
"code": null,
"e": 27038,
"s": 26971,
"text": "He asked me to write the full code for method 1 in the above link."
},
{
"code": null,
"e": 27096,
"s": 27038,
"text": "In the end 3 students were hired and I was one of them.. "
},
{
"code": null,
"e": 27205,
"s": 27096,
"text": "I am very thankful to geeksforgeeks It really helped me a lot for my preparation. Keep up the good work guys"
},
{
"code": null,
"e": 27515,
"s": 27205,
"text": "This article is compiled by Sahil. Many Many congratulations to Sahil for his selection. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27522,
"s": 27515,
"text": "Amazon"
},
{
"code": null,
"e": 27544,
"s": 27522,
"text": "Interview Experiences"
},
{
"code": null,
"e": 27551,
"s": 27544,
"text": "Amazon"
},
{
"code": null,
"e": 27649,
"s": 27551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27658,
"s": 27649,
"text": "Comments"
},
{
"code": null,
"e": 27671,
"s": 27658,
"text": "Old Comments"
},
{
"code": null,
"e": 27721,
"s": 27671,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 27780,
"s": 27721,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 27818,
"s": 27780,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 27854,
"s": 27818,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 27904,
"s": 27854,
"text": "Directi Interview | Set 7 (Programming Questions)"
},
{
"code": null,
"e": 27942,
"s": 27904,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 28007,
"s": 27942,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 28053,
"s": 28007,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 28089,
"s": 28053,
"text": "Zoho Interview | Set 3 (Off-Campus)"
}
] |
Winner of an election | Practice | GeeksforGeeks
|
Given an array of names (consisting of lowercase characters) of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidate that received Max votes. If there is tie, print lexicographically smaller name.
Example 1:
Input:
n = 13
Votes[] = {john,johnny,jackie,johnny,john
jackie,jamie,jamie,john,johnny,jamie,
johnny,john}
Output: john 4
Explanation: john has 4 votes casted for
him, but so does johny. john is
lexicographically smaller, so we print
john and the votes he received.
Example 2:
Input:
n = 3
Votes[] = {andy,blake,clark}
Output: andy 1
Explanation: All the candidates get 1
votes each. We print andy as it is
lexicographically smaller.
Your Task:
You only need to complete the function winner() that takes an array of strings arr, and n as parameters and returns the name of the candiate with maximum votes and the number of votes the candidate got as an array of size 2.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 <= n <= 105
0
parikshitparmar6 hours ago
from collections import Counter counter_dict = Counter(arr) max_val = [max(counter_dict.values())] d = [k for k,v in counter_dict.items() if v == max_val[0]] d.sort() return (d[0], max_val[0])
0
adamyasharma4933 days ago
Easy to Understand Time:O(n) and Space :O(n) + only two traversals
vector<string> winner(string arr[],int n) { unordered_map<string , int> m ; vector<string> ans ; for(int i=0; i< n ; i++) { m[arr[i]]++ ; } string s; int res= INT_MIN ; for(auto x: m) { if(x.second > res ) { s= x.first ; res = x.second ; } if(x.second == res) { if(s.length() != 0) { s = (s < x.first)? s :x.first ; } } } string votes = to_string(res) ; ans.push_back(s) ; ans.push_back(votes) ; return ans ;
0
singhvipnesh66 days ago
class Solution{ //Function to return the name of candidate that received maximum votes. public static String[] winner(String arr[], int n) { Arrays.sort(arr); HashMap<String,Integer>map=new HashMap<>(); for(int i=0;i<arr.length;i++) { if(!map.containsKey(arr[i])) map.put(arr[i],1); else map.put(arr[i],map.get(arr[i])+1); } int k=0; String[] s = new String[2]; int count; int min=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { count=map.get(arr[i]); if(count>min) { min=count; s[0]=arr[i]; s[1]=String.valueOf(min); } } return s; }}
0
ziaurrahman1 week ago
Easy To Understand JAVA Solution
HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int i=0; i<n; i++){ String s= arr[i]; if(map.containsKey(s)){ map.put(s,map.getOrDefault(s,0)+1); } else{ map.put(s,1); } } int max=Integer.MIN_VALUE; for(String i: map.keySet()){ if(map.get(i) > max){ max=map.get(i); } } ArrayList<String> list= new ArrayList<String>(); for(String i: arr){ if(map.get(i)==max && !list.contains(i)){ list.add(i); } } Collections.sort(list); String[] ans = new String[2]; ans[0] = list.get(0); ans[1] = Integer.toString(max); return ans;
0
shubham211019971 week ago
Easiest solution avilable on internet -→using hashing and lambda expression
public static String[] winner(String arr[], int n)
{
Map<String,Integer>h=new HashMap<>();
for(String i:arr){
h.put(i,h.getOrDefault(i,0)+1);
}
Arrays.sort(arr,(n1,n2)->{
int f1=h.get(n1);
int f2=h.get(n2);
if(f1!=f2) return f2-f1;
else
return n1.compareTo(n2);
});
String[] str=new String[2];
str[0]=arr[0];
str[1]=""+h.get(arr[0]);
return str;
}
0
gautam2002pandeyjee1 week ago
See how to make things complex.
class Solution{ //Function to return the name of candidate that received maximum votes. public static String[] winner(String arr[], int n) { // Here you need to make a HashMap of String and integer. int max = 0; int num = 0; String str1= null; HashMap<String,Integer> has = new HashMap<>(); for(String str: arr){ has.put(str,has.getOrDefault(str,0)+1); } for(Map.Entry<String,Integer> set: has.entrySet()){ if(set.getValue()>max) max = set.getValue(); } for(Map.Entry<String,Integer> set : has.entrySet()){ if(set.getValue()==max){ str1 = set.getKey(); } } for(Map.Entry<String,Integer> set: has.entrySet()){ if(set.getValue()==max){ if(str1.compareTo(set.getKey())>0){ str1 = set.getKey(); } } } Integer min = max; String arrr[]= {str1,min.toString()}; return arrr; }}
+3
mazumderg5373 weeks ago
EASY HASHING SOLUTION IN CPP
vector<string> winner(string arr[],int n)
{
// Your code here
// Return the string containing the name and an integer
// representing the number of votes the winning candidate got
unordered_map<string , int>umap;
for(int i=0;i<n;i++){
umap[arr[i]]++;
}
string name = "";
int max_vote = 0;
for(auto itr = umap.begin(); itr!=umap.end(); itr++){
string key = itr->first;
int val = itr->second;
if(val>max_vote){
max_vote = val;
name = key;
}
else if(val == max_vote){
if(key<name)
name = key;
}
}
vector<string> ans;
ans.push_back(name);
string temp = to_string(max_vote);
ans.push_back(temp);
return ans;
}
0
jerinvarghese0274 weeks ago
total time taken = 0.05
def winner(self,arr,n): # Your code here # return the name of the winning candidate and the votes he recieved vote = {} for i in arr: if i in vote.keys(): vote[i] += 1 else: vote[i] = 1 maxVal = 0 for i in set(vote.values()): if i > maxVal: maxVal = i winners = [] for i,j in vote.items(): if j == maxVal: winners.append(i) minWord = min(winners) return minWord, maxVal
0
haulya4 weeks ago
vector<string> winner(string arr[],int n) { // Your code here // Return the string containing the name and an integer // representing the number of votes the winning candidate got
unordered_map<string, int>um; for(int i = 0; i < n; i++){ um[arr[i]]++; } string winner = arr[0]; int maxvotes = 0; for(auto it = um.begin(); it != um.end(); it++){ if(maxvotes < (*it).second){ winner = (*it).first; maxvotes = (*it).second; } else if(maxvotes == (*it).second && (winner > (*it).first)){ winner = (*it).first; } } vector<string> res; res.push_back(winner); res.push_back(to_string(maxvotes)); return res; }
+1
kartikeyashokgautam1 month ago
Easy To understand JAVA Solution :-
public static String[] winner(String arr[], int n) { String[] result = new String[2]; // storing candidates with their votes HashMap<String,Integer> hm = new HashMap<>(); for(String s : arr) { if(hm.containsKey(s)) { hm.put(s,hm.get(s)+1); } else { hm.put(s,1); } } // Finding who got the max votes int max=0; for(String s: arr) { if(hm.get(s)>max) { int temp = max; max=hm.get(s); } } // Since by default priority queue gives ans in ascending order // therefore here also pq will give ans in lexicographcally (alphabetically ascending order) PriorityQueue<String> pq = new PriorityQueue<>(); for(String s: hm.keySet()) { // Add only if candidate get maximum votes
// so , only candidates with maximum votes will be added in "lexicographically" fashion
// candidate with smallest lexicographical value will at peek of PQ.
if(hm.get(s)==max) { pq.add(s); } } result[0]=pq.peek(); result[1]=Integer.toString(max); //converting Integer value of vote to string as Return type is String return result; }
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.
|
[
{
"code": null,
"e": 506,
"s": 238,
"text": "Given an array of names (consisting of lowercase characters) of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidate that received Max votes. If there is tie, print lexicographically smaller name."
},
{
"code": null,
"e": 517,
"s": 506,
"text": "Example 1:"
},
{
"code": null,
"e": 787,
"s": 517,
"text": "Input:\nn = 13\nVotes[] = {john,johnny,jackie,johnny,john \njackie,jamie,jamie,john,johnny,jamie,\njohnny,john}\nOutput: john 4\nExplanation: john has 4 votes casted for \nhim, but so does johny. john is \nlexicographically smaller, so we print \njohn and the votes he received."
},
{
"code": null,
"e": 798,
"s": 787,
"text": "Example 2:"
},
{
"code": null,
"e": 958,
"s": 798,
"text": "Input:\nn = 3\nVotes[] = {andy,blake,clark}\nOutput: andy 1\nExplanation: All the candidates get 1 \nvotes each. We print andy as it is \nlexicographically smaller.\n"
},
{
"code": null,
"e": 1194,
"s": 958,
"text": "Your Task:\nYou only need to complete the function winner() that takes an array of strings arr, and n as parameters and returns the name of the candiate with maximum votes and the number of votes the candidate got as an array of size 2."
},
{
"code": null,
"e": 1256,
"s": 1194,
"text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1283,
"s": 1256,
"text": "Constraints:\n1 <= n <= 105"
},
{
"code": null,
"e": 1285,
"s": 1283,
"text": "0"
},
{
"code": null,
"e": 1312,
"s": 1285,
"text": "parikshitparmar6 hours ago"
},
{
"code": null,
"e": 1535,
"s": 1312,
"text": "from collections import Counter counter_dict = Counter(arr) max_val = [max(counter_dict.values())] d = [k for k,v in counter_dict.items() if v == max_val[0]] d.sort() return (d[0], max_val[0])"
},
{
"code": null,
"e": 1537,
"s": 1535,
"text": "0"
},
{
"code": null,
"e": 1563,
"s": 1537,
"text": "adamyasharma4933 days ago"
},
{
"code": null,
"e": 1634,
"s": 1563,
"text": "Easy to Understand Time:O(n) and Space :O(n) + only two traversals "
},
{
"code": null,
"e": 2319,
"s": 1634,
"text": " vector<string> winner(string arr[],int n) { unordered_map<string , int> m ; vector<string> ans ; for(int i=0; i< n ; i++) { m[arr[i]]++ ; } string s; int res= INT_MIN ; for(auto x: m) { if(x.second > res ) { s= x.first ; res = x.second ; } if(x.second == res) { if(s.length() != 0) { s = (s < x.first)? s :x.first ; } } } string votes = to_string(res) ; ans.push_back(s) ; ans.push_back(votes) ; return ans ; "
},
{
"code": null,
"e": 2323,
"s": 2321,
"text": "0"
},
{
"code": null,
"e": 2347,
"s": 2323,
"text": "singhvipnesh66 days ago"
},
{
"code": null,
"e": 3094,
"s": 2347,
"text": "class Solution{ //Function to return the name of candidate that received maximum votes. public static String[] winner(String arr[], int n) { Arrays.sort(arr); HashMap<String,Integer>map=new HashMap<>(); for(int i=0;i<arr.length;i++) { if(!map.containsKey(arr[i])) map.put(arr[i],1); else map.put(arr[i],map.get(arr[i])+1); } int k=0; String[] s = new String[2]; int count; int min=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { count=map.get(arr[i]); if(count>min) { min=count; s[0]=arr[i]; s[1]=String.valueOf(min); } } return s; }}"
},
{
"code": null,
"e": 3098,
"s": 3096,
"text": "0"
},
{
"code": null,
"e": 3120,
"s": 3098,
"text": "ziaurrahman1 week ago"
},
{
"code": null,
"e": 3153,
"s": 3120,
"text": "Easy To Understand JAVA Solution"
},
{
"code": null,
"e": 3963,
"s": 3153,
"text": " HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int i=0; i<n; i++){ String s= arr[i]; if(map.containsKey(s)){ map.put(s,map.getOrDefault(s,0)+1); } else{ map.put(s,1); } } int max=Integer.MIN_VALUE; for(String i: map.keySet()){ if(map.get(i) > max){ max=map.get(i); } } ArrayList<String> list= new ArrayList<String>(); for(String i: arr){ if(map.get(i)==max && !list.contains(i)){ list.add(i); } } Collections.sort(list); String[] ans = new String[2]; ans[0] = list.get(0); ans[1] = Integer.toString(max); return ans; "
},
{
"code": null,
"e": 3965,
"s": 3963,
"text": "0"
},
{
"code": null,
"e": 3991,
"s": 3965,
"text": "shubham211019971 week ago"
},
{
"code": null,
"e": 4067,
"s": 3991,
"text": "Easiest solution avilable on internet -→using hashing and lambda expression"
},
{
"code": null,
"e": 4568,
"s": 4067,
"text": "public static String[] winner(String arr[], int n)\n {\n Map<String,Integer>h=new HashMap<>();\n for(String i:arr){\n h.put(i,h.getOrDefault(i,0)+1);\n }\n Arrays.sort(arr,(n1,n2)->{\n int f1=h.get(n1);\n int f2=h.get(n2);\n \n if(f1!=f2) return f2-f1;\n else\n return n1.compareTo(n2);\n \n });\n \n String[] str=new String[2];\n str[0]=arr[0];\n str[1]=\"\"+h.get(arr[0]);\n return str;\n }"
},
{
"code": null,
"e": 4570,
"s": 4568,
"text": "0"
},
{
"code": null,
"e": 4600,
"s": 4570,
"text": "gautam2002pandeyjee1 week ago"
},
{
"code": null,
"e": 4632,
"s": 4600,
"text": "See how to make things complex."
},
{
"code": null,
"e": 5724,
"s": 4632,
"text": "class Solution{ //Function to return the name of candidate that received maximum votes. public static String[] winner(String arr[], int n) { // Here you need to make a HashMap of String and integer. int max = 0; int num = 0; String str1= null; HashMap<String,Integer> has = new HashMap<>(); for(String str: arr){ has.put(str,has.getOrDefault(str,0)+1); } for(Map.Entry<String,Integer> set: has.entrySet()){ if(set.getValue()>max) max = set.getValue(); } for(Map.Entry<String,Integer> set : has.entrySet()){ if(set.getValue()==max){ str1 = set.getKey(); } } for(Map.Entry<String,Integer> set: has.entrySet()){ if(set.getValue()==max){ if(str1.compareTo(set.getKey())>0){ str1 = set.getKey(); } } } Integer min = max; String arrr[]= {str1,min.toString()}; return arrr; }}"
},
{
"code": null,
"e": 5729,
"s": 5726,
"text": "+3"
},
{
"code": null,
"e": 5753,
"s": 5729,
"text": "mazumderg5373 weeks ago"
},
{
"code": null,
"e": 5782,
"s": 5753,
"text": "EASY HASHING SOLUTION IN CPP"
},
{
"code": null,
"e": 6685,
"s": 5782,
"text": " vector<string> winner(string arr[],int n)\n {\n // Your code here\n // Return the string containing the name and an integer\n // representing the number of votes the winning candidate got\n unordered_map<string , int>umap;\n for(int i=0;i<n;i++){\n umap[arr[i]]++;\n }\n \n string name = \"\";\n int max_vote = 0;\n \n for(auto itr = umap.begin(); itr!=umap.end(); itr++){\n string key = itr->first;\n int val = itr->second;\n \n if(val>max_vote){\n max_vote = val;\n name = key;\n }\n else if(val == max_vote){\n if(key<name)\n name = key;\n }\n }\n \n vector<string> ans;\n ans.push_back(name);\n string temp = to_string(max_vote);\n ans.push_back(temp);\n \n return ans;\n }"
},
{
"code": null,
"e": 6687,
"s": 6685,
"text": "0"
},
{
"code": null,
"e": 6715,
"s": 6687,
"text": "jerinvarghese0274 weeks ago"
},
{
"code": null,
"e": 6739,
"s": 6715,
"text": "total time taken = 0.05"
},
{
"code": null,
"e": 7286,
"s": 6739,
"text": "def winner(self,arr,n): # Your code here # return the name of the winning candidate and the votes he recieved vote = {} for i in arr: if i in vote.keys(): vote[i] += 1 else: vote[i] = 1 maxVal = 0 for i in set(vote.values()): if i > maxVal: maxVal = i winners = [] for i,j in vote.items(): if j == maxVal: winners.append(i) minWord = min(winners) return minWord, maxVal"
},
{
"code": null,
"e": 7288,
"s": 7286,
"text": "0"
},
{
"code": null,
"e": 7306,
"s": 7288,
"text": "haulya4 weeks ago"
},
{
"code": null,
"e": 7510,
"s": 7306,
"text": " vector<string> winner(string arr[],int n) { // Your code here // Return the string containing the name and an integer // representing the number of votes the winning candidate got"
},
{
"code": null,
"e": 8116,
"s": 7510,
"text": " unordered_map<string, int>um; for(int i = 0; i < n; i++){ um[arr[i]]++; } string winner = arr[0]; int maxvotes = 0; for(auto it = um.begin(); it != um.end(); it++){ if(maxvotes < (*it).second){ winner = (*it).first; maxvotes = (*it).second; } else if(maxvotes == (*it).second && (winner > (*it).first)){ winner = (*it).first; } } vector<string> res; res.push_back(winner); res.push_back(to_string(maxvotes)); return res; }"
},
{
"code": null,
"e": 8119,
"s": 8116,
"text": "+1"
},
{
"code": null,
"e": 8150,
"s": 8119,
"text": "kartikeyashokgautam1 month ago"
},
{
"code": null,
"e": 8186,
"s": 8150,
"text": "Easy To understand JAVA Solution :-"
},
{
"code": null,
"e": 9145,
"s": 8186,
"text": " public static String[] winner(String arr[], int n) { String[] result = new String[2]; // storing candidates with their votes HashMap<String,Integer> hm = new HashMap<>(); for(String s : arr) { if(hm.containsKey(s)) { hm.put(s,hm.get(s)+1); } else { hm.put(s,1); } } // Finding who got the max votes int max=0; for(String s: arr) { if(hm.get(s)>max) { int temp = max; max=hm.get(s); } } // Since by default priority queue gives ans in ascending order // therefore here also pq will give ans in lexicographcally (alphabetically ascending order) PriorityQueue<String> pq = new PriorityQueue<>(); for(String s: hm.keySet()) { // Add only if candidate get maximum votes"
},
{
"code": null,
"e": 9240,
"s": 9145,
"text": " // so , only candidates with maximum votes will be added in \"lexicographically\" fashion "
},
{
"code": null,
"e": 9313,
"s": 9240,
"text": " // candidate with smallest lexicographical value will at peek of PQ."
},
{
"code": null,
"e": 9560,
"s": 9313,
"text": " if(hm.get(s)==max) { pq.add(s); } } result[0]=pq.peek(); result[1]=Integer.toString(max); //converting Integer value of vote to string as Return type is String return result; }"
},
{
"code": null,
"e": 9708,
"s": 9562,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 9744,
"s": 9708,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9754,
"s": 9744,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9764,
"s": 9754,
"text": "\nContest\n"
},
{
"code": null,
"e": 9827,
"s": 9764,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9975,
"s": 9827,
"text": "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."
},
{
"code": null,
"e": 10183,
"s": 9975,
"text": "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."
},
{
"code": null,
"e": 10289,
"s": 10183,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Python 3 - while Loop Statements
|
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
Here, a key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#!/usr/bin/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.
A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.
#!/usr/bin/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")
When the above code is executed, it produces the following result −
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number :"))
KeyboardInterrupt
The above example goes in an infinite loop and you need to use CTRL+C to exit the program.
Python supports having an else statement associated with a loop statement.
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise the else statement gets executed.
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
When the above code is executed, it produces the following result −
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
#!/usr/bin/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2471,
"s": 2340,
"text": "A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 2534,
"s": 2471,
"text": "The syntax of a while loop in Python programming language is −"
},
{
"code": null,
"e": 2569,
"s": 2534,
"text": "while expression:\n statement(s)\n"
},
{
"code": null,
"e": 2776,
"s": 2569,
"text": "Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true."
},
{
"code": null,
"e": 2877,
"s": 2776,
"text": "When the condition becomes false, program control passes to the line immediately following the loop."
},
{
"code": null,
"e": 3100,
"s": 2877,
"text": "In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements."
},
{
"code": null,
"e": 3320,
"s": 3100,
"text": "Here, a key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed."
},
{
"code": null,
"e": 3445,
"s": 3320,
"text": "#!/usr/bin/python3\n\ncount = 0\nwhile (count < 9):\n print ('The count is:', count)\n count = count + 1\n\nprint (\"Good bye!\")"
},
{
"code": null,
"e": 3513,
"s": 3445,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3668,
"s": 3513,
"text": "The count is: 0\nThe count is: 1\nThe count is: 2\nThe count is: 3\nThe count is: 4\nThe count is: 5\nThe count is: 6\nThe count is: 7\nThe count is: 8\nGood bye!\n"
},
{
"code": null,
"e": 3891,
"s": 3668,
"text": "The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1."
},
{
"code": null,
"e": 4160,
"s": 3891,
"text": "A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop."
},
{
"code": null,
"e": 4335,
"s": 4160,
"text": "An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required."
},
{
"code": null,
"e": 4510,
"s": 4335,
"text": "#!/usr/bin/python3\n\nvar = 1\nwhile var == 1 : # This constructs an infinite loop\n num = int(input(\"Enter a number :\"))\n print (\"You entered: \", num)\n\nprint (\"Good bye!\")"
},
{
"code": null,
"e": 4578,
"s": 4510,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4916,
"s": 4578,
"text": "Enter a number :20\nYou entered: 20\nEnter a number :29\nYou entered: 29\nEnter a number :3\nYou entered: 3\nEnter a number :11\nYou entered: 11\nEnter a number :22\nYou entered: 22\nEnter a number :Traceback (most recent call last):\n File \"examples\\test.py\", line 5, in \n num = int(input(\"Enter a number :\"))\nKeyboardInterrupt\n"
},
{
"code": null,
"e": 5007,
"s": 4916,
"text": "The above example goes in an infinite loop and you need to use CTRL+C to exit the program."
},
{
"code": null,
"e": 5082,
"s": 5007,
"text": "Python supports having an else statement associated with a loop statement."
},
{
"code": null,
"e": 5208,
"s": 5082,
"text": "If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list."
},
{
"code": null,
"e": 5334,
"s": 5208,
"text": "If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list."
},
{
"code": null,
"e": 5448,
"s": 5334,
"text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false."
},
{
"code": null,
"e": 5562,
"s": 5448,
"text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false."
},
{
"code": null,
"e": 5751,
"s": 5562,
"text": "The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise the else statement gets executed."
},
{
"code": null,
"e": 5902,
"s": 5751,
"text": "#!/usr/bin/python3\n\ncount = 0\nwhile count < 5:\n print (count, \" is less than 5\")\n count = count + 1\nelse:\n print (count, \" is not less than 5\")"
},
{
"code": null,
"e": 5970,
"s": 5902,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 6077,
"s": 5970,
"text": "0 is less than 5\n1 is less than 5\n2 is less than 5\n3 is less than 5\n4 is less than 5\n5 is not less than 5\n"
},
{
"code": null,
"e": 6226,
"s": 6077,
"text": "Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header."
},
{
"code": null,
"e": 6286,
"s": 6226,
"text": "Here is the syntax and example of a one-line while clause −"
},
{
"code": null,
"e": 6386,
"s": 6286,
"text": "#!/usr/bin/python3\n\nflag = 1\nwhile (flag): print ('Given flag is really true!')\nprint (\"Good bye!\")"
},
{
"code": null,
"e": 6474,
"s": 6386,
"text": "The above example goes into an infinite loop and you need to press CTRL+C keys to exit."
},
{
"code": null,
"e": 6511,
"s": 6474,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6527,
"s": 6511,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6560,
"s": 6527,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6579,
"s": 6560,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6614,
"s": 6579,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6636,
"s": 6614,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6670,
"s": 6636,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6698,
"s": 6670,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6733,
"s": 6698,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6747,
"s": 6733,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6780,
"s": 6747,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6797,
"s": 6780,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6804,
"s": 6797,
"text": " Print"
},
{
"code": null,
"e": 6815,
"s": 6804,
"text": " Add Notes"
}
] |
Transpose of Matrix | Practice | GeeksforGeeks
|
Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.
Example 1:
Input:
N = 4
mat[][] = {{1, 1, 1, 1},
{2, 2, 2, 2}
{3, 3, 3, 3}
{4, 4, 4, 4}}
Output:
{{1, 2, 3, 4},
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}}
Example 2:
Input:
N = 2
mat[][] = {{1, 2},
{-9, -2}}
Output:
{{1, -9},
{2, -2}}
Your Task:
You dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 100
-103 <= mat[i][j] <= 103
0
maneshram20Premium4 hours ago
class Solution
{
public:
//Function to find transpose of a matrix.
void transpose(vector<vector<int> >& matrix, int n)
{
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
swap(matrix[i][j],matrix[j][i]);
}
}
}
};
0
surajpatwa15062 days ago
// code here for(int i=0;i<matrix.length;i++){ for(int j=i+1;j<matrix[i].length;j++){ //swap (a[i][j],a[j][i]) int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } }
0
arnab_deb_214 days ago
void transpose(vector<vector<int> >& matrix, int n) { vector<vector<int> > v1; for(int i=0;i<n;i++){ vector<int> v2; for(int j=0;j<n;j++){ v2.push_back(matrix[j][i]); } v1.push_back(v2); } matrix.clear(); copy(v1.begin(),v1.end(),back_inserter(matrix)); }
0
sahillather0024 days ago
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++) swap(matrix[i][j],matrix[j][i]);
0
sahillather002
This comment was deleted.
0
tjanhvi5606 days ago
C++ Solution:
void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ swap(matrix[i][j], matrix[j][i]); } } }
0
ncclalit20202083252 weeks ago
void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(i!=j) { swap(matrix[i][j],matrix[j][i]); } } } }
0
shashikantshrivastava132 weeks ago
JAVA SOLUTION
//User function Template for Java
class Solution{ //Function to find transpose of a matrix. static void transpose(int matrix[][], int n) { // code here for(int i=0; i<n; i++){ for(int j=0; j<i; j++){ int temp = matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } }}
0
divakarkumar20002 weeks ago
// C++
void transpose(vector<vector<int> >& matrix, int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i<j)
{
swap(matrix[i][j],matrix[j][i]);
}
}
}
}
+1
vi5hnu2 weeks ago
//simple and efficient
for(int i=0;i<n;i++) for(int j=i;j<n;j++) swap(A[i][j],A[j][i]);
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.
|
[
{
"code": null,
"e": 391,
"s": 226,
"text": "Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.\n\nExample 1:"
},
{
"code": null,
"e": 575,
"s": 391,
"text": "Input:\nN = 4\nmat[][] = {{1, 1, 1, 1},\n {2, 2, 2, 2}\n {3, 3, 3, 3}\n {4, 4, 4, 4}}\nOutput: \n{{1, 2, 3, 4}, \n {1, 2, 3, 4} \n {1, 2, 3, 4}\n {1, 2, 3, 4}} \n"
},
{
"code": null,
"e": 586,
"s": 575,
"text": "Example 2:"
},
{
"code": null,
"e": 670,
"s": 586,
"text": "Input:\nN = 2\nmat[][] = {{1, 2},\n {-9, -2}}\nOutput:\n{{1, -9}, \n {2, -2}}\n\n"
},
{
"code": null,
"e": 1073,
"s": 670,
"text": "Your Task:\nYou dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose. \n\nExpected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N <= 100\n-103 <= mat[i][j] <= 103"
},
{
"code": null,
"e": 1075,
"s": 1073,
"text": "0"
},
{
"code": null,
"e": 1105,
"s": 1075,
"text": "maneshram20Premium4 hours ago"
},
{
"code": null,
"e": 1396,
"s": 1105,
"text": "class Solution\n{ \n public: \n //Function to find transpose of a matrix.\n void transpose(vector<vector<int> >& matrix, int n)\n { \n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n }\n};"
},
{
"code": null,
"e": 1398,
"s": 1396,
"text": "0"
},
{
"code": null,
"e": 1423,
"s": 1398,
"text": "surajpatwa15062 days ago"
},
{
"code": null,
"e": 1704,
"s": 1423,
"text": "// code here for(int i=0;i<matrix.length;i++){ for(int j=i+1;j<matrix[i].length;j++){ //swap (a[i][j],a[j][i]) int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } "
},
{
"code": null,
"e": 1706,
"s": 1704,
"text": "0"
},
{
"code": null,
"e": 1729,
"s": 1706,
"text": "arnab_deb_214 days ago"
},
{
"code": null,
"e": 2074,
"s": 1729,
"text": "void transpose(vector<vector<int> >& matrix, int n) { vector<vector<int> > v1; for(int i=0;i<n;i++){ vector<int> v2; for(int j=0;j<n;j++){ v2.push_back(matrix[j][i]); } v1.push_back(v2); } matrix.clear(); copy(v1.begin(),v1.end(),back_inserter(matrix)); }"
},
{
"code": null,
"e": 2076,
"s": 2074,
"text": "0"
},
{
"code": null,
"e": 2101,
"s": 2076,
"text": "sahillather0024 days ago"
},
{
"code": null,
"e": 2130,
"s": 2101,
"text": " for(int i=0;i<n;i++)"
},
{
"code": null,
"e": 2200,
"s": 2130,
"text": " for(int j=i+1;j<n;j++) swap(matrix[i][j],matrix[j][i]);"
},
{
"code": null,
"e": 2202,
"s": 2200,
"text": "0"
},
{
"code": null,
"e": 2217,
"s": 2202,
"text": "sahillather002"
},
{
"code": null,
"e": 2243,
"s": 2217,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2245,
"s": 2243,
"text": "0"
},
{
"code": null,
"e": 2266,
"s": 2245,
"text": "tjanhvi5606 days ago"
},
{
"code": null,
"e": 2280,
"s": 2266,
"text": "C++ Solution:"
},
{
"code": null,
"e": 2471,
"s": 2282,
"text": "void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ swap(matrix[i][j], matrix[j][i]); } } }"
},
{
"code": null,
"e": 2473,
"s": 2471,
"text": "0"
},
{
"code": null,
"e": 2503,
"s": 2473,
"text": "ncclalit20202083252 weeks ago"
},
{
"code": null,
"e": 2763,
"s": 2503,
"text": "void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(i!=j) { swap(matrix[i][j],matrix[j][i]); } } } }"
},
{
"code": null,
"e": 2765,
"s": 2763,
"text": "0"
},
{
"code": null,
"e": 2800,
"s": 2765,
"text": "shashikantshrivastava132 weeks ago"
},
{
"code": null,
"e": 2816,
"s": 2800,
"text": "JAVA SOLUTION "
},
{
"code": null,
"e": 2850,
"s": 2816,
"text": "//User function Template for Java"
},
{
"code": null,
"e": 3208,
"s": 2850,
"text": "class Solution{ //Function to find transpose of a matrix. static void transpose(int matrix[][], int n) { // code here for(int i=0; i<n; i++){ for(int j=0; j<i; j++){ int temp = matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } }}"
},
{
"code": null,
"e": 3210,
"s": 3208,
"text": "0"
},
{
"code": null,
"e": 3238,
"s": 3210,
"text": "divakarkumar20002 weeks ago"
},
{
"code": null,
"e": 3543,
"s": 3238,
"text": "// C++ \nvoid transpose(vector<vector<int> >& matrix, int n)\n { \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(i<j)\n {\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n }\n \n }"
},
{
"code": null,
"e": 3546,
"s": 3543,
"text": "+1"
},
{
"code": null,
"e": 3564,
"s": 3546,
"text": "vi5hnu2 weeks ago"
},
{
"code": null,
"e": 3587,
"s": 3564,
"text": "//simple and efficient"
},
{
"code": null,
"e": 3668,
"s": 3587,
"text": "for(int i=0;i<n;i++) for(int j=i;j<n;j++) swap(A[i][j],A[j][i]);"
},
{
"code": null,
"e": 3814,
"s": 3668,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3850,
"s": 3814,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3860,
"s": 3850,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3870,
"s": 3860,
"text": "\nContest\n"
},
{
"code": null,
"e": 3933,
"s": 3870,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4118,
"s": 3933,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4402,
"s": 4118,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 4548,
"s": 4402,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 4625,
"s": 4548,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 4666,
"s": 4625,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 4694,
"s": 4666,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 4765,
"s": 4694,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 4952,
"s": 4765,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to Get the Number of Elements in a Python List?
|
01 Jul, 2022
In this article, we will discuss how do we get the number of elements in a list in Python.
Input: [1,2,3,4,5]
Output:No of elements in the list are 5
Input: [1.2 ,4.5, 2.2]
Output:No of elements in the list are 3
Input: [“apple”, “banana”, “mangoe”]
Output:No of elements in the list are 3
Before getting the Number of Elements in the Python List we have to create an empty List. After creating an empty list we have to insert the items or elements into the list.
There are three methods to get the number of elements in the list i.e,
Using Len( ) function
Using for loop
Using length_hint
We can use the len function i.e len( ) to return the number of elements present in the list
Python3
# Returning the number of elements using# len() function in python list = [] # declare empty list# adding items or elements to the listlist.append(1)list.append(2)list.append(3)list.append(4) # printing the listprint(list) # using the len() which return the number# of elements in the listprint("No of elements in list are")print(len(list))
[1, 2, 3, 4]
No of elements in list are
4
We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop in python gets terminated.
Python3
# Python Program for returning the number# of elements in the list using for loop list = [] # declaring empty list # inserting elements in the list using# append methodlist.append(1)list.append(2)list.append(3)list.append(4) # declaring count variable as integer to keep# track of the number of elements in for loopcount = 0 # for loop for iterating through each element# in the listfor i in list: # increments count variable for each # iteration count = count+1 # prints the count variable i.e the total number# of elements in the listprint(list) print("No of elements in the list are")print(count)
[1, 2, 3, 4]
No of elements in the list are
4
Python3
from operator import length_hint l = [1, 2, 3, 4]length_hint(l)
Output:
4
Hence, in this way, we can return the number of elements of a list in python using for loop.
simmytarika5
surindertarika1234
surajkumarguptaintern
Picked
Python list-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 ?
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "In this article, we will discuss how do we get the number of elements in a list in Python."
},
{
"code": null,
"e": 162,
"s": 143,
"text": "Input: [1,2,3,4,5]"
},
{
"code": null,
"e": 202,
"s": 162,
"text": "Output:No of elements in the list are 5"
},
{
"code": null,
"e": 227,
"s": 202,
"text": "Input: [1.2 ,4.5, 2.2] "
},
{
"code": null,
"e": 268,
"s": 227,
"text": "Output:No of elements in the list are 3 "
},
{
"code": null,
"e": 305,
"s": 268,
"text": "Input: [“apple”, “banana”, “mangoe”]"
},
{
"code": null,
"e": 345,
"s": 305,
"text": "Output:No of elements in the list are 3"
},
{
"code": null,
"e": 520,
"s": 345,
"text": "Before getting the Number of Elements in the Python List we have to create an empty List. After creating an empty list we have to insert the items or elements into the list. "
},
{
"code": null,
"e": 591,
"s": 520,
"text": "There are three methods to get the number of elements in the list i.e,"
},
{
"code": null,
"e": 613,
"s": 591,
"text": "Using Len( ) function"
},
{
"code": null,
"e": 629,
"s": 613,
"text": "Using for loop "
},
{
"code": null,
"e": 647,
"s": 629,
"text": "Using length_hint"
},
{
"code": null,
"e": 739,
"s": 647,
"text": "We can use the len function i.e len( ) to return the number of elements present in the list"
},
{
"code": null,
"e": 747,
"s": 739,
"text": "Python3"
},
{
"code": "# Returning the number of elements using# len() function in python list = [] # declare empty list# adding items or elements to the listlist.append(1)list.append(2)list.append(3)list.append(4) # printing the listprint(list) # using the len() which return the number# of elements in the listprint(\"No of elements in list are\")print(len(list))",
"e": 1089,
"s": 747,
"text": null
},
{
"code": null,
"e": 1131,
"s": 1089,
"text": "[1, 2, 3, 4]\nNo of elements in list are\n4"
},
{
"code": null,
"e": 1291,
"s": 1131,
"text": "We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop in python gets terminated. "
},
{
"code": null,
"e": 1299,
"s": 1291,
"text": "Python3"
},
{
"code": "# Python Program for returning the number# of elements in the list using for loop list = [] # declaring empty list # inserting elements in the list using# append methodlist.append(1)list.append(2)list.append(3)list.append(4) # declaring count variable as integer to keep# track of the number of elements in for loopcount = 0 # for loop for iterating through each element# in the listfor i in list: # increments count variable for each # iteration count = count+1 # prints the count variable i.e the total number# of elements in the listprint(list) print(\"No of elements in the list are\")print(count)",
"e": 1910,
"s": 1299,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1910,
"text": "[1, 2, 3, 4]\nNo of elements in the list are\n4"
},
{
"code": null,
"e": 1964,
"s": 1956,
"text": "Python3"
},
{
"code": "from operator import length_hint l = [1, 2, 3, 4]length_hint(l)",
"e": 2028,
"s": 1964,
"text": null
},
{
"code": null,
"e": 2036,
"s": 2028,
"text": "Output:"
},
{
"code": null,
"e": 2038,
"s": 2036,
"text": "4"
},
{
"code": null,
"e": 2131,
"s": 2038,
"text": "Hence, in this way, we can return the number of elements of a list in python using for loop."
},
{
"code": null,
"e": 2144,
"s": 2131,
"text": "simmytarika5"
},
{
"code": null,
"e": 2163,
"s": 2144,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2185,
"s": 2163,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 2192,
"s": 2185,
"text": "Picked"
},
{
"code": null,
"e": 2213,
"s": 2192,
"text": "Python list-programs"
},
{
"code": null,
"e": 2220,
"s": 2213,
"text": "Python"
},
{
"code": null,
"e": 2236,
"s": 2220,
"text": "Python Programs"
},
{
"code": null,
"e": 2334,
"s": 2236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2366,
"s": 2334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2393,
"s": 2366,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2414,
"s": 2393,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2437,
"s": 2414,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2493,
"s": 2437,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2515,
"s": 2493,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2554,
"s": 2515,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2592,
"s": 2554,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2641,
"s": 2592,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Python | Pandas Series.str.findall()
|
28 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.findall() method is also used to find substrings or separators in each string in a series. But it is different from str.find() method. Instead of returning the index, it returns list with substrings and size of list is number of times it occurred.
Syntax: Series.str.findall(pat, flags=0)
Parameters:pat: Substring to be searched forflags: Regex flags that can be passed (A, S, L, M, I, X), default is 0 which means None. For this regex module (re) has to be imported too.
Return Type: Series of list(strings).
To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Searching character in string
In this example, the name column is searched for ‘r’ using str.findall() method and output is stored in new column. Before doing any operations, null rows are dropped using .dropna() to avoid errors.
# importing pandas module import pandas as pd # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errors data.dropna(inplace = True) # string to be searched forsearch ='r' # returning values and creating columndata["Findall(name)"]= data["Name"].str.findall(search) # displaydata.head(10)
Output:As shown in the output image, it can be compared that the number of ‘e’ returned is equal to number of time it occurred in string. Example #2: Searching character and passing IGNORECASE flag
In this example, the Name column is searched for ‘a’ and the IGNORECASE flag is passed. For that re module has to be imported too. The returned series from str.findall() method is stored in a New column.
# importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errors data.dropna(inplace = True) # string to be searched forsearch ='a' # returning values and creating columndata["Findall(name)"]= data["Name"].str.findall(search, flags = re.I) # displaydata.head(10)
Output:As shown in the output image, it can be seen in the first row itself that both ‘A’ and ‘a’ were returned since IGNORECASE flag(re.I) was passed.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 501,
"s": 242,
"text": "Pandas str.findall() method is also used to find substrings or separators in each string in a series. But it is different from str.find() method. Instead of returning the index, it returns list with substrings and size of list is number of times it occurred."
},
{
"code": null,
"e": 542,
"s": 501,
"text": "Syntax: Series.str.findall(pat, flags=0)"
},
{
"code": null,
"e": 726,
"s": 542,
"text": "Parameters:pat: Substring to be searched forflags: Regex flags that can be passed (A, S, L, M, I, X), default is 0 which means None. For this regex module (re) has to be imported too."
},
{
"code": null,
"e": 764,
"s": 726,
"text": "Return Type: Series of list(strings)."
},
{
"code": null,
"e": 956,
"s": 764,
"text": "To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 998,
"s": 956,
"text": "Example #1: Searching character in string"
},
{
"code": null,
"e": 1198,
"s": 998,
"text": "In this example, the name column is searched for ‘r’ using str.findall() method and output is stored in new column. Before doing any operations, null rows are dropped using .dropna() to avoid errors."
},
{
"code": "# importing pandas module import pandas as pd # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errors data.dropna(inplace = True) # string to be searched forsearch ='r' # returning values and creating columndata[\"Findall(name)\"]= data[\"Name\"].str.findall(search) # displaydata.head(10)",
"e": 1580,
"s": 1198,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1580,
"text": "Output:As shown in the output image, it can be compared that the number of ‘e’ returned is equal to number of time it occurred in string. Example #2: Searching character and passing IGNORECASE flag"
},
{
"code": null,
"e": 1982,
"s": 1778,
"text": "In this example, the Name column is searched for ‘a’ and the IGNORECASE flag is passed. For that re module has to be imported too. The returned series from str.findall() method is stored in a New column."
},
{
"code": "# importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errors data.dropna(inplace = True) # string to be searched forsearch ='a' # returning values and creating columndata[\"Findall(name)\"]= data[\"Name\"].str.findall(search, flags = re.I) # displaydata.head(10)",
"e": 2413,
"s": 1982,
"text": null
},
{
"code": null,
"e": 2565,
"s": 2413,
"text": "Output:As shown in the output image, it can be seen in the first row itself that both ‘A’ and ‘a’ were returned since IGNORECASE flag(re.I) was passed."
},
{
"code": null,
"e": 2586,
"s": 2565,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2615,
"s": 2586,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2629,
"s": 2615,
"text": "Python-pandas"
},
{
"code": null,
"e": 2654,
"s": 2629,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2661,
"s": 2654,
"text": "Python"
},
{
"code": null,
"e": 2759,
"s": 2661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2777,
"s": 2759,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2819,
"s": 2777,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2841,
"s": 2819,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2867,
"s": 2841,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2899,
"s": 2867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2928,
"s": 2899,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2955,
"s": 2928,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2991,
"s": 2955,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3022,
"s": 2991,
"text": "Python | os.path.join() method"
}
] |
Python – Call function from another function
|
15 Dec, 2021
Prerequisite: Functions in PythonIn Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with help of multiple examples.
Calling and Called Function ? The Function which calls another Function is called Calling Function and function which is called by another Function is call Called Function.
How does Function execution work? A stack data structure is used during the execution of the function calls. Whenever a function is invoked then the calling function is pushed into the stack and called function is executed. When the called function completes its execution and returns then the calling function is popped from the stack and executed. Calling Function execution will be completed only when called Function is execution completes.
In the below figure. The function call is made from the Main function to Function1, Now the state of the Main function is stored in Stack, and execution of the Main function is continued when the Function 1 returns. The Fucntion1 Calls Function2 now the State of the Function1 is stored stack and execution of Function 1 will be continued when Function 2 returns.
Consider the below Example of the function call. The Function SumOfSquares function calls the Function Square which returns the square of the number.
Python3
# Python code to demonstrate calling the# function from another function def Square(X): # computes the Square of the given number # and return to the caller function return (X * X) def SumofSquares(Array, n): # Initialize variable Sum to 0. It stores the # Total sum of squares of the array of elements Sum = 0 for i in range(n): # Square of Array[i] element is stored in SquaredValue SquaredValue = Square(Array[i]) # Cumulative sum is stored in Sum variable Sum += SquaredValue return Sum # Driver FunctionArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]n = len(Array) # Return value from the function# Sum of Squares is stored in TotalTotal = SumofSquares(Array, n)print("Sum of the Square of List of Numbers:", Total)
Output :
Sum of the Square of List of Numbers: 385
Calling Function From another Function within Same class –In the below example, the class method Function1 calls method Function2 from the class.
Python3
'''Call a function from within another functionin the same class in Python''' class Main: # constructor of Main class def __init__(self): # Initialization of the Strings self.String1 ="Hello" self.String2 ="World" def Function1(self): # calling Function2 Method self.Function2() print("Function1 : ", self.String2) return def Function2(self): print("Function2 : ", self.String1) return # Instance of Class MainObject = Main() # Calling Function1Object.Function1()
Output :
Function2 : Hello
Function1 : World
Calling parent class Function from Child class Function –Consider the below example the child class method invokes the parent class method. The child class inherits the attributes from the parent class.
Python3
# Python code to demonstrate calling parent class# method from the child class method class Parent: # constructor of Parent class def __init__(self): # Initialization of the Strings self.String1 ="Hello" self.String2 ="World" def Function2(self): print("Function2 : ", self.String1) return # Child class is inheriting from Parent classclass Child(Parent): def Function1(self): # calling Function2 Method in parent class self.Function2() print("Function1 : ", self.String2) return ### Instance of Parent classObject1 = Parent() ### Instance of Child classObject2 = Child() # Calling Function1 using Child class instanceObject2.Function1()
Output :
Function2 : Hello
Function1 : World
surinderdawra388
Picked
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 371,
"s": 52,
"text": "Prerequisite: Functions in PythonIn Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with help of multiple examples. "
},
{
"code": null,
"e": 544,
"s": 371,
"text": "Calling and Called Function ? The Function which calls another Function is called Calling Function and function which is called by another Function is call Called Function."
},
{
"code": null,
"e": 989,
"s": 544,
"text": "How does Function execution work? A stack data structure is used during the execution of the function calls. Whenever a function is invoked then the calling function is pushed into the stack and called function is executed. When the called function completes its execution and returns then the calling function is popped from the stack and executed. Calling Function execution will be completed only when called Function is execution completes."
},
{
"code": null,
"e": 1354,
"s": 989,
"text": "In the below figure. The function call is made from the Main function to Function1, Now the state of the Main function is stored in Stack, and execution of the Main function is continued when the Function 1 returns. The Fucntion1 Calls Function2 now the State of the Function1 is stored stack and execution of Function 1 will be continued when Function 2 returns. "
},
{
"code": null,
"e": 1505,
"s": 1354,
"text": "Consider the below Example of the function call. The Function SumOfSquares function calls the Function Square which returns the square of the number. "
},
{
"code": null,
"e": 1513,
"s": 1505,
"text": "Python3"
},
{
"code": "# Python code to demonstrate calling the# function from another function def Square(X): # computes the Square of the given number # and return to the caller function return (X * X) def SumofSquares(Array, n): # Initialize variable Sum to 0. It stores the # Total sum of squares of the array of elements Sum = 0 for i in range(n): # Square of Array[i] element is stored in SquaredValue SquaredValue = Square(Array[i]) # Cumulative sum is stored in Sum variable Sum += SquaredValue return Sum # Driver FunctionArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]n = len(Array) # Return value from the function# Sum of Squares is stored in TotalTotal = SumofSquares(Array, n)print(\"Sum of the Square of List of Numbers:\", Total)",
"e": 2281,
"s": 1513,
"text": null
},
{
"code": null,
"e": 2291,
"s": 2281,
"text": "Output : "
},
{
"code": null,
"e": 2334,
"s": 2291,
"text": "Sum of the Square of List of Numbers: 385 "
},
{
"code": null,
"e": 2480,
"s": 2334,
"text": "Calling Function From another Function within Same class –In the below example, the class method Function1 calls method Function2 from the class."
},
{
"code": null,
"e": 2488,
"s": 2480,
"text": "Python3"
},
{
"code": "'''Call a function from within another functionin the same class in Python''' class Main: # constructor of Main class def __init__(self): # Initialization of the Strings self.String1 =\"Hello\" self.String2 =\"World\" def Function1(self): # calling Function2 Method self.Function2() print(\"Function1 : \", self.String2) return def Function2(self): print(\"Function2 : \", self.String1) return # Instance of Class MainObject = Main() # Calling Function1Object.Function1()",
"e": 3030,
"s": 2488,
"text": null
},
{
"code": null,
"e": 3040,
"s": 3030,
"text": "Output : "
},
{
"code": null,
"e": 3078,
"s": 3040,
"text": "Function2 : Hello\nFunction1 : World"
},
{
"code": null,
"e": 3281,
"s": 3078,
"text": "Calling parent class Function from Child class Function –Consider the below example the child class method invokes the parent class method. The child class inherits the attributes from the parent class."
},
{
"code": null,
"e": 3289,
"s": 3281,
"text": "Python3"
},
{
"code": "# Python code to demonstrate calling parent class# method from the child class method class Parent: # constructor of Parent class def __init__(self): # Initialization of the Strings self.String1 =\"Hello\" self.String2 =\"World\" def Function2(self): print(\"Function2 : \", self.String1) return # Child class is inheriting from Parent classclass Child(Parent): def Function1(self): # calling Function2 Method in parent class self.Function2() print(\"Function1 : \", self.String2) return ### Instance of Parent classObject1 = Parent() ### Instance of Child classObject2 = Child() # Calling Function1 using Child class instanceObject2.Function1()",
"e": 4007,
"s": 3289,
"text": null
},
{
"code": null,
"e": 4017,
"s": 4007,
"text": "Output : "
},
{
"code": null,
"e": 4055,
"s": 4017,
"text": "Function2 : Hello\nFunction1 : World"
},
{
"code": null,
"e": 4074,
"s": 4057,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4081,
"s": 4074,
"text": "Picked"
},
{
"code": null,
"e": 4098,
"s": 4081,
"text": "Python-Functions"
},
{
"code": null,
"e": 4105,
"s": 4098,
"text": "Python"
},
{
"code": null,
"e": 4203,
"s": 4105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4221,
"s": 4203,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4263,
"s": 4221,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4285,
"s": 4263,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4320,
"s": 4285,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4346,
"s": 4320,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4378,
"s": 4346,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4405,
"s": 4378,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4426,
"s": 4405,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4449,
"s": 4426,
"text": "Introduction To PYTHON"
}
] |
Text Highlighter in Android
|
23 Feb, 2021
Text Highlighter is one of the popular functions in most apps. You can get to see this function in Notes keeping application or in any educational application. The main function of this feature is that it highlights the searched word in any document. In this article, we are going to see how to implement Text Highlighter in our Android App. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
The main feature of using this Text Highlighter is that it highlights the searched word in your app.
It tells you how much time the searched word is repeated and it gets highlighted.
It is used for keyword research in an application.
Attributes
Description
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency of Text Highlighter library in build.gradle file
Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.
implementation ‘com.xeoh.android:text-highlighter:1.0.3’
Now click on Sync now it will sync your all files in build.gradle().
Step 3: Create a new Text Highlighter in your activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Scroll view for scrolling--> <ScrollView android:layout_width="match_parent" android:layout_height="300dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"> <!--Linear layout to arrange elements one below another--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="30dp"> <!--TextView to display text--> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device launched in September 2008. It is free and open source software; its source code is known as Android Open Source Project (AOSP), which is primarily licensed under the Apache License. However most Android devices ship with additional proprietary software pre-installed,[10] most notably Google Mobile Services (GMS)[11] which includes core apps such as Google Chrome, the digital distribution platform Google Play and associated Google Play Services development platform. About 70 percent of Android smartphones run Google's ecosystem;[12] competing Android ecosystems and forks include Fire OS (developed by Amazon) or LineageOS. However the 'Android' name and logo are trademarks of Google which impose standards to restrict 'uncertified' devices outside their ecosystem to use Android branding.[13][14] The source code has been used to develop variants of Android on a range of other electronics, such as game consoles, digital cameras, portable media players, PCs and others, each with a specialized user interface. Some well known derivatives include Android TV for televisions and Wear OS for wearables, both developed by Google. Software packages on Android, which use the APK format, are generally distributed through proprietary application stores like Google Play Store, Samsung Galaxy Store, and Huawei AppGallery, or open source platforms like Aptoide or F-Droid. Android has been the best-selling OS worldwide on smartphones since 2011 and on tablets since 2013. As of May 2017, it has over two billion monthly active users, the largest installed base of any operating system, and as of August 2020, the Google Play Store features over 3 million apps.[15] The current stable version is Android 11, released on September 8, 2020. " /> </LinearLayout> </ScrollView> <!--Button to search text--> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/search" android:layout_centerInParent="true" android:layout_margin="20dp" android:padding="10dp" android:text="Search" /> <!--EditText to give text input--> <EditText android:id="@+id/search" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_margin="10dp" android:ems="10" android:hint="Search" android:inputType="text" android:text="" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.xeoh.android.texthighlighter.TextHighlighter; public class MainActivity extends AppCompatActivity { // Variable for button, // edit text and text view given Button button; EditText editText; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Accepted through Id's button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.search); textView = (TextView) findViewById(R.id.textView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new TextHighlighter() .setBackgroundColor(Color.parseColor("#FFFF00")) .setForegroundColor(Color.GREEN) .addTarget(textView) .highlight(editText.getText().toString(), TextHighlighter.BASE_MATCHER); } }); }}
Step 5: Working with the AndroidManifest.xml file
Add the following line to the AndroidManifest.xml file inside the <activity> tag.
android:windowSoftInputMode=”adjustNothing|stateHidden”>
Below is the complete code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.emoji_slider"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Emoji_slider"> <activity android:name=".MainActivity" android:windowSoftInputMode="adjustNothing|stateHidden"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Android-Animation
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 535,
"s": 28,
"text": "Text Highlighter is one of the popular functions in most apps. You can get to see this function in Notes keeping application or in any educational application. The main function of this feature is that it highlights the searched word in any document. In this article, we are going to see how to implement Text Highlighter in our Android App. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 636,
"s": 535,
"text": "The main feature of using this Text Highlighter is that it highlights the searched word in your app."
},
{
"code": null,
"e": 718,
"s": 636,
"text": "It tells you how much time the searched word is repeated and it gets highlighted."
},
{
"code": null,
"e": 769,
"s": 718,
"text": "It is used for keyword research in an application."
},
{
"code": null,
"e": 780,
"s": 769,
"text": "Attributes"
},
{
"code": null,
"e": 792,
"s": 780,
"text": "Description"
},
{
"code": null,
"e": 821,
"s": 792,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 983,
"s": 821,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1055,
"s": 983,
"text": "Step 2: Add dependency of Text Highlighter library in build.gradle file"
},
{
"code": null,
"e": 1192,
"s": 1055,
"text": "Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section."
},
{
"code": null,
"e": 1249,
"s": 1192,
"text": "implementation ‘com.xeoh.android:text-highlighter:1.0.3’"
},
{
"code": null,
"e": 1318,
"s": 1249,
"text": "Now click on Sync now it will sync your all files in build.gradle()."
},
{
"code": null,
"e": 1387,
"s": 1318,
"text": "Step 3: Create a new Text Highlighter in your activity_main.xml file"
},
{
"code": null,
"e": 1503,
"s": 1387,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1507,
"s": 1503,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Scroll view for scrolling--> <ScrollView android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\"> <!--Linear layout to arrange elements one below another--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"30dp\"> <!--TextView to display text--> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:text=\"Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device launched in September 2008. It is free and open source software; its source code is known as Android Open Source Project (AOSP), which is primarily licensed under the Apache License. However most Android devices ship with additional proprietary software pre-installed,[10] most notably Google Mobile Services (GMS)[11] which includes core apps such as Google Chrome, the digital distribution platform Google Play and associated Google Play Services development platform. About 70 percent of Android smartphones run Google's ecosystem;[12] competing Android ecosystems and forks include Fire OS (developed by Amazon) or LineageOS. However the 'Android' name and logo are trademarks of Google which impose standards to restrict 'uncertified' devices outside their ecosystem to use Android branding.[13][14] The source code has been used to develop variants of Android on a range of other electronics, such as game consoles, digital cameras, portable media players, PCs and others, each with a specialized user interface. Some well known derivatives include Android TV for televisions and Wear OS for wearables, both developed by Google. Software packages on Android, which use the APK format, are generally distributed through proprietary application stores like Google Play Store, Samsung Galaxy Store, and Huawei AppGallery, or open source platforms like Aptoide or F-Droid. Android has been the best-selling OS worldwide on smartphones since 2011 and on tablets since 2013. As of May 2017, it has over two billion monthly active users, the largest installed base of any operating system, and as of August 2020, the Google Play Store features over 3 million apps.[15] The current stable version is Android 11, released on September 8, 2020. \" /> </LinearLayout> </ScrollView> <!--Button to search text--> <Button android:id=\"@+id/button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/search\" android:layout_centerInParent=\"true\" android:layout_margin=\"20dp\" android:padding=\"10dp\" android:text=\"Search\" /> <!--EditText to give text input--> <EditText android:id=\"@+id/search\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"10dp\" android:ems=\"10\" android:hint=\"Search\" android:inputType=\"text\" android:text=\"\" /> </RelativeLayout>",
"e": 5648,
"s": 1507,
"text": null
},
{
"code": null,
"e": 5696,
"s": 5648,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 5886,
"s": 5696,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5891,
"s": 5886,
"text": "Java"
},
{
"code": "import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.xeoh.android.texthighlighter.TextHighlighter; public class MainActivity extends AppCompatActivity { // Variable for button, // edit text and text view given Button button; EditText editText; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Accepted through Id's button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.search); textView = (TextView) findViewById(R.id.textView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new TextHighlighter() .setBackgroundColor(Color.parseColor(\"#FFFF00\")) .setForegroundColor(Color.GREEN) .addTarget(textView) .highlight(editText.getText().toString(), TextHighlighter.BASE_MATCHER); } }); }}",
"e": 7190,
"s": 5891,
"text": null
},
{
"code": null,
"e": 7240,
"s": 7190,
"text": "Step 5: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 7322,
"s": 7240,
"text": "Add the following line to the AndroidManifest.xml file inside the <activity> tag."
},
{
"code": null,
"e": 7379,
"s": 7322,
"text": "android:windowSoftInputMode=”adjustNothing|stateHidden”>"
},
{
"code": null,
"e": 7440,
"s": 7379,
"text": "Below is the complete code for the AndroidManifest.xml file."
},
{
"code": null,
"e": 7444,
"s": 7440,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.emoji_slider\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.Emoji_slider\"> <activity android:name=\".MainActivity\" android:windowSoftInputMode=\"adjustNothing|stateHidden\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 8258,
"s": 7444,
"text": null
},
{
"code": null,
"e": 8276,
"s": 8258,
"text": "Android-Animation"
},
{
"code": null,
"e": 8300,
"s": 8276,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8308,
"s": 8300,
"text": "Android"
},
{
"code": null,
"e": 8313,
"s": 8308,
"text": "Java"
},
{
"code": null,
"e": 8332,
"s": 8313,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8337,
"s": 8332,
"text": "Java"
},
{
"code": null,
"e": 8345,
"s": 8337,
"text": "Android"
},
{
"code": null,
"e": 8443,
"s": 8345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8512,
"s": 8443,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8544,
"s": 8512,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8593,
"s": 8544,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8632,
"s": 8593,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8674,
"s": 8632,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 8689,
"s": 8674,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8733,
"s": 8689,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 8769,
"s": 8733,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 8820,
"s": 8769,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to Brute Force ZIP File Passwords in Python?
|
24 Feb, 2021
In this article, we will see a Python program that will crack the zip file’s password using the brute force method.
The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn’t want to give its access to every individual. Hence, the zip file is protected with a password. If the password is common then it’s easily crack-able. Here, we’ll use the brute force method to crack the zip file’s password.
A brute force method is a method where a set of predefined values are used to crack a password until successful. This is basically a “hit and try” method. This method might take a long time if the set of values are high, but its success rate is high. The more the number of values, the greater the chances of cracking passwords. Here we’ll be using “rockyou” text file of size 133 MB with over 14 million sets of passwords to try. Download the text file here.
Approach:
First, import the zipfile module.
Initialize the ZipFile object which helps in extracting the contents of the zip file.
Count the number of words present in “rockyou.txt” file and display it on the terminal.
Call the “crack_password” function which returns true if a password is found else returns false. Pass the name of the text file and the ZipFile object as parameters.
idx variable is used to keep track of line numbers.
Open the text file “rockyou.txt” in “rb” mode in order to handle file contents in binary form. This is because the file contains some special symbols which can’t be handled if the file is opened in “r” mode and will generate UnicodeDecodeError.
After opening the file, extract the line from the file and then split the word from it.
In the try block, extract the contents of the zip file by giving the password to pwd field of extractall method. extractall() method will extract all the contents of the zip file to the current working directory. The above program extracts a zip file named “gfg.zip” in the same directory as this python script.
If the password is incorrect, an exception will be generated. In except block, continue the loop to check other words in the file.
If the password is found return true else at last return false and display the desired message.
Below is the full implementation:
Python3
import zipfile def crack_password(password_list, obj): # tracking line no. at which password is found idx = 0 # open file in read byte mode only as "rockyou.txt" # file contains some special characters and hence # UnicodeDecodeError will be generated with open(password_list, 'rb') as file: for line in file: for word in line.split(): try: idx += 1 obj.extractall(pwd=word) print("Password found at line", idx) print("Password is", word.decode()) return True except: continue return False password_list = "rockyou.txt" zip_file = "gfg.zip" # ZipFile object initialisedobj = zipfile.ZipFile(zip_file) # count of number of words present in filecnt = len(list(open(password_list, "rb"))) print("There are total", cnt, "number of passwords to test") if crack_password(password_list, obj) == False: print("Password not found in this file")
Output:
Picked
python-utility
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
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 168,
"s": 52,
"text": "In this article, we will see a Python program that will crack the zip file’s password using the brute force method."
},
{
"code": null,
"e": 554,
"s": 168,
"text": "The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn’t want to give its access to every individual. Hence, the zip file is protected with a password. If the password is common then it’s easily crack-able. Here, we’ll use the brute force method to crack the zip file’s password."
},
{
"code": null,
"e": 1014,
"s": 554,
"text": "A brute force method is a method where a set of predefined values are used to crack a password until successful. This is basically a “hit and try” method. This method might take a long time if the set of values are high, but its success rate is high. The more the number of values, the greater the chances of cracking passwords. Here we’ll be using “rockyou” text file of size 133 MB with over 14 million sets of passwords to try. Download the text file here."
},
{
"code": null,
"e": 1024,
"s": 1014,
"text": "Approach:"
},
{
"code": null,
"e": 1058,
"s": 1024,
"text": "First, import the zipfile module."
},
{
"code": null,
"e": 1144,
"s": 1058,
"text": "Initialize the ZipFile object which helps in extracting the contents of the zip file."
},
{
"code": null,
"e": 1232,
"s": 1144,
"text": "Count the number of words present in “rockyou.txt” file and display it on the terminal."
},
{
"code": null,
"e": 1398,
"s": 1232,
"text": "Call the “crack_password” function which returns true if a password is found else returns false. Pass the name of the text file and the ZipFile object as parameters."
},
{
"code": null,
"e": 1450,
"s": 1398,
"text": "idx variable is used to keep track of line numbers."
},
{
"code": null,
"e": 1695,
"s": 1450,
"text": "Open the text file “rockyou.txt” in “rb” mode in order to handle file contents in binary form. This is because the file contains some special symbols which can’t be handled if the file is opened in “r” mode and will generate UnicodeDecodeError."
},
{
"code": null,
"e": 1783,
"s": 1695,
"text": "After opening the file, extract the line from the file and then split the word from it."
},
{
"code": null,
"e": 2095,
"s": 1783,
"text": "In the try block, extract the contents of the zip file by giving the password to pwd field of extractall method. extractall() method will extract all the contents of the zip file to the current working directory. The above program extracts a zip file named “gfg.zip” in the same directory as this python script."
},
{
"code": null,
"e": 2226,
"s": 2095,
"text": "If the password is incorrect, an exception will be generated. In except block, continue the loop to check other words in the file."
},
{
"code": null,
"e": 2322,
"s": 2226,
"text": "If the password is found return true else at last return false and display the desired message."
},
{
"code": null,
"e": 2356,
"s": 2322,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 2364,
"s": 2356,
"text": "Python3"
},
{
"code": "import zipfile def crack_password(password_list, obj): # tracking line no. at which password is found idx = 0 # open file in read byte mode only as \"rockyou.txt\" # file contains some special characters and hence # UnicodeDecodeError will be generated with open(password_list, 'rb') as file: for line in file: for word in line.split(): try: idx += 1 obj.extractall(pwd=word) print(\"Password found at line\", idx) print(\"Password is\", word.decode()) return True except: continue return False password_list = \"rockyou.txt\" zip_file = \"gfg.zip\" # ZipFile object initialisedobj = zipfile.ZipFile(zip_file) # count of number of words present in filecnt = len(list(open(password_list, \"rb\"))) print(\"There are total\", cnt, \"number of passwords to test\") if crack_password(password_list, obj) == False: print(\"Password not found in this file\")",
"e": 3403,
"s": 2364,
"text": null
},
{
"code": null,
"e": 3411,
"s": 3403,
"text": "Output:"
},
{
"code": null,
"e": 3418,
"s": 3411,
"text": "Picked"
},
{
"code": null,
"e": 3433,
"s": 3418,
"text": "python-utility"
},
{
"code": null,
"e": 3440,
"s": 3433,
"text": "Python"
},
{
"code": null,
"e": 3538,
"s": 3440,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3570,
"s": 3538,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3597,
"s": 3570,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3618,
"s": 3597,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3641,
"s": 3618,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3697,
"s": 3641,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3728,
"s": 3697,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3770,
"s": 3728,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3812,
"s": 3770,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3851,
"s": 3812,
"text": "Python | Get unique values from a list"
}
] |
How to Implement Loading AlertDialog in Android?
|
03 Sep, 2021
AlertDialog is defined as the small window that shows a particular message to the user when the user performs or commits certain action. In this article, we are going to build a simple android application in which we learn how to implement a Loading AlertDialog that means whenever the user clicks on the submit button it shows a dialog with a loading ProgressBar and a message please wait and after a certain time it gets dismissed and shows a message done. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
In this step, we are going to design our activity_main.xml. These are the following things that we will add to our activity_main.xml
An ImageView with the image of the GEEKSOFGEEKS symbol.
Two EditTexts one for username and one for the password field
A Button with the text SUBMIT.
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="276dp" android:text="SUBMIT" android:textColor="#0f9d58" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.504" app:layout_constraintStart_toStartOf="parent" /> <EditText android:id="@+id/editTextTextPersonName2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="52dp" android:ems="10" android:hint="Password" android:inputType="textPassword" android:text="" android:textAlignment="center" android:textColorHint="#0f9d58" android:textSize="20dp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName3" /> <EditText android:id="@+id/editTextTextPersonName3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="180dp" android:ems="10" android:hint="Username" android:inputType="textPersonName" android:text="" android:textAlignment="center" android:textColorHint="#0f9d58" android:textSize="20dp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imageView2" android:layout_width="138dp" android:layout_height="123dp" android:layout_marginTop="10dp" android:layout_marginBottom="40dp" app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName3" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="1.0" app:srcCompat="@drawable/gfg" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create a new layout file
In this step, we are going to create a new layout file for designing our dialog. Now create a new layout file to design the dialog that includes a loading ProgressBar and a text field with a text please wait. To create a new layout file please follow the following steps: Right-click on layout > new > Layout Resource file and name it loading and add the following code in it.
Below is the code for the loading.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="50dp"> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyle" android:layout_width="80dp" android:layout_height="66dp" android:layout_marginBottom="24dp" app:layout_constraintBottom_toTopOf="@+id/message" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/message" android:layout_width="150dp" android:layout_height="56dp" android:text=" Please Wait " android:textSize="25sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Create a new java file
In the fourth step create a new java file named Dialog to implement alert dialog and methods like startloadingdialog and dismissdialog. startloadingdialog function that will have an AlertDialog and on calling startloadingdialog function an alert loading dialog will appear on the user screen that gets dismisses after 4 seconds. dismissdialog function with the help of dialog.dismiss method that will dismiss the dialog. Below is the code for the Dialog.java file:
Java
import android.annotation.SuppressLint;import android.app.Activity;import android.app.AlertDialog;import android.view.LayoutInflater; public class dialog { // 2 objects activity and dialog private Activity activity; private AlertDialog dialog; // constructor of dialog class // with parameter activity dialog(Activity myActivity) { activity = myActivity; } @SuppressLint("InflateParams") void startLoadingdialog() { // adding ALERT Dialog builder object and passing activity as parameter AlertDialog.Builder builder = new AlertDialog.Builder(activity); // layoutinflater object and use activity to get layout inflater LayoutInflater inflater = activity.getLayoutInflater(); builder.setView(inflater.inflate(R.layout.loading, null)); builder.setCancelable(true); dialog = builder.create(); dialog.show(); } // dismiss method void dismissdialog() { dialog.dismiss(); } }
Step 5: Create a vector asset icon
In this step, we are going to create a vector asset icon that we will use in the 6th step to design a layout that appears on the screen after dismiss dialog function gets executed or invoked. Create a new vector asset for click icon using the following steps: Right-click on drawable > new > vector asset and search for check > select and finish
fig = vector asset
XML
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:fillColor="#0F9D58" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" /></vector>
After changing color code to green:
FIG = VECTOR ASSET
Step 6: In this step, we are going to make a new activity that contains a vector asset click icon that we created in the previous step (step 5) and a TextView with text done this activity will be visible to the user after the dismissing of the dialog that happened in the interval of 4 seconds. Following is the xml code to implement vector asset click icon with the help of ImageView and a TextView with text done.
1. xml file
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".finished"> <TextView android:id="@+id/textView3" android:layout_width="118dp" android:layout_height="44dp" android:layout_marginTop="24dp" android:text=" DONE " android:textAlignment="center" android:textSize="25dp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.477" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <ImageView android:id="@+id/imageView" android:layout_width="112dp" android:layout_height="86dp" android:layout_marginTop="220dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.468" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/ic_baseline_check_circle_24" /> </androidx.constraintlayout.widget.ConstraintLayout>
2. Java file
No need to change anything in the java class of this activity
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class finished extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_finished); }}
Step 7: Working with the MainActivity.java file
Now in the final step, we are going to add the onclick listener on our submit button in our MainActivity.java file.
Approach:
First, we will create an object of dialog class, and after finds the view of our submit button id we will implement set onclicklistener method on the submit button and invoke or implement the start loading function that we create in the dialog class and with the use of handler class we implement the time delay method for dismissdialog function and start new activity method using the intent that takes the user to finishedactivity after 4 seconds of delay time.
Java
import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button login_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login_btn = findViewById(R.id.button); // creating object of Loadingdialog class and passing MainActivity as argument final dialog loadingdialog = new dialog(MainActivity.this); // onclicklistener implementation login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // invoking startLoadingDialog method loadingdialog.startLoadingdialog(); // using handler class to set time delay methods Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // after 4 seconds loadingdialog.dismissdialog(); Intent i = new Intent(MainActivity.this, finished.class); // starting finished activity startActivity(i); } }, 4000); // 4 seconds } }); }}
Output:
1. Home Activity
FIG = HOME SCREEN
2. onclick
FIG = LOADING DIALOG
3. After 4 Seconds
FIG = CLICK VECTOR ASSET
Output Video:
Project Link: Click Here
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 651,
"s": 28,
"text": "AlertDialog is defined as the small window that shows a particular message to the user when the user performs or commits certain action. In this article, we are going to build a simple android application in which we learn how to implement a Loading AlertDialog that means whenever the user clicks on the submit button it shows a dialog with a loading ProgressBar and a message please wait and after a certain time it gets dismissed and shows a message done. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language."
},
{
"code": null,
"e": 680,
"s": 651,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 842,
"s": 680,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 890,
"s": 842,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1024,
"s": 890,
"text": "In this step, we are going to design our activity_main.xml. These are the following things that we will add to our activity_main.xml "
},
{
"code": null,
"e": 1080,
"s": 1024,
"text": "An ImageView with the image of the GEEKSOFGEEKS symbol."
},
{
"code": null,
"e": 1142,
"s": 1080,
"text": "Two EditTexts one for username and one for the password field"
},
{
"code": null,
"e": 1173,
"s": 1142,
"text": "A Button with the text SUBMIT."
},
{
"code": null,
"e": 1316,
"s": 1173,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1320,
"s": 1316,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"276dp\" android:text=\"SUBMIT\" android:textColor=\"#0f9d58\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.504\" app:layout_constraintStart_toStartOf=\"parent\" /> <EditText android:id=\"@+id/editTextTextPersonName2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"52dp\" android:ems=\"10\" android:hint=\"Password\" android:inputType=\"textPassword\" android:text=\"\" android:textAlignment=\"center\" android:textColorHint=\"#0f9d58\" android:textSize=\"20dp\" android:textStyle=\"bold\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/editTextTextPersonName3\" /> <EditText android:id=\"@+id/editTextTextPersonName3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"180dp\" android:ems=\"10\" android:hint=\"Username\" android:inputType=\"textPersonName\" android:text=\"\" android:textAlignment=\"center\" android:textColorHint=\"#0f9d58\" android:textSize=\"20dp\" android:textStyle=\"bold\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <ImageView android:id=\"@+id/imageView2\" android:layout_width=\"138dp\" android:layout_height=\"123dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"40dp\" app:layout_constraintBottom_toTopOf=\"@+id/editTextTextPersonName3\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"1.0\" app:srcCompat=\"@drawable/gfg\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 4034,
"s": 1320,
"text": null
},
{
"code": null,
"e": 4067,
"s": 4034,
"text": "Step 3: Create a new layout file"
},
{
"code": null,
"e": 4444,
"s": 4067,
"text": "In this step, we are going to create a new layout file for designing our dialog. Now create a new layout file to design the dialog that includes a loading ProgressBar and a text field with a text please wait. To create a new layout file please follow the following steps: Right-click on layout > new > Layout Resource file and name it loading and add the following code in it."
},
{
"code": null,
"e": 4488,
"s": 4444,
"text": "Below is the code for the loading.xml file:"
},
{
"code": null,
"e": 4492,
"s": 4488,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"50dp\"> <ProgressBar android:id=\"@+id/progressBar\" style=\"?android:attr/progressBarStyle\" android:layout_width=\"80dp\" android:layout_height=\"66dp\" android:layout_marginBottom=\"24dp\" app:layout_constraintBottom_toTopOf=\"@+id/message\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" /> <TextView android:id=\"@+id/message\" android:layout_width=\"150dp\" android:layout_height=\"56dp\" android:text=\" Please Wait \" android:textSize=\"25sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 5722,
"s": 4492,
"text": null
},
{
"code": null,
"e": 5753,
"s": 5722,
"text": "Step 4: Create a new java file"
},
{
"code": null,
"e": 6218,
"s": 5753,
"text": "In the fourth step create a new java file named Dialog to implement alert dialog and methods like startloadingdialog and dismissdialog. startloadingdialog function that will have an AlertDialog and on calling startloadingdialog function an alert loading dialog will appear on the user screen that gets dismisses after 4 seconds. dismissdialog function with the help of dialog.dismiss method that will dismiss the dialog. Below is the code for the Dialog.java file:"
},
{
"code": null,
"e": 6223,
"s": 6218,
"text": "Java"
},
{
"code": "import android.annotation.SuppressLint;import android.app.Activity;import android.app.AlertDialog;import android.view.LayoutInflater; public class dialog { // 2 objects activity and dialog private Activity activity; private AlertDialog dialog; // constructor of dialog class // with parameter activity dialog(Activity myActivity) { activity = myActivity; } @SuppressLint(\"InflateParams\") void startLoadingdialog() { // adding ALERT Dialog builder object and passing activity as parameter AlertDialog.Builder builder = new AlertDialog.Builder(activity); // layoutinflater object and use activity to get layout inflater LayoutInflater inflater = activity.getLayoutInflater(); builder.setView(inflater.inflate(R.layout.loading, null)); builder.setCancelable(true); dialog = builder.create(); dialog.show(); } // dismiss method void dismissdialog() { dialog.dismiss(); } }",
"e": 7234,
"s": 6223,
"text": null
},
{
"code": null,
"e": 7269,
"s": 7234,
"text": "Step 5: Create a vector asset icon"
},
{
"code": null,
"e": 7616,
"s": 7269,
"text": "In this step, we are going to create a vector asset icon that we will use in the 6th step to design a layout that appears on the screen after dismiss dialog function gets executed or invoked. Create a new vector asset for click icon using the following steps: Right-click on drawable > new > vector asset and search for check > select and finish "
},
{
"code": null,
"e": 7636,
"s": 7616,
"text": "fig = vector asset "
},
{
"code": null,
"e": 7640,
"s": 7636,
"text": "XML"
},
{
"code": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\"> <path android:fillColor=\"#0F9D58\" android:pathData=\"M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z\" /></vector>",
"e": 8023,
"s": 7640,
"text": null
},
{
"code": null,
"e": 8060,
"s": 8023,
"text": "After changing color code to green: "
},
{
"code": null,
"e": 8079,
"s": 8060,
"text": "FIG = VECTOR ASSET"
},
{
"code": null,
"e": 8496,
"s": 8079,
"text": "Step 6: In this step, we are going to make a new activity that contains a vector asset click icon that we created in the previous step (step 5) and a TextView with text done this activity will be visible to the user after the dismissing of the dialog that happened in the interval of 4 seconds. Following is the xml code to implement vector asset click icon with the help of ImageView and a TextView with text done. "
},
{
"code": null,
"e": 8508,
"s": 8496,
"text": "1. xml file"
},
{
"code": null,
"e": 8512,
"s": 8508,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".finished\"> <TextView android:id=\"@+id/textView3\" android:layout_width=\"118dp\" android:layout_height=\"44dp\" android:layout_marginTop=\"24dp\" android:text=\" DONE \" android:textAlignment=\"center\" android:textSize=\"25dp\" android:textStyle=\"bold\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.477\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"112dp\" android:layout_height=\"86dp\" android:layout_marginTop=\"220dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.468\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:srcCompat=\"@drawable/ic_baseline_check_circle_24\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 9873,
"s": 8512,
"text": null
},
{
"code": null,
"e": 9887,
"s": 9873,
"text": "2. Java file "
},
{
"code": null,
"e": 9950,
"s": 9887,
"text": "No need to change anything in the java class of this activity "
},
{
"code": null,
"e": 9955,
"s": 9950,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class finished extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_finished); }}",
"e": 10253,
"s": 9955,
"text": null
},
{
"code": null,
"e": 10301,
"s": 10253,
"text": "Step 7: Working with the MainActivity.java file"
},
{
"code": null,
"e": 10417,
"s": 10301,
"text": "Now in the final step, we are going to add the onclick listener on our submit button in our MainActivity.java file."
},
{
"code": null,
"e": 10428,
"s": 10417,
"text": "Approach: "
},
{
"code": null,
"e": 10892,
"s": 10428,
"text": "First, we will create an object of dialog class, and after finds the view of our submit button id we will implement set onclicklistener method on the submit button and invoke or implement the start loading function that we create in the dialog class and with the use of handler class we implement the time delay method for dismissdialog function and start new activity method using the intent that takes the user to finishedactivity after 4 seconds of delay time."
},
{
"code": null,
"e": 10897,
"s": 10892,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button login_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login_btn = findViewById(R.id.button); // creating object of Loadingdialog class and passing MainActivity as argument final dialog loadingdialog = new dialog(MainActivity.this); // onclicklistener implementation login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // invoking startLoadingDialog method loadingdialog.startLoadingdialog(); // using handler class to set time delay methods Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // after 4 seconds loadingdialog.dismissdialog(); Intent i = new Intent(MainActivity.this, finished.class); // starting finished activity startActivity(i); } }, 4000); // 4 seconds } }); }}",
"e": 12391,
"s": 10897,
"text": null
},
{
"code": null,
"e": 12399,
"s": 12391,
"text": "Output:"
},
{
"code": null,
"e": 12417,
"s": 12399,
"text": "1. Home Activity "
},
{
"code": null,
"e": 12436,
"s": 12417,
"text": "FIG = HOME SCREEN "
},
{
"code": null,
"e": 12448,
"s": 12436,
"text": "2. onclick "
},
{
"code": null,
"e": 12469,
"s": 12448,
"text": "FIG = LOADING DIALOG"
},
{
"code": null,
"e": 12489,
"s": 12469,
"text": "3. After 4 Seconds "
},
{
"code": null,
"e": 12514,
"s": 12489,
"text": "FIG = CLICK VECTOR ASSET"
},
{
"code": null,
"e": 12528,
"s": 12514,
"text": "Output Video:"
},
{
"code": null,
"e": 12553,
"s": 12528,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 12561,
"s": 12553,
"text": "Android"
},
{
"code": null,
"e": 12566,
"s": 12561,
"text": "Java"
},
{
"code": null,
"e": 12571,
"s": 12566,
"text": "Java"
},
{
"code": null,
"e": 12579,
"s": 12571,
"text": "Android"
}
] |
Python | Difference Between List and Tuple
|
17 Mar, 2021
List and Tuple in Python are the class of data structure. The list is dynamic, whereas the tuple has static characteristics. List is just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. In Python, the list is a type of container in Data Structures, which is used to store multiple data at the same time. Lists are a useful tool for preserving a sequence of data and further iterating over it. Syntax:
list_data = ['an', 'example', 'of', 'a', 'list']
Tuple is also a sequence data type that can contain elements of different data types, but these are immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The tuple is faster than the list because of static in nature. Syntax:
tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')
Difference Between List and Tuple in Python:
shivam2608
Difference Between
Python
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
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Stack vs Heap Memory Allocation
Difference between Clustered and Non-clustered index
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 538,
"s": 52,
"text": "List and Tuple in Python are the class of data structure. The list is dynamic, whereas the tuple has static characteristics. List is just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. In Python, the list is a type of container in Data Structures, which is used to store multiple data at the same time. Lists are a useful tool for preserving a sequence of data and further iterating over it. Syntax: "
},
{
"code": null,
"e": 587,
"s": 538,
"text": "list_data = ['an', 'example', 'of', 'a', 'list']"
},
{
"code": null,
"e": 860,
"s": 587,
"text": "Tuple is also a sequence data type that can contain elements of different data types, but these are immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The tuple is faster than the list because of static in nature. Syntax: "
},
{
"code": null,
"e": 920,
"s": 860,
"text": "tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')"
},
{
"code": null,
"e": 967,
"s": 920,
"text": "Difference Between List and Tuple in Python: "
},
{
"code": null,
"e": 980,
"s": 969,
"text": "shivam2608"
},
{
"code": null,
"e": 999,
"s": 980,
"text": "Difference Between"
},
{
"code": null,
"e": 1006,
"s": 999,
"text": "Python"
},
{
"code": null,
"e": 1104,
"s": 1006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1165,
"s": 1104,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1233,
"s": 1165,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 1270,
"s": 1233,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 1302,
"s": 1270,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 1355,
"s": 1302,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 1383,
"s": 1355,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1433,
"s": 1383,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1455,
"s": 1433,
"text": "Python map() function"
},
{
"code": null,
"e": 1499,
"s": 1455,
"text": "How to get column names in Pandas dataframe"
}
] |
Python – Vertical Concatenation in Matrix
|
30 Aug, 2020
Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths.
Input : [[“Gfg”, “good”], [“is”, “for”]]Output : [‘Gfgis’, ‘goodfor’]Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on.
Input : [[“Gfg”, “good”, “geeks”], [“is”, “for”, “best”]]Output : [‘Gfgis’, ‘goodfor’, “geeksbest”]Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we iterate for all the columns and perform concatenation.
Python3
# Python3 code to demonstrate working of # Vertical Concatenation in Matrix# Using loop # initializing liststest_list = [["Gfg", "good"], ["is", "for"], ["Best"]] # printing original listprint("The original list : " + str(test_list)) # using loop for iterationres = []N = 0while N != len(test_list): temp = '' for idx in test_list: # checking for valid index / column try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] # printing result print("List after column Concatenation : " + str(res))
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']
Method #2 : Using join() + list comprehension + zip_longest()
The combination of above functions can be used to solve this problem. In this, we handle the null index values using zip_longest, and join() is used to perform task of concatenation. The list comprehension drives one-liner logic.
Python3
# Python3 code to demonstrate working of # Vertical Concatenation in Matrix# Using join() + list comprehension + zip_longest()from itertools import zip_longest # initializing liststest_list = [["Gfg", "good"], ["is", "for"], ["Best"]] # printing original listprint("The original list : " + str(test_list)) # using join to concaternate, zip_longest filling values using # "fill"res = ["".join(ele) for ele in zip_longest(*test_list, fillvalue ="")] # printing result print("List after column Concatenation : " + str(res))
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
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 | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 154,
"s": 52,
"text": "Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths."
},
{
"code": null,
"e": 312,
"s": 154,
"text": "Input : [[“Gfg”, “good”], [“is”, “for”]]Output : [‘Gfgis’, ‘goodfor’]Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on."
},
{
"code": null,
"e": 500,
"s": 312,
"text": "Input : [[“Gfg”, “good”, “geeks”], [“is”, “for”, “best”]]Output : [‘Gfgis’, ‘goodfor’, “geeksbest”]Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on."
},
{
"code": null,
"e": 523,
"s": 500,
"text": "Method #1 : Using loop"
},
{
"code": null,
"e": 646,
"s": 523,
"text": "This is brute way in which this task can be performed. In this, we iterate for all the columns and perform concatenation. "
},
{
"code": null,
"e": 654,
"s": 646,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Vertical Concatenation in Matrix# Using loop # initializing liststest_list = [[\"Gfg\", \"good\"], [\"is\", \"for\"], [\"Best\"]] # printing original listprint(\"The original list : \" + str(test_list)) # using loop for iterationres = []N = 0while N != len(test_list): temp = '' for idx in test_list: # checking for valid index / column try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] # printing result print(\"List after column Concatenation : \" + str(res))",
"e": 1254,
"s": 654,
"text": null
},
{
"code": null,
"e": 1377,
"s": 1254,
"text": "The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]\nList after column Concatenation : ['GfgisBest', 'goodfor']\n"
},
{
"code": null,
"e": 1439,
"s": 1377,
"text": "Method #2 : Using join() + list comprehension + zip_longest()"
},
{
"code": null,
"e": 1669,
"s": 1439,
"text": "The combination of above functions can be used to solve this problem. In this, we handle the null index values using zip_longest, and join() is used to perform task of concatenation. The list comprehension drives one-liner logic."
},
{
"code": null,
"e": 1677,
"s": 1669,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Vertical Concatenation in Matrix# Using join() + list comprehension + zip_longest()from itertools import zip_longest # initializing liststest_list = [[\"Gfg\", \"good\"], [\"is\", \"for\"], [\"Best\"]] # printing original listprint(\"The original list : \" + str(test_list)) # using join to concaternate, zip_longest filling values using # \"fill\"res = [\"\".join(ele) for ele in zip_longest(*test_list, fillvalue =\"\")] # printing result print(\"List after column Concatenation : \" + str(res))",
"e": 2202,
"s": 1677,
"text": null
},
{
"code": null,
"e": 2325,
"s": 2202,
"text": "The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]\nList after column Concatenation : ['GfgisBest', 'goodfor']\n"
},
{
"code": null,
"e": 2346,
"s": 2325,
"text": "Python list-programs"
},
{
"code": null,
"e": 2369,
"s": 2346,
"text": "Python string-programs"
},
{
"code": null,
"e": 2376,
"s": 2369,
"text": "Python"
},
{
"code": null,
"e": 2392,
"s": 2376,
"text": "Python Programs"
},
{
"code": null,
"e": 2490,
"s": 2392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2508,
"s": 2490,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2550,
"s": 2508,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2572,
"s": 2550,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2607,
"s": 2572,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2633,
"s": 2607,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2676,
"s": 2633,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2698,
"s": 2676,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2737,
"s": 2698,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2775,
"s": 2737,
"text": "Python | Convert a list to dictionary"
}
] |
jQuery data() with Examples
|
The data() method in jQuery is used to attach data to or gets data from selected elements.
The syntax is as follows −
$(selector).data(name)
$(selector).data(name,value)
Above, the name is the name of data to retrieve for the 1st syntax.
For the 2nd syntax, the name is the name of data to set, whereas value is the value of data to set.
Let us now see an example to implement the jQuery data() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".button1").click(function(){
$("div").data("student", "Jack Sparrow");
alert("Student Name = " +$("div").data("student"));
});
$(".button2").click(function(){
$("div").removeData("student");
alert("Student Name = " +$("div").data("Jack Sparrow"));
});
});
</script>
<style>
.button1 {
background-color: orange;
color: white;
}
.button2 {
background-color: orange;
color: white;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<button class="button1">Attach</button><br><br>
<button class="button2">Remove</button>
<div></div>
</body>
</html>
This will produce the following output −
|
[
{
"code": null,
"e": 1278,
"s": 1187,
"text": "The data() method in jQuery is used to attach data to or gets data from selected elements."
},
{
"code": null,
"e": 1305,
"s": 1278,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1357,
"s": 1305,
"text": "$(selector).data(name)\n$(selector).data(name,value)"
},
{
"code": null,
"e": 1425,
"s": 1357,
"text": "Above, the name is the name of data to retrieve for the 1st syntax."
},
{
"code": null,
"e": 1525,
"s": 1425,
"text": "For the 2nd syntax, the name is the name of data to set, whereas value is the value of data to set."
},
{
"code": null,
"e": 1591,
"s": 1525,
"text": "Let us now see an example to implement the jQuery data() method −"
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": " Live Demo"
},
{
"code": null,
"e": 2383,
"s": 1602,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\".button1\").click(function(){\n $(\"div\").data(\"student\", \"Jack Sparrow\");\n alert(\"Student Name = \" +$(\"div\").data(\"student\"));\n });\n $(\".button2\").click(function(){\n $(\"div\").removeData(\"student\");\n alert(\"Student Name = \" +$(\"div\").data(\"Jack Sparrow\"));\n });\n });\n</script>\n<style>\n.button1 {\n background-color: orange;\n color: white;\n}\n.button2 {\n background-color: orange;\n color: white;\n}\n</style>\n</head>\n<body>\n<h2>Demo Heading</h2>\n<button class=\"button1\">Attach</button><br><br>\n<button class=\"button2\">Remove</button>\n<div></div>\n</body>\n</html>"
},
{
"code": null,
"e": 2424,
"s": 2383,
"text": "This will produce the following output −"
}
] |
Python | Tail Sliced List Summation
|
10 Oct, 2021
We often come to the situations in which we need to decrease the size of the list by truncating the last elements of the list and perform remaining list summation. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we require to get all the lists of similar size. Let’s discuss certain ways in which this task can be performed.Method #1 : Using len() + list slicing + sum() List slicing can perform this particular task in which we just slice the first len(list) – K elements to be in the list and hence removing the last K elements. The task of performing tail summation is performed using sum().
Python3
# Python code to demonstrate# Tail Sliced List Summation# using len() + list slicing + sum() # initializing listtest_list = [1, 4, 6, 3, 5, 8] # printing original listprint ("The original list is : " + str(test_list)) # initializing KK = 3 # using len() + list slicing + sum()# Tail Sliced List Summationres = sum(test_list[: len(test_list) - K]) # printing resultprint ("The tail removed list summation : " + str(res))
The original list is : [1, 4, 6, 3, 5, 8]
The tail removed list summation : 11
Method #2 : Using Negative list slicing + sum() We can perform this particular task using the negative list slicing in which we start removing the elements from the last index of the list and hence remove all the K elements from the last. We remove None if 0 elements are asked to be removed. The task of performing tail summation is performed using sum().
Python3
# Python code to demonstrate# Tail Sliced List Summation# using negative list slicing + sum() # initializing listtest_list = [1, 4, 6, 3, 5, 8] # printing original listprint ("The original list is : " + str(test_list)) # initializing KK = 3 # using negative list slicing + sum()# Tail Sliced List Summationres = sum(test_list[: -K or None]) # printing resultprint ("The tail removed list summation : " + str(res))
The original list is : [1, 4, 6, 3, 5, 8]
The tail removed list summation : 11
simmytarika5
Python list-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 ?
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 707,
"s": 28,
"text": "We often come to the situations in which we need to decrease the size of the list by truncating the last elements of the list and perform remaining list summation. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we require to get all the lists of similar size. Let’s discuss certain ways in which this task can be performed.Method #1 : Using len() + list slicing + sum() List slicing can perform this particular task in which we just slice the first len(list) – K elements to be in the list and hence removing the last K elements. The task of performing tail summation is performed using sum(). "
},
{
"code": null,
"e": 715,
"s": 707,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# Tail Sliced List Summation# using len() + list slicing + sum() # initializing listtest_list = [1, 4, 6, 3, 5, 8] # printing original listprint (\"The original list is : \" + str(test_list)) # initializing KK = 3 # using len() + list slicing + sum()# Tail Sliced List Summationres = sum(test_list[: len(test_list) - K]) # printing resultprint (\"The tail removed list summation : \" + str(res))",
"e": 1135,
"s": 715,
"text": null
},
{
"code": null,
"e": 1214,
"s": 1135,
"text": "The original list is : [1, 4, 6, 3, 5, 8]\nThe tail removed list summation : 11"
},
{
"code": null,
"e": 1575,
"s": 1216,
"text": " Method #2 : Using Negative list slicing + sum() We can perform this particular task using the negative list slicing in which we start removing the elements from the last index of the list and hence remove all the K elements from the last. We remove None if 0 elements are asked to be removed. The task of performing tail summation is performed using sum(). "
},
{
"code": null,
"e": 1583,
"s": 1575,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# Tail Sliced List Summation# using negative list slicing + sum() # initializing listtest_list = [1, 4, 6, 3, 5, 8] # printing original listprint (\"The original list is : \" + str(test_list)) # initializing KK = 3 # using negative list slicing + sum()# Tail Sliced List Summationres = sum(test_list[: -K or None]) # printing resultprint (\"The tail removed list summation : \" + str(res))",
"e": 1997,
"s": 1583,
"text": null
},
{
"code": null,
"e": 2076,
"s": 1997,
"text": "The original list is : [1, 4, 6, 3, 5, 8]\nThe tail removed list summation : 11"
},
{
"code": null,
"e": 2091,
"s": 2078,
"text": "simmytarika5"
},
{
"code": null,
"e": 2112,
"s": 2091,
"text": "Python list-programs"
},
{
"code": null,
"e": 2119,
"s": 2112,
"text": "Python"
},
{
"code": null,
"e": 2135,
"s": 2119,
"text": "Python Programs"
},
{
"code": null,
"e": 2233,
"s": 2135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2265,
"s": 2233,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2292,
"s": 2265,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2313,
"s": 2292,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2336,
"s": 2313,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2392,
"s": 2336,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2414,
"s": 2392,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2453,
"s": 2414,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2491,
"s": 2453,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2528,
"s": 2491,
"text": "Python Program for Fibonacci numbers"
}
] |
How to Reference Elements in an Array in Python
|
03 Jan, 2021
Prerequisites: Numpy
Elements of an array can be referenced like a regular python array. Since python internally doesn’t support arrays, here whenever we use the term array we are referring to pythons list that can be used to build an array of any required dimension. Besides this, Python’s NumPy module also provides a container named ‘array’ for storing collections of data. In this article, we will talk about how to reference elements in a Python array as well as numpy array in Python.
For array referencing only the index of the required element has to be passed to the name of the array.
Syntax:
array_name[index]
For referencing using numpy array, first an array is created using numpy’s array function then it is referenced like a regular array.
Syntax:
np.array([array elements])
Implementation using both methods is given below for various cases:
Example 1: Referencing items in a 1-D array
Example with Python Array
Python3
# Creating a array of elementsarr = [4, 6, 3, 9, 2] # Referring elements of the array# by index to a new variablefirst_element = arr[0]second_element = arr[1]third_element = arr[2]fourth_element = arr[3]fifth_element = arr[4] # Print the variablesprint("First Element =", first_element)print("Second Element =", second_element)print("Third Element =", third_element)print("Fourth Element =", fourth_element)print("Fifth Element =", fifth_element)
Output:
Example with Python’s numpy module’s array
Python3
# Importing numpy moduleimport numpy as np # Creating a numpy array of elementsarr = np.array([4, 6, 3, 9, 2]) # Referring elements of the array# by index to a new variablefirst_element = arr[0]second_element = arr[1]third_element = arr[2]fourth_element = arr[3]fifth_element = arr[4] # Print the variablesprint("First Element =", first_element)print("Second Element =", second_element)print("Third Element =", third_element)print("Fourth Element =", fourth_element)print("Fifth Element =", fifth_element)
Output:
Example 2: Referencing Items in a 2-D Array
Example with Python Array
Python3
# Creating a 2d-array of elementsarr = [[4, 6, 3], [5, 9, 2], [1, 8, 7]] # Referring elements of the 2d-array# by row and column index to new variablesfirst_row_second_column = arr[0][1]second_row_first_column = arr[1][0]third_row_third_column = arr[2][2] # Print the variablesprint("First Row Second Column =", first_row_second_column)print("Second Row First Column =", second_row_first_column)print("Third Row Third Column =", third_row_third_column)
Output:
Example with Python’s numpy module’s array
Python3
# Importing numpy moduleimport numpy as np # Creating a 2d-numpy-array of elementsarr = np.array([[4, 6, 3], [5, 9, 2], [1, 8, 7]]) # Referring elements of the 2d-array# by row and column index to new variablesfirst_row_second_column = arr[0][1]second_row_first_column = arr[1][0]third_row_third_column = arr[2][2] # Print the variablesprint("First Row Second Column =", first_row_second_column)print("Second Row First Column =", second_row_first_column)print("Third Row Third Column =", third_row_third_column)
Output:
Example 3: Referencing Items in a3-D Array
Example with Python array
Python3
# Creating a 3d-array of elementsarr = [[[4, 6, 3], [2, 6, 8], [3, 5, 12]], [[32, 11, 4], [23, 53, 89], [19, 17, 10]], [[14, 22, 52], [56, 43, 99], [20, 37, 32]]] # Referring elements of the 3d-array# by 3d index to new variablesfirst_second_second = arr[0][1][1]second_first_third = arr[1][0][2]third_third_first = arr[2][2][0] # Print the variablesprint("First Second Second Value =", first_second_second)print("Second First Third Value =", second_first_third)print("Third Third First Value =", third_third_first)
Output:
Example with Python’s numpy module’s array
Python3
# Importing numpy moduleimport numpy as np # Creating a 3d-array of elementsarr = np.array([[[4, 6, 3], [2, 6, 8], [3, 5, 12]], [[32, 11, 4], [23, 53, 89], [19, 17, 10]], [[14, 22, 52], [56, 43, 99], [20, 37, 32]]]) # Referring elements of the 3d-array# by 3d index to new variablesfirst_second_second = arr[0][1][1]second_first_third = arr[1][0][2]third_third_first = arr[2][2][0] # Print the variablesprint("First Second Second Value =", first_second_second)print("Second First Third Value =", second_first_third)print("Third Third First Value =", third_third_first)
Output:
Example 4: Referencing an Entire Row of an Array
Example with Python array
Python3
# Creating a 2d-array of elementsarr = [[4, 6, 3], [5, 9, 2], [1, 8, 7]] # Referring rows of the 2d-array# by row index to new variablesfirst_row = arr[0]second_row = arr[1]third_row = arr[2] # Print the variablesprint("First Row =", first_row)print("Second Row =", second_row)print("Third Row =", third_row)
Output:
Example with Python’s numpy module’s array
Python3
# Importing numpy moduleimport numpy as np # Creating a 2d-numpy-array of elementsarr = np.array([[4, 6, 3], [5, 9, 2], [1, 8, 7]]) # Referring rows of the 2d-array# by row index to new variablesfirst_row = arr[0]second_row = arr[1]third_row = arr[2] # Print the variablesprint("First Row =", first_row)print("Second Row =", second_row)print("Third Row =", third_row)
Output:
Picked
Python-array
Technical Scripter 2020
Python
Technical Scripter
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
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 74,
"s": 53,
"text": "Prerequisites: Numpy"
},
{
"code": null,
"e": 545,
"s": 74,
"text": "Elements of an array can be referenced like a regular python array. Since python internally doesn’t support arrays, here whenever we use the term array we are referring to pythons list that can be used to build an array of any required dimension. Besides this, Python’s NumPy module also provides a container named ‘array’ for storing collections of data. In this article, we will talk about how to reference elements in a Python array as well as numpy array in Python."
},
{
"code": null,
"e": 649,
"s": 545,
"text": "For array referencing only the index of the required element has to be passed to the name of the array."
},
{
"code": null,
"e": 657,
"s": 649,
"text": "Syntax:"
},
{
"code": null,
"e": 675,
"s": 657,
"text": "array_name[index]"
},
{
"code": null,
"e": 809,
"s": 675,
"text": "For referencing using numpy array, first an array is created using numpy’s array function then it is referenced like a regular array."
},
{
"code": null,
"e": 817,
"s": 809,
"text": "Syntax:"
},
{
"code": null,
"e": 844,
"s": 817,
"text": "np.array([array elements])"
},
{
"code": null,
"e": 912,
"s": 844,
"text": "Implementation using both methods is given below for various cases:"
},
{
"code": null,
"e": 956,
"s": 912,
"text": "Example 1: Referencing items in a 1-D array"
},
{
"code": null,
"e": 982,
"s": 956,
"text": "Example with Python Array"
},
{
"code": null,
"e": 990,
"s": 982,
"text": "Python3"
},
{
"code": "# Creating a array of elementsarr = [4, 6, 3, 9, 2] # Referring elements of the array# by index to a new variablefirst_element = arr[0]second_element = arr[1]third_element = arr[2]fourth_element = arr[3]fifth_element = arr[4] # Print the variablesprint(\"First Element =\", first_element)print(\"Second Element =\", second_element)print(\"Third Element =\", third_element)print(\"Fourth Element =\", fourth_element)print(\"Fifth Element =\", fifth_element)",
"e": 1439,
"s": 990,
"text": null
},
{
"code": null,
"e": 1447,
"s": 1439,
"text": "Output:"
},
{
"code": null,
"e": 1490,
"s": 1447,
"text": "Example with Python’s numpy module’s array"
},
{
"code": null,
"e": 1498,
"s": 1490,
"text": "Python3"
},
{
"code": "# Importing numpy moduleimport numpy as np # Creating a numpy array of elementsarr = np.array([4, 6, 3, 9, 2]) # Referring elements of the array# by index to a new variablefirst_element = arr[0]second_element = arr[1]third_element = arr[2]fourth_element = arr[3]fifth_element = arr[4] # Print the variablesprint(\"First Element =\", first_element)print(\"Second Element =\", second_element)print(\"Third Element =\", third_element)print(\"Fourth Element =\", fourth_element)print(\"Fifth Element =\", fifth_element)",
"e": 2007,
"s": 1498,
"text": null
},
{
"code": null,
"e": 2015,
"s": 2007,
"text": "Output:"
},
{
"code": null,
"e": 2059,
"s": 2015,
"text": "Example 2: Referencing Items in a 2-D Array"
},
{
"code": null,
"e": 2086,
"s": 2059,
"text": " Example with Python Array"
},
{
"code": null,
"e": 2094,
"s": 2086,
"text": "Python3"
},
{
"code": "# Creating a 2d-array of elementsarr = [[4, 6, 3], [5, 9, 2], [1, 8, 7]] # Referring elements of the 2d-array# by row and column index to new variablesfirst_row_second_column = arr[0][1]second_row_first_column = arr[1][0]third_row_third_column = arr[2][2] # Print the variablesprint(\"First Row Second Column =\", first_row_second_column)print(\"Second Row First Column =\", second_row_first_column)print(\"Third Row Third Column =\", third_row_third_column)",
"e": 2561,
"s": 2094,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2561,
"text": "Output:"
},
{
"code": null,
"e": 2612,
"s": 2569,
"text": "Example with Python’s numpy module’s array"
},
{
"code": null,
"e": 2620,
"s": 2612,
"text": "Python3"
},
{
"code": "# Importing numpy moduleimport numpy as np # Creating a 2d-numpy-array of elementsarr = np.array([[4, 6, 3], [5, 9, 2], [1, 8, 7]]) # Referring elements of the 2d-array# by row and column index to new variablesfirst_row_second_column = arr[0][1]second_row_first_column = arr[1][0]third_row_third_column = arr[2][2] # Print the variablesprint(\"First Row Second Column =\", first_row_second_column)print(\"Second Row First Column =\", second_row_first_column)print(\"Third Row Third Column =\", third_row_third_column)",
"e": 3165,
"s": 2620,
"text": null
},
{
"code": null,
"e": 3173,
"s": 3165,
"text": "Output:"
},
{
"code": null,
"e": 3216,
"s": 3173,
"text": "Example 3: Referencing Items in a3-D Array"
},
{
"code": null,
"e": 3242,
"s": 3216,
"text": "Example with Python array"
},
{
"code": null,
"e": 3250,
"s": 3242,
"text": "Python3"
},
{
"code": "# Creating a 3d-array of elementsarr = [[[4, 6, 3], [2, 6, 8], [3, 5, 12]], [[32, 11, 4], [23, 53, 89], [19, 17, 10]], [[14, 22, 52], [56, 43, 99], [20, 37, 32]]] # Referring elements of the 3d-array# by 3d index to new variablesfirst_second_second = arr[0][1][1]second_first_third = arr[1][0][2]third_third_first = arr[2][2][0] # Print the variablesprint(\"First Second Second Value =\", first_second_second)print(\"Second First Third Value =\", second_first_third)print(\"Third Third First Value =\", third_third_first)",
"e": 3780,
"s": 3250,
"text": null
},
{
"code": null,
"e": 3788,
"s": 3780,
"text": "Output:"
},
{
"code": null,
"e": 3831,
"s": 3788,
"text": "Example with Python’s numpy module’s array"
},
{
"code": null,
"e": 3839,
"s": 3831,
"text": "Python3"
},
{
"code": "# Importing numpy moduleimport numpy as np # Creating a 3d-array of elementsarr = np.array([[[4, 6, 3], [2, 6, 8], [3, 5, 12]], [[32, 11, 4], [23, 53, 89], [19, 17, 10]], [[14, 22, 52], [56, 43, 99], [20, 37, 32]]]) # Referring elements of the 3d-array# by 3d index to new variablesfirst_second_second = arr[0][1][1]second_first_third = arr[1][0][2]third_third_first = arr[2][2][0] # Print the variablesprint(\"First Second Second Value =\", first_second_second)print(\"Second First Third Value =\", second_first_third)print(\"Third Third First Value =\", third_third_first)",
"e": 4441,
"s": 3839,
"text": null
},
{
"code": null,
"e": 4449,
"s": 4441,
"text": "Output:"
},
{
"code": null,
"e": 4498,
"s": 4449,
"text": "Example 4: Referencing an Entire Row of an Array"
},
{
"code": null,
"e": 4524,
"s": 4498,
"text": "Example with Python array"
},
{
"code": null,
"e": 4532,
"s": 4524,
"text": "Python3"
},
{
"code": "# Creating a 2d-array of elementsarr = [[4, 6, 3], [5, 9, 2], [1, 8, 7]] # Referring rows of the 2d-array# by row index to new variablesfirst_row = arr[0]second_row = arr[1]third_row = arr[2] # Print the variablesprint(\"First Row =\", first_row)print(\"Second Row =\", second_row)print(\"Third Row =\", third_row)",
"e": 4855,
"s": 4532,
"text": null
},
{
"code": null,
"e": 4863,
"s": 4855,
"text": "Output:"
},
{
"code": null,
"e": 4906,
"s": 4863,
"text": "Example with Python’s numpy module’s array"
},
{
"code": null,
"e": 4914,
"s": 4906,
"text": "Python3"
},
{
"code": "# Importing numpy moduleimport numpy as np # Creating a 2d-numpy-array of elementsarr = np.array([[4, 6, 3], [5, 9, 2], [1, 8, 7]]) # Referring rows of the 2d-array# by row index to new variablesfirst_row = arr[0]second_row = arr[1]third_row = arr[2] # Print the variablesprint(\"First Row =\", first_row)print(\"Second Row =\", second_row)print(\"Third Row =\", third_row)",
"e": 5315,
"s": 4914,
"text": null
},
{
"code": null,
"e": 5323,
"s": 5315,
"text": "Output:"
},
{
"code": null,
"e": 5330,
"s": 5323,
"text": "Picked"
},
{
"code": null,
"e": 5343,
"s": 5330,
"text": "Python-array"
},
{
"code": null,
"e": 5367,
"s": 5343,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5374,
"s": 5367,
"text": "Python"
},
{
"code": null,
"e": 5393,
"s": 5374,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5491,
"s": 5393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5523,
"s": 5491,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5550,
"s": 5523,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5571,
"s": 5550,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5594,
"s": 5571,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5650,
"s": 5594,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5681,
"s": 5650,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5723,
"s": 5681,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5765,
"s": 5723,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5804,
"s": 5765,
"text": "Python | Get unique values from a list"
}
] |
Check if all rows of a matrix are circular rotations of each other
|
06 Jul, 2022
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not.
Examples:
Input: mat[][] = 1, 2, 3
3, 1, 2
2, 3, 1
Output: Yes
All rows are rotated permutation
of each other.
Input: mat[3][3] = 1, 2, 3
3, 2, 1
1, 3, 2
Output: No
Explanation : As 3, 2, 1 is not a rotated or
circular permutation of 1, 2, 3
The idea is based on below article. A Program to check if strings are rotations of each other or not
Steps :
Create a string of first row elements and concatenate the string with itself so that string search operations can be efficiently performed. Let this string be str_cat.Traverse all remaining rows. For every row being traversed, create a string str_curr of current row elements. If str_curr is not a substring of str_cat, return false.Return true.
Create a string of first row elements and concatenate the string with itself so that string search operations can be efficiently performed. Let this string be str_cat.
Traverse all remaining rows. For every row being traversed, create a string str_curr of current row elements. If str_curr is not a substring of str_cat, return false.
Return true.
Below is the implementation of above steps.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if all rows of a matrix// are rotations of each other#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.bool isPermutedMatrix( int mat[MAX][MAX], int n){ // Creating a string that contains elements of first // row. string str_cat = ""; for (int i = 0 ; i < n ; i++) str_cat = str_cat + "-" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i<n; i++) { // Store the matrix into vector in the form // of strings string curr_str = ""; for (int j = 0 ; j < n ; j++) curr_str = curr_str + "-" + to_string(mat[i][j]); // Check if the current string is present in // the concatenated string or not if (str_cat.find(curr_str) == string::npos) return false; } return true;} // Drivers codeint main(){ int n = 4 ; int mat[MAX][MAX] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; isPermutedMatrix(mat, n)? cout << "Yes" : cout << "No"; return 0;}
// Java program to check if all rows of a matrix// are rotations of each otherclass GFG{ static int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. static boolean isPermutedMatrix(int mat[][], int n) { // Creating a string that contains // elements of first row. String str_cat = ""; for (int i = 0; i < n; i++) { str_cat = str_cat + "-" + String.valueOf(mat[0][i]); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings String curr_str = ""; for (int j = 0; j < n; j++) { curr_str = curr_str + "-" + String.valueOf(mat[i][j]); } // Check if the current string is present in // the concatenated string or not if (str_cat.contentEquals(curr_str)) { return false; } } return true; } // Drivers code public static void main(String[] args) { int n = 4; int mat[][] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; if (isPermutedMatrix(mat, n)) { System.out.println("Yes"); } else { System.out.println("No"); } }} /* This code contributed by PrinciRaj1992 */
# Python3 program to check if all rows# of a matrix are rotations of each other MAX = 1000 # Returns true if all rows of mat[0..n-1][0..n-1]# are rotations of each other.def isPermutedMatrix(mat, n) : # Creating a string that contains # elements of first row. str_cat = "" for i in range(n) : str_cat = str_cat + "-" + str(mat[0][i]) # Concatenating the string with itself # so that substring search operations # can be performed on this str_cat = str_cat + str_cat # Start traversing remaining rows for i in range(1, n) : # Store the matrix into vector # in the form of strings curr_str = "" for j in range(n) : curr_str = curr_str + "-" + str(mat[i][j]) # Check if the current string is present # in the concatenated string or not if (str_cat.find(curr_str)) : return True return False # Driver codeif __name__ == "__main__" : n = 4 mat = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] if (isPermutedMatrix(mat, n)): print("Yes") else : print("No") # This code is contributed by Ryuga
// C# program to check if all rows of a matrix// are rotations of each otherusing System; class GFG{ //static int MAX = 1000; // Returns true if all rows of mat[0..n-1,0..n-1] // are rotations of each other. static bool isPermutedMatrix(int [,]mat, int n) { // Creating a string that contains // elements of first row. string str_cat = ""; for (int i = 0; i < n; i++) { str_cat = str_cat + "-" + mat[0,i].ToString(); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings string curr_str = ""; for (int j = 0; j < n; j++) { curr_str = curr_str + "-" + mat[i,j].ToString(); } // Check if the current string is present in // the concatenated string or not if (str_cat.Equals(curr_str)) { return false; } } return true; } // Driver code static void Main() { int n = 4; int [,]mat = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; if (isPermutedMatrix(mat, n)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} /* This code contributed by mits */
<?php// PHP program to check if all rows of a// matrix are rotations of each other$MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.function isPermutedMatrix( &$mat, $n){ // Creating a string that contains // elements of first row. $str_cat = ""; for ($i = 0 ; $i < $n ; $i++) $str_cat = $str_cat . "-" . strval($mat[0][$i]); // Concatenating the string with itself // so that substring search operations // can be performed on this $str_cat = $str_cat . $str_cat; // Start traversing remaining rows for ($i = 1; $i < $n; $i++) { // Store the matrix into vector // in the form of strings $curr_str = ""; for ($j = 0 ; $j < $n ; $j++) $curr_str = $curr_str . "-" . strval($mat[$i][$j]); // Check if the current string is present // in the concatenated string or not if (strpos($str_cat, $curr_str)) return true; } return false;} // Driver Code$n = 4;$mat = array(array(1, 2, 3, 4), array(4, 1, 2, 3), array(3, 4, 1, 2), array(2, 3, 4, 1));if (isPermutedMatrix($mat, $n)) echo "Yes";else echo "No"; // This code is contributed by ita_c?>
<script> // Javascript program to check if all rows of a matrix// are rotations of each other // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.function isPermutedMatrix(mat, n){ // Creating a string that contains // elements of first row. let str_cat = ""; for (let i = 0; i < n; i++) { str_cat = str_cat + "-" + (mat[0][i]).toString(); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for(let i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings let curr_str = ""; for(let j = 0; j < n; j++) { curr_str = curr_str + "-" + (mat[i][j]).toString(); } // Check if the current string is present in // the concatenated string or not if (str_cat.includes(curr_str)) { return true; } } return false;} // Drivers codelet n = 4;let mat = [ [ 1, 2, 3, 4 ], [ 4, 1, 2, 3 ], [ 3, 4, 1, 2 ], [ 2, 3, 4, 1 ] ]; if (isPermutedMatrix(mat, n)) document.write("Yes")else document.write("No") // This code is contributed by rag2127 </script>
Yes
Time complexity : O(n3) Auxiliary Space : O(n)
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
ankthon
ukasp
princiraj1992
Mithun Kumar
rag2127
codewithmini
hardikkoriintern
rotation
Matrix
Strings
Strings
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 165,
"s": 54,
"text": "Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. "
},
{
"code": null,
"e": 176,
"s": 165,
"text": "Examples: "
},
{
"code": null,
"e": 484,
"s": 176,
"text": "Input: mat[][] = 1, 2, 3\n 3, 1, 2\n 2, 3, 1\nOutput: Yes\nAll rows are rotated permutation\nof each other.\n\nInput: mat[3][3] = 1, 2, 3\n 3, 2, 1\n 1, 3, 2\nOutput: No\nExplanation : As 3, 2, 1 is not a rotated or \ncircular permutation of 1, 2, 3"
},
{
"code": null,
"e": 585,
"s": 484,
"text": "The idea is based on below article. A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 595,
"s": 585,
"text": "Steps : "
},
{
"code": null,
"e": 941,
"s": 595,
"text": "Create a string of first row elements and concatenate the string with itself so that string search operations can be efficiently performed. Let this string be str_cat.Traverse all remaining rows. For every row being traversed, create a string str_curr of current row elements. If str_curr is not a substring of str_cat, return false.Return true."
},
{
"code": null,
"e": 1109,
"s": 941,
"text": "Create a string of first row elements and concatenate the string with itself so that string search operations can be efficiently performed. Let this string be str_cat."
},
{
"code": null,
"e": 1276,
"s": 1109,
"text": "Traverse all remaining rows. For every row being traversed, create a string str_curr of current row elements. If str_curr is not a substring of str_cat, return false."
},
{
"code": null,
"e": 1289,
"s": 1276,
"text": "Return true."
},
{
"code": null,
"e": 1334,
"s": 1289,
"text": "Below is the implementation of above steps. "
},
{
"code": null,
"e": 1338,
"s": 1334,
"text": "C++"
},
{
"code": null,
"e": 1343,
"s": 1338,
"text": "Java"
},
{
"code": null,
"e": 1351,
"s": 1343,
"text": "Python3"
},
{
"code": null,
"e": 1354,
"s": 1351,
"text": "C#"
},
{
"code": null,
"e": 1358,
"s": 1354,
"text": "PHP"
},
{
"code": null,
"e": 1369,
"s": 1358,
"text": "Javascript"
},
{
"code": "// C++ program to check if all rows of a matrix// are rotations of each other#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.bool isPermutedMatrix( int mat[MAX][MAX], int n){ // Creating a string that contains elements of first // row. string str_cat = \"\"; for (int i = 0 ; i < n ; i++) str_cat = str_cat + \"-\" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i<n; i++) { // Store the matrix into vector in the form // of strings string curr_str = \"\"; for (int j = 0 ; j < n ; j++) curr_str = curr_str + \"-\" + to_string(mat[i][j]); // Check if the current string is present in // the concatenated string or not if (str_cat.find(curr_str) == string::npos) return false; } return true;} // Drivers codeint main(){ int n = 4 ; int mat[MAX][MAX] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; isPermutedMatrix(mat, n)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 2684,
"s": 1369,
"text": null
},
{
"code": "// Java program to check if all rows of a matrix// are rotations of each otherclass GFG{ static int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. static boolean isPermutedMatrix(int mat[][], int n) { // Creating a string that contains // elements of first row. String str_cat = \"\"; for (int i = 0; i < n; i++) { str_cat = str_cat + \"-\" + String.valueOf(mat[0][i]); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings String curr_str = \"\"; for (int j = 0; j < n; j++) { curr_str = curr_str + \"-\" + String.valueOf(mat[i][j]); } // Check if the current string is present in // the concatenated string or not if (str_cat.contentEquals(curr_str)) { return false; } } return true; } // Drivers code public static void main(String[] args) { int n = 4; int mat[][] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; if (isPermutedMatrix(mat, n)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} /* This code contributed by PrinciRaj1992 */",
"e": 4315,
"s": 2684,
"text": null
},
{
"code": "# Python3 program to check if all rows# of a matrix are rotations of each other MAX = 1000 # Returns true if all rows of mat[0..n-1][0..n-1]# are rotations of each other.def isPermutedMatrix(mat, n) : # Creating a string that contains # elements of first row. str_cat = \"\" for i in range(n) : str_cat = str_cat + \"-\" + str(mat[0][i]) # Concatenating the string with itself # so that substring search operations # can be performed on this str_cat = str_cat + str_cat # Start traversing remaining rows for i in range(1, n) : # Store the matrix into vector # in the form of strings curr_str = \"\" for j in range(n) : curr_str = curr_str + \"-\" + str(mat[i][j]) # Check if the current string is present # in the concatenated string or not if (str_cat.find(curr_str)) : return True return False # Driver codeif __name__ == \"__main__\" : n = 4 mat = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] if (isPermutedMatrix(mat, n)): print(\"Yes\") else : print(\"No\") # This code is contributed by Ryuga",
"e": 5531,
"s": 4315,
"text": null
},
{
"code": "// C# program to check if all rows of a matrix// are rotations of each otherusing System; class GFG{ //static int MAX = 1000; // Returns true if all rows of mat[0..n-1,0..n-1] // are rotations of each other. static bool isPermutedMatrix(int [,]mat, int n) { // Creating a string that contains // elements of first row. string str_cat = \"\"; for (int i = 0; i < n; i++) { str_cat = str_cat + \"-\" + mat[0,i].ToString(); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings string curr_str = \"\"; for (int j = 0; j < n; j++) { curr_str = curr_str + \"-\" + mat[i,j].ToString(); } // Check if the current string is present in // the concatenated string or not if (str_cat.Equals(curr_str)) { return false; } } return true; } // Driver code static void Main() { int n = 4; int [,]mat = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; if (isPermutedMatrix(mat, n)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} /* This code contributed by mits */",
"e": 7127,
"s": 5531,
"text": null
},
{
"code": "<?php// PHP program to check if all rows of a// matrix are rotations of each other$MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.function isPermutedMatrix( &$mat, $n){ // Creating a string that contains // elements of first row. $str_cat = \"\"; for ($i = 0 ; $i < $n ; $i++) $str_cat = $str_cat . \"-\" . strval($mat[0][$i]); // Concatenating the string with itself // so that substring search operations // can be performed on this $str_cat = $str_cat . $str_cat; // Start traversing remaining rows for ($i = 1; $i < $n; $i++) { // Store the matrix into vector // in the form of strings $curr_str = \"\"; for ($j = 0 ; $j < $n ; $j++) $curr_str = $curr_str . \"-\" . strval($mat[$i][$j]); // Check if the current string is present // in the concatenated string or not if (strpos($str_cat, $curr_str)) return true; } return false;} // Driver Code$n = 4;$mat = array(array(1, 2, 3, 4), array(4, 1, 2, 3), array(3, 4, 1, 2), array(2, 3, 4, 1));if (isPermutedMatrix($mat, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed by ita_c?>",
"e": 8411,
"s": 7127,
"text": null
},
{
"code": "<script> // Javascript program to check if all rows of a matrix// are rotations of each other // Returns true if all rows of mat[0..n-1][0..n-1]// are rotations of each other.function isPermutedMatrix(mat, n){ // Creating a string that contains // elements of first row. let str_cat = \"\"; for (let i = 0; i < n; i++) { str_cat = str_cat + \"-\" + (mat[0][i]).toString(); } // Concatenating the string with itself // so that substring search operations // can be performed on this str_cat = str_cat + str_cat; // Start traversing remaining rows for(let i = 1; i < n; i++) { // Store the matrix into vector in the form // of strings let curr_str = \"\"; for(let j = 0; j < n; j++) { curr_str = curr_str + \"-\" + (mat[i][j]).toString(); } // Check if the current string is present in // the concatenated string or not if (str_cat.includes(curr_str)) { return true; } } return false;} // Drivers codelet n = 4;let mat = [ [ 1, 2, 3, 4 ], [ 4, 1, 2, 3 ], [ 3, 4, 1, 2 ], [ 2, 3, 4, 1 ] ]; if (isPermutedMatrix(mat, n)) document.write(\"Yes\")else document.write(\"No\") // This code is contributed by rag2127 </script>",
"e": 9791,
"s": 8411,
"text": null
},
{
"code": null,
"e": 9795,
"s": 9791,
"text": "Yes"
},
{
"code": null,
"e": 9842,
"s": 9795,
"text": "Time complexity : O(n3) Auxiliary Space : O(n)"
},
{
"code": null,
"e": 10147,
"s": 9842,
"text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 10155,
"s": 10147,
"text": "ankthon"
},
{
"code": null,
"e": 10161,
"s": 10155,
"text": "ukasp"
},
{
"code": null,
"e": 10175,
"s": 10161,
"text": "princiraj1992"
},
{
"code": null,
"e": 10188,
"s": 10175,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10196,
"s": 10188,
"text": "rag2127"
},
{
"code": null,
"e": 10209,
"s": 10196,
"text": "codewithmini"
},
{
"code": null,
"e": 10226,
"s": 10209,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 10235,
"s": 10226,
"text": "rotation"
},
{
"code": null,
"e": 10242,
"s": 10235,
"text": "Matrix"
},
{
"code": null,
"e": 10250,
"s": 10242,
"text": "Strings"
},
{
"code": null,
"e": 10258,
"s": 10250,
"text": "Strings"
},
{
"code": null,
"e": 10265,
"s": 10258,
"text": "Matrix"
},
{
"code": null,
"e": 10363,
"s": 10265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10398,
"s": 10363,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 10442,
"s": 10398,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 10473,
"s": 10442,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 10497,
"s": 10473,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 10519,
"s": 10497,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 10565,
"s": 10519,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10590,
"s": 10565,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10650,
"s": 10590,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10665,
"s": 10650,
"text": "C++ Data Types"
}
] |
Tailwind CSS Min-Height
|
23 Mar, 2022
This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS Min-Height Property. This class is used to set the minimum height of an element. The min-height class is used when the content of the element is smaller than the min-height and if the content is larger than the min-height, it has no effect. This class ensures that the value of the height class is not less than the specified min-height value of the element in consideration.
Min-Height classes:
min-h-0
min-h-full
min-h-screen
min-h-0: This class is used to set the minimum specific height for any element.
Syntax:
<element class="min-h-0">...</element>
Example:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class="mx-48 bg-green-200 p-8"> <div class="min-h-0 bg-green-400 rounded-lg">min-h-0</div> </div></body> </html>
Output:
min-h-full: This class is used to set the minimum height of an element that is full, depending on the parent element.
Syntax:
<element class="min-h-full">...</element>
Example:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class="mx-48 h-48 bg-green-200 p-8"> <div class="min-h-full bg-green-400 rounded-lg">min-h-full</div> </div></body> </html>
Output:
min-h-screen: This class is used to make an element span the entire height of the viewport minimum.
Syntax:
<element class="min-h-screen">...</element>
Example:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class="mx-48 bg-green-200 p-8"> <div class="min-h-screen bg-green-400 rounded-lg">min-h-screen</div> </div></body> </html>
Output:
Tailwind CSS
Tailwind-Sizing
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 543,
"s": 28,
"text": "This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS Min-Height Property. This class is used to set the minimum height of an element. The min-height class is used when the content of the element is smaller than the min-height and if the content is larger than the min-height, it has no effect. This class ensures that the value of the height class is not less than the specified min-height value of the element in consideration."
},
{
"code": null,
"e": 563,
"s": 543,
"text": "Min-Height classes:"
},
{
"code": null,
"e": 571,
"s": 563,
"text": "min-h-0"
},
{
"code": null,
"e": 582,
"s": 571,
"text": "min-h-full"
},
{
"code": null,
"e": 595,
"s": 582,
"text": "min-h-screen"
},
{
"code": null,
"e": 675,
"s": 595,
"text": "min-h-0: This class is used to set the minimum specific height for any element."
},
{
"code": null,
"e": 683,
"s": 675,
"text": "Syntax:"
},
{
"code": null,
"e": 722,
"s": 683,
"text": "<element class=\"min-h-0\">...</element>"
},
{
"code": null,
"e": 731,
"s": 722,
"text": "Example:"
},
{
"code": null,
"e": 736,
"s": 731,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class=\"mx-48 bg-green-200 p-8\"> <div class=\"min-h-0 bg-green-400 rounded-lg\">min-h-0</div> </div></body> </html>",
"e": 1189,
"s": 736,
"text": null
},
{
"code": null,
"e": 1197,
"s": 1189,
"text": "Output:"
},
{
"code": null,
"e": 1315,
"s": 1197,
"text": "min-h-full: This class is used to set the minimum height of an element that is full, depending on the parent element."
},
{
"code": null,
"e": 1323,
"s": 1315,
"text": "Syntax:"
},
{
"code": null,
"e": 1365,
"s": 1323,
"text": "<element class=\"min-h-full\">...</element>"
},
{
"code": null,
"e": 1374,
"s": 1365,
"text": "Example:"
},
{
"code": null,
"e": 1379,
"s": 1374,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class=\"mx-48 h-48 bg-green-200 p-8\"> <div class=\"min-h-full bg-green-400 rounded-lg\">min-h-full</div> </div></body> </html>",
"e": 1843,
"s": 1379,
"text": null
},
{
"code": null,
"e": 1851,
"s": 1843,
"text": "Output:"
},
{
"code": null,
"e": 1951,
"s": 1851,
"text": "min-h-screen: This class is used to make an element span the entire height of the viewport minimum."
},
{
"code": null,
"e": 1959,
"s": 1951,
"text": "Syntax:"
},
{
"code": null,
"e": 2003,
"s": 1959,
"text": "<element class=\"min-h-screen\">...</element>"
},
{
"code": null,
"e": 2012,
"s": 2003,
"text": "Example:"
},
{
"code": null,
"e": 2017,
"s": 2012,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Min-Height Class</b> <div class=\"mx-48 bg-green-200 p-8\"> <div class=\"min-h-screen bg-green-400 rounded-lg\">min-h-screen</div> </div></body> </html>",
"e": 2480,
"s": 2017,
"text": null
},
{
"code": null,
"e": 2488,
"s": 2480,
"text": "Output:"
},
{
"code": null,
"e": 2501,
"s": 2488,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 2517,
"s": 2501,
"text": "Tailwind-Sizing"
},
{
"code": null,
"e": 2521,
"s": 2517,
"text": "CSS"
},
{
"code": null,
"e": 2538,
"s": 2521,
"text": "Web Technologies"
}
] |
Creating a Neural Network from Scratch | by Joao Zsigmond | Towards Data Science
|
Neural networks have been around for many years. In fact, the idea behind the algorithm was first introduced over 60 years ago by a psychologist named Frank Rosenblatt.
It wasn’t until the start of the last decade, however, that these machine learning models started getting more attention, with the publication of this paper, proving the use and effectiveness of neural networks in machine learning.
Today, neural networks are at the core of deep learning. The most complex tasks in artificial intelligence are usually in the hands of Artificial Neural Networks and there are many libraries that abstract the creation of NNs in extremely few lines of code.
In this article we will walk through the fundamental concepts behind neural networks, and understand their inner workings. We will do this by creating a flexible NN from scratch.
The full source code for this article can be found at this link! 👇👇👇
github.com
The code we will be looking at is written in javascript, however, each concept and step will be deeply documented and explained, so you can follow along with any language you like!
Neural networks are a type of algorithm that belong inside deep learning. Deep learning, for that matter, is a subclass of machine learning, that is itself a subclass of artificial intelligence.
The core idea behind machine learning is that algorithms can be trained to classify and process data without being explicitly told the rules of classification.
What this means is that instead of having a model that makes decisions based on hard coded instructions, we can train the model on a great amount of input/output pairs (the training set), and after some time, have the model come up with it’s own rules of classification for a never-before-seen given input.
This idea is valid on all machine learning algorithms.
All right — now that the basics of machine learning are out of the way, let’s move on to neural nets!
Let’s talk about the fundamental structure of a neural network. The data processing works through layers. Any network will have an input layer, a subset of hidden layers (we’ll talk about them in just a sec), and an output layer.
Each layer of a network is composed by a number of neurons, and the neurons of each layer are connected to the neurons of the next through weights.
The input layer is where the data will enter the algorithm. Say we want to create a network to predict the probability of a patient having a certain disease parting from the symptoms he has shown.
In this case, our training data will be structured as an input/output pair. The input will be an array of 0's and 1's representing the symptoms we are analyzing, and the output will be a 0 or 1, representing the infectious status of the patient that presented the ‘input’ symptoms.
If we were to train a neural network on this data, we would have to have an input layer with five neurons, one for each of the symptoms. We can have an arbitrary amount of hidden layers, with an arbitrary amount of neurons in each one, but we must have an output layer of just one neuron.
The neuron in the output layer will have an activation close to 1 when the algorithm thinks that the input represents a sick patient and close to 0 when the algorithm thinks that the input represents a non-infected patient.
You can think of the activation of a neuron as being the value that it stores. The activations of the neurons in the first layer will be the same as the values of our input data. These values will be translated on to the neurons of the following layers through mathematical operations we will check out in a bit.
The activations of the neurons in our output layer will result in our network’s prediction. (It may be just one neuron, as in the case of the example above)
(and the sigmoid function!)
Alright, you might be wondering how the data that enters the input layer transverses the network and ends up in the output layer totally different than how it came in. This process is called feedforward and the full explanation involves some linear algebra and matrix multiplications that we will look at soon. For now we’ll stick with the idea behind the process.
As we saw earlier, each neuron is connected to a neuron of the previous layer through what we called weights. What this means is that the activation of a neuron in, say, the second layer will be relative to the sum of all the activations of the neurons in the layer before it multiplied by the weights connecting them.
If we represent the activation of a neuron with the letter a and the weight connecting two neurons as w, the activation of a single neuron in the second layer may be represented as in the below image.
The equation above is actually way oversimplified for this matter. In reality this is just the first step of calculating the activation of any given neuron. The image below will introduce us to the remaining operations we must execute to find the final activation.
The two new factors that we haven’t yet looked at are: the bias, represented by the letter b; and the activation function, represented by the function g(z).
Let’s start by tackling the bias.
The idea here is that each neuron will have a unique number that will be added to the weighted sum of the the previous neurons’s activations.
Adding the bias is useful so that neural networks can generalize better to any given data. You can think about it as being the constant in a linear function y=mx+c.
Adding a bias to each neuron isn’t fundamental for a network to work properly on simple data, however, when we are tackling very complex tasks it becomes indispensable.
Now that we got down the bias, our activation equation looks something like this:
The last thing we must understand to make sense of how data transverses the network are activation functions.
Lets represent with the letter z the weighted sum of a given neuron added up with it’s bias. The activation of the neuron in question will be the result of an activation function applied to the z factor.
The activation function is used to smoothen out small changes to a neurons activation and keep it between 0 and 1. One very common activation function, and the one that we’ll be using on our own network, is the sigmoid function.
The Sigmoid is useful as an activation function because inputs way greater than 0 will quickly result in a number very close to 1, once passed through the sigmoid function. By the same principle, the smaller the input, the closer the resulting number will be to 0. Input numbers very close to 0 will have a value that smoothly oscillates between 0 and 1.
To sum it all up, we can find the activation of any neuron by adding up the weighted sum of the activations of the neurons in the previous layer with the bias, and passing this result through the sigmoid function.
The process of finding the activation of the neurons in the output layer from any given input is called feedforward. It works by finding all the activations of the neurons in the second layer from the neurons in the input layer and the weights connecting them. The activations of the neurons in the second layer are used to find the activations of the following layer, and so on until the output layer.
The weights and biases are all initialized randomly in an untrained network. The process of training a network means finding the values of these weights and biases that make the resulting output layer of any given input extremely close to the expected output.
Let’s code all of this up, and then we’ll check out how we can teach our network by tweaking these weights and biases to have an optimal performance!
||→[{[{ DISCLAIMER }]}] ←||
We won’t be using any external JS libraries throughout this article except math.js to optimize matrix operations.
All right — Now let’s start coding.
Let’s start by initializing our Network class.
To allow our network to be more flexible, and generalize better to data, we will receive the number of layers, and the number of neurons in each layer in the constructor of our class.
The idea here is that the class will be instantiated with an array. Each elements of the array represents a new layer, and the value of each element is the number of neurons in the respective layer.
To do this, we’ll represent the weights connecting each layer to the previous as a matrix. Each column of this weight matrix will represent the weights connecting all neurons of a previous layer to a single neuron in the next.
For each layer in our network we’ll have a weight matrix, and the weights will be initialized randomly with values oscillating from 0 to 1.
To simplify the code, we’ll set the bias of our network’s neurons to zero.
To recap: The weights attribute of our network will be a list of matrices. Each one of the matrices represents all the weights connecting one layer to the next.
Now that we’ve got all the weights set up, let’s code the feedforward method.
The method will receive an array with the inputs as an argument. These inputs will be mapped to the input layer of our network.
To find the resulting activation of the next layer, we can use the result of a dot product between the input activations and the weight matrix connecting the input layer to the next.
This algebraic operation is analogous to multiplying each activation of the input layer by it’s connecting weight to a neuron in the second layer and summing up these products for each neuron. We can then apply the sigmoid function to each of the resulting weighted sums in the second layer to find all the resulting activations.
These resulting activations will be dot multiplied again by the next weight matrix in our weights array, and the dot product will undergo the sigmoid function, resulting in the activations of the neurons in the following layer. This happens until the resulting activations are the activations in our output layer, hence resulting our prediction.
To implement this in code, we can loop over our weight matrix array. The loop will start by dot multiplying the inputs with the first weight matrix and applying the sigmoid function to the results. The resulting activations will then be mapped to an activation variable, that will be dot multiplied with the second layer of weights and so on.
At every iteration, we’ll update the activation variable so that the dot product between the activation and the weight matrix results in the following layer’s activation (after undergoing the sigmoid, of course).
For the code above to work, we must first code the sigmoid function. The code is pretty simple:
The full code for our network, until now, looks like this:
Right now, our network can already make predictions!!!!
... Well, not exactly.
We can already feed in some input data and receive an output prediction through the feedForward method, but our weights and biases have random values, so our predictions won’t be at all precise. Our network will be guessing blindly the results.
How can we tweak these weights and biases so that our network stops guessing and starts making ‘informed’ decisions?
The complete answer involves partial derivatives and some multivariable calculus, but for now, let’s stick to the idea behind the calculations.
The first step in making our predictions better is finding out how bad they are.
The type of functions that fulfill this task are called cost functions. There are many cost functions available, but the one we will use for our network is the mean squared error function, or MSE.
The idea behind the MSE cost function is to compare the activation of each neuron in the output layer to the expected value of that output. We will subtract our expected output value from our predicted activations and square the result for each neuron. Summing up all these squared errors will give us the final value of our cost function.
The idea here is to tweak the weights and biases of each layer to minimize the cost function. The smaller the value of the MSE, the closer our predictions are to the actual results.
Here is where the partial derivatives come in. Let’s look at it this way: Each weight and bias is a variable that acts on the cost function in some way. Any change to any weight of any layer in our network will impact our cost in some way, large or small.
If we can find the partial derivative of each weight, that is, how much a tiny change to that single weight impacts the result of the cost function, we can figure out how to change that weight to minimize our cost function for the training example at hand.
For example: If, when we calculate the partial derivative of a single weight, we see that a tiny increase in that weight will increase the cost function, we know we must decrease this weight to minimize the cost. If, on the other hand, a tiny increase of the weight decreases the cost function, we’ll know to increase this weight in order to lessen our cost.
Besides telling us rather we should increase or decrease each weight, the partial derivative will also indicate how much the weight should change. If, by applying a tiny nudge to the value of the weight, we see a significant change to our cost function, we know this is an important weight, and it’s value influences heavily our network’s cost. Therefore, we must change it significantly in order to minimize our MSE. The reciprocal is also valid.
For each training example in our training set, we’ll find the cost for the example at hand and tweak all the weights accordingly. When we go over this process thousands (if not millions) of times — once for each training example — we’ll end up with an optimized network that can make excellent predictions for any given input.
The process for finding the optimal bias for each neuron is very similar, but since our simple network will have all the biases set to zero, we won’t dive deep into the bias calculation.
Let’s get coding!
Let’s start by adding a method to our Network class that calculates the cost of a single training example.
The cost method will receive an input, output pair of our training set.
It will begin by finding the networks prediction from the given input through the feedForward method. The activations of the output layer will be stored in the activations array. We’ll now create a new array with each element being the squared error of the output neuron.
We’ll return the sum of all of the squared errors in the array.
Now we’ve gotten to the most complex part of our network. The tweaking of the weights in order to find an optimal network. The process of calculating these new weights is called back-propagation.
There are complex algorithms that figure out all the partial derivatives of the weights in our network with respect to the cost value, speeding up the training process, but for the sake of simplicity, we’ll calculate these derivatives numerically and not analytically (for now).
What this means is that we’ll choose a very small number, say 0.01, and change a given weight by this value. Then we’ll recalculate the cost function for this tweaked network, to see if we made the prediction better or worse.
The difference between the original cost and the cost after we’ve changed the weight by 0.01, divided by 0.01, is a numerical approximation of the partial derivative of this weight in relation to the cost function.
Let’s add a new method to our Network class called backProp.
For each weight of our network, we’ll calculate it’s partial derivative with respect to the cost and store the value in an array. The structure of this array will be the same structure as the array with all of our network’s weights, but instead of having each weight value, it will have each partial derivative value.
To finish off, after we’ve calculated all of our partial derivatives, we’ll iterate through our weights array and subtract from each weight its corresponding partial derivative with respect to the cost function.
By doing this, we will magnify the value of the weights that diminish the cost, and diminish the value of the weights that maximize the cost.
The backProp method will look like this:
Phew... That was a lot of stuff! But now we have the fundamental parts of our network up and running!
The last thing we have to do is create a train method to receive a bunch of input/output pairs of training data and run the back-propagation algorithm for each entry.
After training, we’ll have a network with optimized weights, ready to predict the output for any new input.
The train method will also receive an epochs value.
The epochs value represents the number of times the network should be trained on the same training data. This may be interesting when we don’t have a very large training set, or other reasons that are very well explained in this article.
The full code for our network now looks something like this:
Notice we’ve also added a predict method which just implements the feedforward method and returns the result.
Now let’s see what we can do with our network!
To prove our networks functionality, let’s train a network to classify points on a coordinate plane.
In this example, let’s draw a diagonal line transversing the plane. This line would represent the function y = x.
We’ll try to train our network to classify points as being above the line or below the line.
To do this, we’ll feed into the network 1,000 examples of points, with the correct labels for them: 0 if the point is below the line and 1 if the point is above the line.
For now, we’ll only consider points with x and y values between 0 and 1.
I’ve created a simple function to automate the process of creating the training data. The function receives the number of input/output pairs to generate and then returns the input array and the corresponding output array.
Now we can train our network like so:
In the code above, first we initialize a new network with two neurons in the input layer, a hidden layer with 5 neurons and an output layer with 1 neuron.
In the second line, we create the x and y training data.
Next, we train our network for just one epoch, with the labeled data we generated.
Lastly, to see if we’ve been able to train a precise network, we’ll check out the networks prediction on a new value, in this case (0.5; 0.1).
We expect the network to classify the output as being 0, since this point on the coordinate plane is under the line we’re evaluating.
The output for the code above is
node index.js//returns [ 0.000019314711178699818 ]
Now let’s try to predict the output for the point (0.3, 0.7). The expected value should be close to 1.
When we run the predict method, the returned value is:
[ 0.9999203743668156 ]
This is exactly the output we expected. We’ve now created a network that can classify points on the coordinate grid after being trained with 10,000 examples.
We’ve already accomplished an intriguing task: understanding the nuts and bolts of a neural network and creating one ourselves, but there is still a lot of room for improvement.
The first improvement we could make to our network is to implement the back-propagation algorithm analytically instead of numerically.
The video above is really insightful for that matter, and I highly recommend you to watch it!
Implementing back-propagation through this algorithm can exponentially boost our training times, and allow us to train more complex nets in waaaaay less time.
Another adjustment we can make to our network is adding bias values to each neuron. In the references section you can find articles that explain and implement biases on other neural nets.
Lastly, another modification we could make to our network is to train it through batches. What this means is that instead of calculating the cost and tweaking the weights for every single training example, we could calculate the mean cost for, say, 100 training examples and tweak the weights based on this value. This technique can greatly speed up our training times!
There are definitely many other things we could tweak and tinker in our network to boost performance, but I hope that this simple example may have helped you to understand the key concepts behind the algorithm!
I hope you may have found this article inspiring, and that it may have helped you in any way! 😁😁😁
neuralnetworksanddeeplearning.com
towardsdatascience.com
playground.tensorflow.org
www.kdnuggets.com
Code snippets made with https://carbon.now.sh/
|
[
{
"code": null,
"e": 341,
"s": 172,
"text": "Neural networks have been around for many years. In fact, the idea behind the algorithm was first introduced over 60 years ago by a psychologist named Frank Rosenblatt."
},
{
"code": null,
"e": 573,
"s": 341,
"text": "It wasn’t until the start of the last decade, however, that these machine learning models started getting more attention, with the publication of this paper, proving the use and effectiveness of neural networks in machine learning."
},
{
"code": null,
"e": 830,
"s": 573,
"text": "Today, neural networks are at the core of deep learning. The most complex tasks in artificial intelligence are usually in the hands of Artificial Neural Networks and there are many libraries that abstract the creation of NNs in extremely few lines of code."
},
{
"code": null,
"e": 1009,
"s": 830,
"text": "In this article we will walk through the fundamental concepts behind neural networks, and understand their inner workings. We will do this by creating a flexible NN from scratch."
},
{
"code": null,
"e": 1078,
"s": 1009,
"text": "The full source code for this article can be found at this link! 👇👇👇"
},
{
"code": null,
"e": 1089,
"s": 1078,
"text": "github.com"
},
{
"code": null,
"e": 1270,
"s": 1089,
"text": "The code we will be looking at is written in javascript, however, each concept and step will be deeply documented and explained, so you can follow along with any language you like!"
},
{
"code": null,
"e": 1465,
"s": 1270,
"text": "Neural networks are a type of algorithm that belong inside deep learning. Deep learning, for that matter, is a subclass of machine learning, that is itself a subclass of artificial intelligence."
},
{
"code": null,
"e": 1625,
"s": 1465,
"text": "The core idea behind machine learning is that algorithms can be trained to classify and process data without being explicitly told the rules of classification."
},
{
"code": null,
"e": 1932,
"s": 1625,
"text": "What this means is that instead of having a model that makes decisions based on hard coded instructions, we can train the model on a great amount of input/output pairs (the training set), and after some time, have the model come up with it’s own rules of classification for a never-before-seen given input."
},
{
"code": null,
"e": 1987,
"s": 1932,
"text": "This idea is valid on all machine learning algorithms."
},
{
"code": null,
"e": 2089,
"s": 1987,
"text": "All right — now that the basics of machine learning are out of the way, let’s move on to neural nets!"
},
{
"code": null,
"e": 2319,
"s": 2089,
"text": "Let’s talk about the fundamental structure of a neural network. The data processing works through layers. Any network will have an input layer, a subset of hidden layers (we’ll talk about them in just a sec), and an output layer."
},
{
"code": null,
"e": 2467,
"s": 2319,
"text": "Each layer of a network is composed by a number of neurons, and the neurons of each layer are connected to the neurons of the next through weights."
},
{
"code": null,
"e": 2664,
"s": 2467,
"text": "The input layer is where the data will enter the algorithm. Say we want to create a network to predict the probability of a patient having a certain disease parting from the symptoms he has shown."
},
{
"code": null,
"e": 2946,
"s": 2664,
"text": "In this case, our training data will be structured as an input/output pair. The input will be an array of 0's and 1's representing the symptoms we are analyzing, and the output will be a 0 or 1, representing the infectious status of the patient that presented the ‘input’ symptoms."
},
{
"code": null,
"e": 3235,
"s": 2946,
"text": "If we were to train a neural network on this data, we would have to have an input layer with five neurons, one for each of the symptoms. We can have an arbitrary amount of hidden layers, with an arbitrary amount of neurons in each one, but we must have an output layer of just one neuron."
},
{
"code": null,
"e": 3459,
"s": 3235,
"text": "The neuron in the output layer will have an activation close to 1 when the algorithm thinks that the input represents a sick patient and close to 0 when the algorithm thinks that the input represents a non-infected patient."
},
{
"code": null,
"e": 3772,
"s": 3459,
"text": "You can think of the activation of a neuron as being the value that it stores. The activations of the neurons in the first layer will be the same as the values of our input data. These values will be translated on to the neurons of the following layers through mathematical operations we will check out in a bit."
},
{
"code": null,
"e": 3929,
"s": 3772,
"text": "The activations of the neurons in our output layer will result in our network’s prediction. (It may be just one neuron, as in the case of the example above)"
},
{
"code": null,
"e": 3957,
"s": 3929,
"text": "(and the sigmoid function!)"
},
{
"code": null,
"e": 4322,
"s": 3957,
"text": "Alright, you might be wondering how the data that enters the input layer transverses the network and ends up in the output layer totally different than how it came in. This process is called feedforward and the full explanation involves some linear algebra and matrix multiplications that we will look at soon. For now we’ll stick with the idea behind the process."
},
{
"code": null,
"e": 4641,
"s": 4322,
"text": "As we saw earlier, each neuron is connected to a neuron of the previous layer through what we called weights. What this means is that the activation of a neuron in, say, the second layer will be relative to the sum of all the activations of the neurons in the layer before it multiplied by the weights connecting them."
},
{
"code": null,
"e": 4842,
"s": 4641,
"text": "If we represent the activation of a neuron with the letter a and the weight connecting two neurons as w, the activation of a single neuron in the second layer may be represented as in the below image."
},
{
"code": null,
"e": 5107,
"s": 4842,
"text": "The equation above is actually way oversimplified for this matter. In reality this is just the first step of calculating the activation of any given neuron. The image below will introduce us to the remaining operations we must execute to find the final activation."
},
{
"code": null,
"e": 5264,
"s": 5107,
"text": "The two new factors that we haven’t yet looked at are: the bias, represented by the letter b; and the activation function, represented by the function g(z)."
},
{
"code": null,
"e": 5298,
"s": 5264,
"text": "Let’s start by tackling the bias."
},
{
"code": null,
"e": 5440,
"s": 5298,
"text": "The idea here is that each neuron will have a unique number that will be added to the weighted sum of the the previous neurons’s activations."
},
{
"code": null,
"e": 5605,
"s": 5440,
"text": "Adding the bias is useful so that neural networks can generalize better to any given data. You can think about it as being the constant in a linear function y=mx+c."
},
{
"code": null,
"e": 5774,
"s": 5605,
"text": "Adding a bias to each neuron isn’t fundamental for a network to work properly on simple data, however, when we are tackling very complex tasks it becomes indispensable."
},
{
"code": null,
"e": 5856,
"s": 5774,
"text": "Now that we got down the bias, our activation equation looks something like this:"
},
{
"code": null,
"e": 5966,
"s": 5856,
"text": "The last thing we must understand to make sense of how data transverses the network are activation functions."
},
{
"code": null,
"e": 6170,
"s": 5966,
"text": "Lets represent with the letter z the weighted sum of a given neuron added up with it’s bias. The activation of the neuron in question will be the result of an activation function applied to the z factor."
},
{
"code": null,
"e": 6399,
"s": 6170,
"text": "The activation function is used to smoothen out small changes to a neurons activation and keep it between 0 and 1. One very common activation function, and the one that we’ll be using on our own network, is the sigmoid function."
},
{
"code": null,
"e": 6754,
"s": 6399,
"text": "The Sigmoid is useful as an activation function because inputs way greater than 0 will quickly result in a number very close to 1, once passed through the sigmoid function. By the same principle, the smaller the input, the closer the resulting number will be to 0. Input numbers very close to 0 will have a value that smoothly oscillates between 0 and 1."
},
{
"code": null,
"e": 6968,
"s": 6754,
"text": "To sum it all up, we can find the activation of any neuron by adding up the weighted sum of the activations of the neurons in the previous layer with the bias, and passing this result through the sigmoid function."
},
{
"code": null,
"e": 7371,
"s": 6968,
"text": "The process of finding the activation of the neurons in the output layer from any given input is called feedforward. It works by finding all the activations of the neurons in the second layer from the neurons in the input layer and the weights connecting them. The activations of the neurons in the second layer are used to find the activations of the following layer, and so on until the output layer."
},
{
"code": null,
"e": 7631,
"s": 7371,
"text": "The weights and biases are all initialized randomly in an untrained network. The process of training a network means finding the values of these weights and biases that make the resulting output layer of any given input extremely close to the expected output."
},
{
"code": null,
"e": 7781,
"s": 7631,
"text": "Let’s code all of this up, and then we’ll check out how we can teach our network by tweaking these weights and biases to have an optimal performance!"
},
{
"code": null,
"e": 7809,
"s": 7781,
"text": "||→[{[{ DISCLAIMER }]}] ←||"
},
{
"code": null,
"e": 7923,
"s": 7809,
"text": "We won’t be using any external JS libraries throughout this article except math.js to optimize matrix operations."
},
{
"code": null,
"e": 7959,
"s": 7923,
"text": "All right — Now let’s start coding."
},
{
"code": null,
"e": 8006,
"s": 7959,
"text": "Let’s start by initializing our Network class."
},
{
"code": null,
"e": 8190,
"s": 8006,
"text": "To allow our network to be more flexible, and generalize better to data, we will receive the number of layers, and the number of neurons in each layer in the constructor of our class."
},
{
"code": null,
"e": 8389,
"s": 8190,
"text": "The idea here is that the class will be instantiated with an array. Each elements of the array represents a new layer, and the value of each element is the number of neurons in the respective layer."
},
{
"code": null,
"e": 8616,
"s": 8389,
"text": "To do this, we’ll represent the weights connecting each layer to the previous as a matrix. Each column of this weight matrix will represent the weights connecting all neurons of a previous layer to a single neuron in the next."
},
{
"code": null,
"e": 8756,
"s": 8616,
"text": "For each layer in our network we’ll have a weight matrix, and the weights will be initialized randomly with values oscillating from 0 to 1."
},
{
"code": null,
"e": 8831,
"s": 8756,
"text": "To simplify the code, we’ll set the bias of our network’s neurons to zero."
},
{
"code": null,
"e": 8992,
"s": 8831,
"text": "To recap: The weights attribute of our network will be a list of matrices. Each one of the matrices represents all the weights connecting one layer to the next."
},
{
"code": null,
"e": 9070,
"s": 8992,
"text": "Now that we’ve got all the weights set up, let’s code the feedforward method."
},
{
"code": null,
"e": 9198,
"s": 9070,
"text": "The method will receive an array with the inputs as an argument. These inputs will be mapped to the input layer of our network."
},
{
"code": null,
"e": 9381,
"s": 9198,
"text": "To find the resulting activation of the next layer, we can use the result of a dot product between the input activations and the weight matrix connecting the input layer to the next."
},
{
"code": null,
"e": 9711,
"s": 9381,
"text": "This algebraic operation is analogous to multiplying each activation of the input layer by it’s connecting weight to a neuron in the second layer and summing up these products for each neuron. We can then apply the sigmoid function to each of the resulting weighted sums in the second layer to find all the resulting activations."
},
{
"code": null,
"e": 10057,
"s": 9711,
"text": "These resulting activations will be dot multiplied again by the next weight matrix in our weights array, and the dot product will undergo the sigmoid function, resulting in the activations of the neurons in the following layer. This happens until the resulting activations are the activations in our output layer, hence resulting our prediction."
},
{
"code": null,
"e": 10400,
"s": 10057,
"text": "To implement this in code, we can loop over our weight matrix array. The loop will start by dot multiplying the inputs with the first weight matrix and applying the sigmoid function to the results. The resulting activations will then be mapped to an activation variable, that will be dot multiplied with the second layer of weights and so on."
},
{
"code": null,
"e": 10613,
"s": 10400,
"text": "At every iteration, we’ll update the activation variable so that the dot product between the activation and the weight matrix results in the following layer’s activation (after undergoing the sigmoid, of course)."
},
{
"code": null,
"e": 10709,
"s": 10613,
"text": "For the code above to work, we must first code the sigmoid function. The code is pretty simple:"
},
{
"code": null,
"e": 10768,
"s": 10709,
"text": "The full code for our network, until now, looks like this:"
},
{
"code": null,
"e": 10824,
"s": 10768,
"text": "Right now, our network can already make predictions!!!!"
},
{
"code": null,
"e": 10847,
"s": 10824,
"text": "... Well, not exactly."
},
{
"code": null,
"e": 11092,
"s": 10847,
"text": "We can already feed in some input data and receive an output prediction through the feedForward method, but our weights and biases have random values, so our predictions won’t be at all precise. Our network will be guessing blindly the results."
},
{
"code": null,
"e": 11209,
"s": 11092,
"text": "How can we tweak these weights and biases so that our network stops guessing and starts making ‘informed’ decisions?"
},
{
"code": null,
"e": 11353,
"s": 11209,
"text": "The complete answer involves partial derivatives and some multivariable calculus, but for now, let’s stick to the idea behind the calculations."
},
{
"code": null,
"e": 11434,
"s": 11353,
"text": "The first step in making our predictions better is finding out how bad they are."
},
{
"code": null,
"e": 11631,
"s": 11434,
"text": "The type of functions that fulfill this task are called cost functions. There are many cost functions available, but the one we will use for our network is the mean squared error function, or MSE."
},
{
"code": null,
"e": 11971,
"s": 11631,
"text": "The idea behind the MSE cost function is to compare the activation of each neuron in the output layer to the expected value of that output. We will subtract our expected output value from our predicted activations and square the result for each neuron. Summing up all these squared errors will give us the final value of our cost function."
},
{
"code": null,
"e": 12153,
"s": 11971,
"text": "The idea here is to tweak the weights and biases of each layer to minimize the cost function. The smaller the value of the MSE, the closer our predictions are to the actual results."
},
{
"code": null,
"e": 12409,
"s": 12153,
"text": "Here is where the partial derivatives come in. Let’s look at it this way: Each weight and bias is a variable that acts on the cost function in some way. Any change to any weight of any layer in our network will impact our cost in some way, large or small."
},
{
"code": null,
"e": 12666,
"s": 12409,
"text": "If we can find the partial derivative of each weight, that is, how much a tiny change to that single weight impacts the result of the cost function, we can figure out how to change that weight to minimize our cost function for the training example at hand."
},
{
"code": null,
"e": 13025,
"s": 12666,
"text": "For example: If, when we calculate the partial derivative of a single weight, we see that a tiny increase in that weight will increase the cost function, we know we must decrease this weight to minimize the cost. If, on the other hand, a tiny increase of the weight decreases the cost function, we’ll know to increase this weight in order to lessen our cost."
},
{
"code": null,
"e": 13473,
"s": 13025,
"text": "Besides telling us rather we should increase or decrease each weight, the partial derivative will also indicate how much the weight should change. If, by applying a tiny nudge to the value of the weight, we see a significant change to our cost function, we know this is an important weight, and it’s value influences heavily our network’s cost. Therefore, we must change it significantly in order to minimize our MSE. The reciprocal is also valid."
},
{
"code": null,
"e": 13800,
"s": 13473,
"text": "For each training example in our training set, we’ll find the cost for the example at hand and tweak all the weights accordingly. When we go over this process thousands (if not millions) of times — once for each training example — we’ll end up with an optimized network that can make excellent predictions for any given input."
},
{
"code": null,
"e": 13987,
"s": 13800,
"text": "The process for finding the optimal bias for each neuron is very similar, but since our simple network will have all the biases set to zero, we won’t dive deep into the bias calculation."
},
{
"code": null,
"e": 14005,
"s": 13987,
"text": "Let’s get coding!"
},
{
"code": null,
"e": 14112,
"s": 14005,
"text": "Let’s start by adding a method to our Network class that calculates the cost of a single training example."
},
{
"code": null,
"e": 14184,
"s": 14112,
"text": "The cost method will receive an input, output pair of our training set."
},
{
"code": null,
"e": 14456,
"s": 14184,
"text": "It will begin by finding the networks prediction from the given input through the feedForward method. The activations of the output layer will be stored in the activations array. We’ll now create a new array with each element being the squared error of the output neuron."
},
{
"code": null,
"e": 14520,
"s": 14456,
"text": "We’ll return the sum of all of the squared errors in the array."
},
{
"code": null,
"e": 14716,
"s": 14520,
"text": "Now we’ve gotten to the most complex part of our network. The tweaking of the weights in order to find an optimal network. The process of calculating these new weights is called back-propagation."
},
{
"code": null,
"e": 14995,
"s": 14716,
"text": "There are complex algorithms that figure out all the partial derivatives of the weights in our network with respect to the cost value, speeding up the training process, but for the sake of simplicity, we’ll calculate these derivatives numerically and not analytically (for now)."
},
{
"code": null,
"e": 15221,
"s": 14995,
"text": "What this means is that we’ll choose a very small number, say 0.01, and change a given weight by this value. Then we’ll recalculate the cost function for this tweaked network, to see if we made the prediction better or worse."
},
{
"code": null,
"e": 15436,
"s": 15221,
"text": "The difference between the original cost and the cost after we’ve changed the weight by 0.01, divided by 0.01, is a numerical approximation of the partial derivative of this weight in relation to the cost function."
},
{
"code": null,
"e": 15497,
"s": 15436,
"text": "Let’s add a new method to our Network class called backProp."
},
{
"code": null,
"e": 15815,
"s": 15497,
"text": "For each weight of our network, we’ll calculate it’s partial derivative with respect to the cost and store the value in an array. The structure of this array will be the same structure as the array with all of our network’s weights, but instead of having each weight value, it will have each partial derivative value."
},
{
"code": null,
"e": 16027,
"s": 15815,
"text": "To finish off, after we’ve calculated all of our partial derivatives, we’ll iterate through our weights array and subtract from each weight its corresponding partial derivative with respect to the cost function."
},
{
"code": null,
"e": 16169,
"s": 16027,
"text": "By doing this, we will magnify the value of the weights that diminish the cost, and diminish the value of the weights that maximize the cost."
},
{
"code": null,
"e": 16210,
"s": 16169,
"text": "The backProp method will look like this:"
},
{
"code": null,
"e": 16312,
"s": 16210,
"text": "Phew... That was a lot of stuff! But now we have the fundamental parts of our network up and running!"
},
{
"code": null,
"e": 16479,
"s": 16312,
"text": "The last thing we have to do is create a train method to receive a bunch of input/output pairs of training data and run the back-propagation algorithm for each entry."
},
{
"code": null,
"e": 16587,
"s": 16479,
"text": "After training, we’ll have a network with optimized weights, ready to predict the output for any new input."
},
{
"code": null,
"e": 16639,
"s": 16587,
"text": "The train method will also receive an epochs value."
},
{
"code": null,
"e": 16877,
"s": 16639,
"text": "The epochs value represents the number of times the network should be trained on the same training data. This may be interesting when we don’t have a very large training set, or other reasons that are very well explained in this article."
},
{
"code": null,
"e": 16938,
"s": 16877,
"text": "The full code for our network now looks something like this:"
},
{
"code": null,
"e": 17048,
"s": 16938,
"text": "Notice we’ve also added a predict method which just implements the feedforward method and returns the result."
},
{
"code": null,
"e": 17095,
"s": 17048,
"text": "Now let’s see what we can do with our network!"
},
{
"code": null,
"e": 17196,
"s": 17095,
"text": "To prove our networks functionality, let’s train a network to classify points on a coordinate plane."
},
{
"code": null,
"e": 17310,
"s": 17196,
"text": "In this example, let’s draw a diagonal line transversing the plane. This line would represent the function y = x."
},
{
"code": null,
"e": 17403,
"s": 17310,
"text": "We’ll try to train our network to classify points as being above the line or below the line."
},
{
"code": null,
"e": 17574,
"s": 17403,
"text": "To do this, we’ll feed into the network 1,000 examples of points, with the correct labels for them: 0 if the point is below the line and 1 if the point is above the line."
},
{
"code": null,
"e": 17647,
"s": 17574,
"text": "For now, we’ll only consider points with x and y values between 0 and 1."
},
{
"code": null,
"e": 17869,
"s": 17647,
"text": "I’ve created a simple function to automate the process of creating the training data. The function receives the number of input/output pairs to generate and then returns the input array and the corresponding output array."
},
{
"code": null,
"e": 17907,
"s": 17869,
"text": "Now we can train our network like so:"
},
{
"code": null,
"e": 18062,
"s": 17907,
"text": "In the code above, first we initialize a new network with two neurons in the input layer, a hidden layer with 5 neurons and an output layer with 1 neuron."
},
{
"code": null,
"e": 18119,
"s": 18062,
"text": "In the second line, we create the x and y training data."
},
{
"code": null,
"e": 18202,
"s": 18119,
"text": "Next, we train our network for just one epoch, with the labeled data we generated."
},
{
"code": null,
"e": 18345,
"s": 18202,
"text": "Lastly, to see if we’ve been able to train a precise network, we’ll check out the networks prediction on a new value, in this case (0.5; 0.1)."
},
{
"code": null,
"e": 18479,
"s": 18345,
"text": "We expect the network to classify the output as being 0, since this point on the coordinate plane is under the line we’re evaluating."
},
{
"code": null,
"e": 18512,
"s": 18479,
"text": "The output for the code above is"
},
{
"code": null,
"e": 18563,
"s": 18512,
"text": "node index.js//returns [ 0.000019314711178699818 ]"
},
{
"code": null,
"e": 18666,
"s": 18563,
"text": "Now let’s try to predict the output for the point (0.3, 0.7). The expected value should be close to 1."
},
{
"code": null,
"e": 18721,
"s": 18666,
"text": "When we run the predict method, the returned value is:"
},
{
"code": null,
"e": 18744,
"s": 18721,
"text": "[ 0.9999203743668156 ]"
},
{
"code": null,
"e": 18902,
"s": 18744,
"text": "This is exactly the output we expected. We’ve now created a network that can classify points on the coordinate grid after being trained with 10,000 examples."
},
{
"code": null,
"e": 19080,
"s": 18902,
"text": "We’ve already accomplished an intriguing task: understanding the nuts and bolts of a neural network and creating one ourselves, but there is still a lot of room for improvement."
},
{
"code": null,
"e": 19215,
"s": 19080,
"text": "The first improvement we could make to our network is to implement the back-propagation algorithm analytically instead of numerically."
},
{
"code": null,
"e": 19309,
"s": 19215,
"text": "The video above is really insightful for that matter, and I highly recommend you to watch it!"
},
{
"code": null,
"e": 19468,
"s": 19309,
"text": "Implementing back-propagation through this algorithm can exponentially boost our training times, and allow us to train more complex nets in waaaaay less time."
},
{
"code": null,
"e": 19656,
"s": 19468,
"text": "Another adjustment we can make to our network is adding bias values to each neuron. In the references section you can find articles that explain and implement biases on other neural nets."
},
{
"code": null,
"e": 20026,
"s": 19656,
"text": "Lastly, another modification we could make to our network is to train it through batches. What this means is that instead of calculating the cost and tweaking the weights for every single training example, we could calculate the mean cost for, say, 100 training examples and tweak the weights based on this value. This technique can greatly speed up our training times!"
},
{
"code": null,
"e": 20237,
"s": 20026,
"text": "There are definitely many other things we could tweak and tinker in our network to boost performance, but I hope that this simple example may have helped you to understand the key concepts behind the algorithm!"
},
{
"code": null,
"e": 20335,
"s": 20237,
"text": "I hope you may have found this article inspiring, and that it may have helped you in any way! 😁😁😁"
},
{
"code": null,
"e": 20369,
"s": 20335,
"text": "neuralnetworksanddeeplearning.com"
},
{
"code": null,
"e": 20392,
"s": 20369,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 20418,
"s": 20392,
"text": "playground.tensorflow.org"
},
{
"code": null,
"e": 20436,
"s": 20418,
"text": "www.kdnuggets.com"
}
] |
Java Generics - Parameterized Types
|
A Generic class can have parameterized types where a type parameter can be substituted with a parameterized type. Following example will showcase above mentioned concept.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer, List<String>> box
= new Box<Integer, List<String>>();
List<String> messages = new ArrayList<String>();
messages.add("Hi");
messages.add("Hello");
messages.add("Bye");
box.add(Integer.valueOf(10),messages);
System.out.printf("Integer Value :%d\n", box.getFirst());
System.out.printf("String Value :%s\n", box.getSecond());
}
}
class Box<T, S> {
private T t;
private S s;
public void add(T t, S s) {
this.t = t;
this.s = s;
}
public T getFirst() {
return t;
}
public S getSecond() {
return s;
}
}
This will produce the following result.
Integer Value :10
String Value :[Hi, Hello, Bye]
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2811,
"s": 2640,
"text": "A Generic class can have parameterized types where a type parameter can be substituted with a parameterized type. Following example will showcase above mentioned concept."
},
{
"code": null,
"e": 2878,
"s": 2811,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 2898,
"s": 2878,
"text": "GenericsTester.java"
},
{
"code": null,
"e": 3711,
"s": 2898,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box<Integer, List<String>> box\n = new Box<Integer, List<String>>();\n \n List<String> messages = new ArrayList<String>();\n \n messages.add(\"Hi\");\n messages.add(\"Hello\");\n messages.add(\"Bye\"); \n \n box.add(Integer.valueOf(10),messages);\n System.out.printf(\"Integer Value :%d\\n\", box.getFirst());\n System.out.printf(\"String Value :%s\\n\", box.getSecond());\n\n \n }\n}\n\nclass Box<T, S> {\n private T t;\n private S s;\n\n public void add(T t, S s) {\n this.t = t;\n this.s = s;\n }\n\n public T getFirst() {\n return t;\n } \n\n public S getSecond() {\n return s;\n } \n}"
},
{
"code": null,
"e": 3751,
"s": 3711,
"text": "This will produce the following result."
},
{
"code": null,
"e": 3801,
"s": 3751,
"text": "Integer Value :10\nString Value :[Hi, Hello, Bye]\n"
},
{
"code": null,
"e": 3834,
"s": 3801,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3834,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3883,
"s": 3850,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3899,
"s": 3883,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3934,
"s": 3899,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3948,
"s": 3934,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3982,
"s": 3948,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3996,
"s": 3982,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4033,
"s": 3996,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4048,
"s": 4033,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4081,
"s": 4048,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4100,
"s": 4081,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4107,
"s": 4100,
"text": " Print"
},
{
"code": null,
"e": 4118,
"s": 4107,
"text": " Add Notes"
}
] |
Multi-label image classification with Inception net | by Radek Bartyzal | Towards Data Science
|
Update: This article has been updated to fix possible issues with accuracy calculation pointed out by Theresa Barton. The git repo has also been updated and you can find all the changes there.
Inception v3 is a deep convolutional neural network trained for single-label image classification on ImageNet data set. The TensorFlow team already prepared a tutorial on retraining it to tell apart a number of classes based on our own examples. We are going to modify the retraining script retrain.py from that tutorial to change the network into a multi-label classifier.
If you just want to jump to the resulting code, it’s here with all the necessary files and information required to make it work. From now on, I will assume that you have cloned the mentioned repository and refer to its files.
So what needs to be done? First of all, we have to somehow tell the network which are the correct labels for each image. Then we have to modify both the last layer that is being retrained and the method of evaluating the generated predictions to be actually able to train it with regard to multiple possible correct classes for each image.
TensorFlow 0.12.0-rc1
training images in JPEG format
the modified source codes with examples
Put all the training images into one folder inside images directory. Try to remove all duplicate images, they could atificially inflate the test and validation accuracy.The name of the folder does not matter. I use multi-label.
Put all the training images into one folder inside images directory. Try to remove all duplicate images, they could atificially inflate the test and validation accuracy.The name of the folder does not matter. I use multi-label.
We need to prepare files with correct labels for each image. Name the files <image_file_name.jpg>.txt = if you have an image car.jpg, the accompanying file should be named car.jpg.txt.
Put each label on a new line inside the file, nothing else.
Now copy all the created files into the image_labels_dir directory located in project root. You can change the path to this folder by editing global variable IMAGE_LABELS_DIR in retrain.py.
The original Inception net used a folder structure to derive the list of classes. In our case, all of the training images are inside one folder and we therefore need to list the classes in an external file.
Create file labels.txt in project root and fill it with all the possible labels. Each label on a new line, nothing else. Just like an image_label file for an image that is in all the possible classes.
The main() method originally loaded the directory structure containing images for each label in separate folders and created a validation, testing and training sets for each class by:
image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,cFLAGS.validation_percentage)
We now have all the images inside one directory and therefore the image_lists.keys() contains only one element and that is the folder with all of our images (e.g. multi-label). All the training images are split into validation, testing and training sets accessible through this key.
Now that we have our data correctly split up, we just need to load the list of labels and calculate the class count:
with open(ALL_LABELS_FILE) as f: labels = f.read().splitlines()class_count = len(labels)
Add get_image_labels_path() method which is just slightly edited get_image_path() method returning a path to a file containing correct image labels = e.g. image_labels_dir/car.jpg.txt for car.jpg.Edit get_random_cached_bottlenecks() method:
Add get_image_labels_path() method which is just slightly edited get_image_path() method returning a path to a file containing correct image labels = e.g. image_labels_dir/car.jpg.txt for car.jpg.
Edit get_random_cached_bottlenecks() method:
This method creates the ground_truth vectors containing the correct labels of each returned image. Originally it simply created a vector of zeroes:
ground_truth = np.zeros(class_count, dtype=np.float32)
and then put a 1.0 in a position of the correct label, which we knew, because it is the name of the folder we took the image from:
ground_truth[label_index] = 1.0
It’s not that simple with multi-label classification. We will need to load all the correct labels for the given image from its image_label_file.
Get a path to the file with correct labels:
labels_file = get_image_labels_path(image_lists,label_name,image_index, IMAGE_LABELS_DIR, category)
Read all lines = labels from file and save them into an array true_labels:
with open(labels_file) as f: true_labels = f.read().splitlines()
Initialize the ground_truth vector with zeroes:
ground_truth = np.zeros(class_count, dtype=np.float32)
Indicate the correct labels in the ground_truth vector with 1.0:
idx = 0for label in labels: if label in true_labels: ground_truth[idx] = 1.0 idx += 1
The labels list is an added parameter to the get_random_cached_bottlenecks() method and contains names of all the possible classes.
That’s it! We can improve this solution by caching the created ground_truths. That prevents creating the ground_truth vector every time we request it for the same image, which is bound to happen if we train for multiple epochs. That is what the global dictionary CACHED_GROUND_TRUTH_VECTORS is for.
The add_final_training_ops() method originally added a new softmax and fully-connected layer for training. We just need to replace the softmax function with a different one.
Why?
The softmax function squashes all values of a vector into a range of [0,1] summing together to 1. Which is exactly what we want in a single-label classification. But for our multi-label case, we would like our resulting class probabilities to be able to express that an image of a car belongs to class car with 90% probability and to class accident with 30% probability etc.
We will achieve that by using for example sigmoid function.
Specifically we will replace:
final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
with:
final_tensor = tf.nn.sigmoid(logits, name=final_tensor_name)
We also have to update the way cross entropy is calculated to properly train our network:
Again, simply replace softmax with sigmoid:
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits,ground_truth_input)
The method add_evaluation_step() inserts the operations we need to evaluate the accuracy of the predicted labels. Originally it looked like this:
correct_prediction = tf.equal(tf.argmax(result_tensor, 1), tf.argmax(ground_truth_tensor, 1))
Okay, what is happening here?
Both result_tensor and ground_truth_tensor can be imagined as 2D arrays:
| | label1 | label2 | label3 || image1 | 0 | 1 | 0 || image2 | 1 | 0 | 0 |
Therefore this line:
tf.argmax(result_tensor, 1)
returns index of the maximal value in each row. Each row because of the (axis = 1) parameter.
We will get the indices with the highest values and compare them, while knowing that because only one label can be correct the ground_truth_tensor contains only one 1 in each row.
To adapt this approach to our multi-label case we simply replace the argmax() with round() which turns the probabilities into 0 and 1. Then we compare the result_tensor with ground_truth_tensor already containing only the 0 and 1:
correct_prediction = tf.equal(tf.round(result_tensor), ground_truth_tensor)
That’s all the changes we need to do to properly classify images with multiple labels.
Simply run this command from project root:
python retrain.py \--bottleneck_dir=bottlenecks \--how_many_training_steps 500 \--model_dir=model_dir \--output_graph=retrained_graph.pb \--output_labels=retrained_labels.txt \--summaries_dir=retrain_logs \--image_dir=images
I recommend playing with the number of training steps to prevent overfitting your model.
Run:
python label_image.py <image_name>
I slightly modified the label_image.py to write out the resulting class percentages into results.txt.
After the retraining is done you can view the logs by running:
tensorboard --logdir retrain_logs
and navigating to http://127.0.0.1:6006/ in your browser.
I hope that I made all the changes and reasons behind them as clear as possible and that you learned something new today :)
If you have further questions, you can find me on linkedin or email me directly.
|
[
{
"code": null,
"e": 364,
"s": 171,
"text": "Update: This article has been updated to fix possible issues with accuracy calculation pointed out by Theresa Barton. The git repo has also been updated and you can find all the changes there."
},
{
"code": null,
"e": 738,
"s": 364,
"text": "Inception v3 is a deep convolutional neural network trained for single-label image classification on ImageNet data set. The TensorFlow team already prepared a tutorial on retraining it to tell apart a number of classes based on our own examples. We are going to modify the retraining script retrain.py from that tutorial to change the network into a multi-label classifier."
},
{
"code": null,
"e": 964,
"s": 738,
"text": "If you just want to jump to the resulting code, it’s here with all the necessary files and information required to make it work. From now on, I will assume that you have cloned the mentioned repository and refer to its files."
},
{
"code": null,
"e": 1304,
"s": 964,
"text": "So what needs to be done? First of all, we have to somehow tell the network which are the correct labels for each image. Then we have to modify both the last layer that is being retrained and the method of evaluating the generated predictions to be actually able to train it with regard to multiple possible correct classes for each image."
},
{
"code": null,
"e": 1326,
"s": 1304,
"text": "TensorFlow 0.12.0-rc1"
},
{
"code": null,
"e": 1357,
"s": 1326,
"text": "training images in JPEG format"
},
{
"code": null,
"e": 1397,
"s": 1357,
"text": "the modified source codes with examples"
},
{
"code": null,
"e": 1625,
"s": 1397,
"text": "Put all the training images into one folder inside images directory. Try to remove all duplicate images, they could atificially inflate the test and validation accuracy.The name of the folder does not matter. I use multi-label."
},
{
"code": null,
"e": 1853,
"s": 1625,
"text": "Put all the training images into one folder inside images directory. Try to remove all duplicate images, they could atificially inflate the test and validation accuracy.The name of the folder does not matter. I use multi-label."
},
{
"code": null,
"e": 2038,
"s": 1853,
"text": "We need to prepare files with correct labels for each image. Name the files <image_file_name.jpg>.txt = if you have an image car.jpg, the accompanying file should be named car.jpg.txt."
},
{
"code": null,
"e": 2098,
"s": 2038,
"text": "Put each label on a new line inside the file, nothing else."
},
{
"code": null,
"e": 2288,
"s": 2098,
"text": "Now copy all the created files into the image_labels_dir directory located in project root. You can change the path to this folder by editing global variable IMAGE_LABELS_DIR in retrain.py."
},
{
"code": null,
"e": 2495,
"s": 2288,
"text": "The original Inception net used a folder structure to derive the list of classes. In our case, all of the training images are inside one folder and we therefore need to list the classes in an external file."
},
{
"code": null,
"e": 2696,
"s": 2495,
"text": "Create file labels.txt in project root and fill it with all the possible labels. Each label on a new line, nothing else. Just like an image_label file for an image that is in all the possible classes."
},
{
"code": null,
"e": 2880,
"s": 2696,
"text": "The main() method originally loaded the directory structure containing images for each label in separate folders and created a validation, testing and training sets for each class by:"
},
{
"code": null,
"e": 2985,
"s": 2880,
"text": "image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,cFLAGS.validation_percentage)"
},
{
"code": null,
"e": 3268,
"s": 2985,
"text": "We now have all the images inside one directory and therefore the image_lists.keys() contains only one element and that is the folder with all of our images (e.g. multi-label). All the training images are split into validation, testing and training sets accessible through this key."
},
{
"code": null,
"e": 3385,
"s": 3268,
"text": "Now that we have our data correctly split up, we just need to load the list of labels and calculate the class count:"
},
{
"code": null,
"e": 3477,
"s": 3385,
"text": "with open(ALL_LABELS_FILE) as f: labels = f.read().splitlines()class_count = len(labels)"
},
{
"code": null,
"e": 3718,
"s": 3477,
"text": "Add get_image_labels_path() method which is just slightly edited get_image_path() method returning a path to a file containing correct image labels = e.g. image_labels_dir/car.jpg.txt for car.jpg.Edit get_random_cached_bottlenecks() method:"
},
{
"code": null,
"e": 3915,
"s": 3718,
"text": "Add get_image_labels_path() method which is just slightly edited get_image_path() method returning a path to a file containing correct image labels = e.g. image_labels_dir/car.jpg.txt for car.jpg."
},
{
"code": null,
"e": 3960,
"s": 3915,
"text": "Edit get_random_cached_bottlenecks() method:"
},
{
"code": null,
"e": 4108,
"s": 3960,
"text": "This method creates the ground_truth vectors containing the correct labels of each returned image. Originally it simply created a vector of zeroes:"
},
{
"code": null,
"e": 4163,
"s": 4108,
"text": "ground_truth = np.zeros(class_count, dtype=np.float32)"
},
{
"code": null,
"e": 4294,
"s": 4163,
"text": "and then put a 1.0 in a position of the correct label, which we knew, because it is the name of the folder we took the image from:"
},
{
"code": null,
"e": 4326,
"s": 4294,
"text": "ground_truth[label_index] = 1.0"
},
{
"code": null,
"e": 4471,
"s": 4326,
"text": "It’s not that simple with multi-label classification. We will need to load all the correct labels for the given image from its image_label_file."
},
{
"code": null,
"e": 4515,
"s": 4471,
"text": "Get a path to the file with correct labels:"
},
{
"code": null,
"e": 4615,
"s": 4515,
"text": "labels_file = get_image_labels_path(image_lists,label_name,image_index, IMAGE_LABELS_DIR, category)"
},
{
"code": null,
"e": 4690,
"s": 4615,
"text": "Read all lines = labels from file and save them into an array true_labels:"
},
{
"code": null,
"e": 4757,
"s": 4690,
"text": "with open(labels_file) as f: true_labels = f.read().splitlines()"
},
{
"code": null,
"e": 4805,
"s": 4757,
"text": "Initialize the ground_truth vector with zeroes:"
},
{
"code": null,
"e": 4860,
"s": 4805,
"text": "ground_truth = np.zeros(class_count, dtype=np.float32)"
},
{
"code": null,
"e": 4925,
"s": 4860,
"text": "Indicate the correct labels in the ground_truth vector with 1.0:"
},
{
"code": null,
"e": 5020,
"s": 4925,
"text": "idx = 0for label in labels: if label in true_labels: ground_truth[idx] = 1.0 idx += 1"
},
{
"code": null,
"e": 5152,
"s": 5020,
"text": "The labels list is an added parameter to the get_random_cached_bottlenecks() method and contains names of all the possible classes."
},
{
"code": null,
"e": 5451,
"s": 5152,
"text": "That’s it! We can improve this solution by caching the created ground_truths. That prevents creating the ground_truth vector every time we request it for the same image, which is bound to happen if we train for multiple epochs. That is what the global dictionary CACHED_GROUND_TRUTH_VECTORS is for."
},
{
"code": null,
"e": 5625,
"s": 5451,
"text": "The add_final_training_ops() method originally added a new softmax and fully-connected layer for training. We just need to replace the softmax function with a different one."
},
{
"code": null,
"e": 5630,
"s": 5625,
"text": "Why?"
},
{
"code": null,
"e": 6005,
"s": 5630,
"text": "The softmax function squashes all values of a vector into a range of [0,1] summing together to 1. Which is exactly what we want in a single-label classification. But for our multi-label case, we would like our resulting class probabilities to be able to express that an image of a car belongs to class car with 90% probability and to class accident with 30% probability etc."
},
{
"code": null,
"e": 6065,
"s": 6005,
"text": "We will achieve that by using for example sigmoid function."
},
{
"code": null,
"e": 6095,
"s": 6065,
"text": "Specifically we will replace:"
},
{
"code": null,
"e": 6156,
"s": 6095,
"text": "final_tensor = tf.nn.softmax(logits, name=final_tensor_name)"
},
{
"code": null,
"e": 6162,
"s": 6156,
"text": "with:"
},
{
"code": null,
"e": 6223,
"s": 6162,
"text": "final_tensor = tf.nn.sigmoid(logits, name=final_tensor_name)"
},
{
"code": null,
"e": 6313,
"s": 6223,
"text": "We also have to update the way cross entropy is calculated to properly train our network:"
},
{
"code": null,
"e": 6357,
"s": 6313,
"text": "Again, simply replace softmax with sigmoid:"
},
{
"code": null,
"e": 6440,
"s": 6357,
"text": "cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits,ground_truth_input)"
},
{
"code": null,
"e": 6586,
"s": 6440,
"text": "The method add_evaluation_step() inserts the operations we need to evaluate the accuracy of the predicted labels. Originally it looked like this:"
},
{
"code": null,
"e": 6680,
"s": 6586,
"text": "correct_prediction = tf.equal(tf.argmax(result_tensor, 1), tf.argmax(ground_truth_tensor, 1))"
},
{
"code": null,
"e": 6710,
"s": 6680,
"text": "Okay, what is happening here?"
},
{
"code": null,
"e": 6783,
"s": 6710,
"text": "Both result_tensor and ground_truth_tensor can be imagined as 2D arrays:"
},
{
"code": null,
"e": 6901,
"s": 6783,
"text": "| | label1 | label2 | label3 || image1 | 0 | 1 | 0 || image2 | 1 | 0 | 0 |"
},
{
"code": null,
"e": 6922,
"s": 6901,
"text": "Therefore this line:"
},
{
"code": null,
"e": 6950,
"s": 6922,
"text": "tf.argmax(result_tensor, 1)"
},
{
"code": null,
"e": 7044,
"s": 6950,
"text": "returns index of the maximal value in each row. Each row because of the (axis = 1) parameter."
},
{
"code": null,
"e": 7224,
"s": 7044,
"text": "We will get the indices with the highest values and compare them, while knowing that because only one label can be correct the ground_truth_tensor contains only one 1 in each row."
},
{
"code": null,
"e": 7455,
"s": 7224,
"text": "To adapt this approach to our multi-label case we simply replace the argmax() with round() which turns the probabilities into 0 and 1. Then we compare the result_tensor with ground_truth_tensor already containing only the 0 and 1:"
},
{
"code": null,
"e": 7531,
"s": 7455,
"text": "correct_prediction = tf.equal(tf.round(result_tensor), ground_truth_tensor)"
},
{
"code": null,
"e": 7618,
"s": 7531,
"text": "That’s all the changes we need to do to properly classify images with multiple labels."
},
{
"code": null,
"e": 7661,
"s": 7618,
"text": "Simply run this command from project root:"
},
{
"code": null,
"e": 7886,
"s": 7661,
"text": "python retrain.py \\--bottleneck_dir=bottlenecks \\--how_many_training_steps 500 \\--model_dir=model_dir \\--output_graph=retrained_graph.pb \\--output_labels=retrained_labels.txt \\--summaries_dir=retrain_logs \\--image_dir=images"
},
{
"code": null,
"e": 7975,
"s": 7886,
"text": "I recommend playing with the number of training steps to prevent overfitting your model."
},
{
"code": null,
"e": 7980,
"s": 7975,
"text": "Run:"
},
{
"code": null,
"e": 8015,
"s": 7980,
"text": "python label_image.py <image_name>"
},
{
"code": null,
"e": 8117,
"s": 8015,
"text": "I slightly modified the label_image.py to write out the resulting class percentages into results.txt."
},
{
"code": null,
"e": 8180,
"s": 8117,
"text": "After the retraining is done you can view the logs by running:"
},
{
"code": null,
"e": 8214,
"s": 8180,
"text": "tensorboard --logdir retrain_logs"
},
{
"code": null,
"e": 8272,
"s": 8214,
"text": "and navigating to http://127.0.0.1:6006/ in your browser."
},
{
"code": null,
"e": 8396,
"s": 8272,
"text": "I hope that I made all the changes and reasons behind them as clear as possible and that you learned something new today :)"
}
] |
Count numbers in range 1 to N which are divisible by X but not by Y in C++
|
We are provided a number N. The goal is to find the numbers that are divisible by X and not by Y and are in the range [1,N].
Let’s understand with examples.
Input
N=20 X=5 Y=20
Output
Numbers from 1 to N divisible by X not Y: 2
Explanation
Only 5 and 15 are divisible by 5 and not 10.
Input
N=20 X=4 Y=7
Output
Numbers from 1 to N divisible by X not Y: 5
Explanation
Numbers 4, 8, 12, 16 and 20 are divisible by 4 and not 7.
We take an integer N.
We take an integer N.
Function divisibleXY(int x, int y, int n) returns a count of numbers from 1 to N which are divisible by X and not Y.
Function divisibleXY(int x, int y, int n) returns a count of numbers from 1 to N which are divisible by X and not Y.
Take the initial variable count as 0 for such numbers.
Take the initial variable count as 0 for such numbers.
Traverse range of numbers using for loop. i=1 to i=n
Traverse range of numbers using for loop. i=1 to i=n
Now for each number i, check if ( i%x==0 && i%y!=0 ), if true increment count.
Now for each number i, check if ( i%x==0 && i%y!=0 ), if true increment count.
Return the count as result.
Return the count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int divisibleXY(int x, int y, int n){
int count = 0;
for (int i = 1; i <= n; i++) {
if(i%x==0 && i%y!=0 )
{ count++; }
}
return count;
}
int main(){
int N = 100;
int X=6, Y=8;
cout <<"Numbers from 1 to N which are divisible by X and not Y: "<< divisibleXY(X,Y,N);
return 0;
}
If we run the above code it will generate the following output −
Numbers from 1 to N which are divisible by X and not Y: 12
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "We are provided a number N. The goal is to find the numbers that are divisible by X and not by Y and are in the range [1,N]."
},
{
"code": null,
"e": 1219,
"s": 1187,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1226,
"s": 1219,
"text": "Input "
},
{
"code": null,
"e": 1240,
"s": 1226,
"text": "N=20 X=5 Y=20"
},
{
"code": null,
"e": 1248,
"s": 1240,
"text": "Output "
},
{
"code": null,
"e": 1292,
"s": 1248,
"text": "Numbers from 1 to N divisible by X not Y: 2"
},
{
"code": null,
"e": 1305,
"s": 1292,
"text": "Explanation "
},
{
"code": null,
"e": 1350,
"s": 1305,
"text": "Only 5 and 15 are divisible by 5 and not 10."
},
{
"code": null,
"e": 1357,
"s": 1350,
"text": "Input "
},
{
"code": null,
"e": 1370,
"s": 1357,
"text": "N=20 X=4 Y=7"
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Output "
},
{
"code": null,
"e": 1422,
"s": 1378,
"text": "Numbers from 1 to N divisible by X not Y: 5"
},
{
"code": null,
"e": 1435,
"s": 1422,
"text": "Explanation "
},
{
"code": null,
"e": 1493,
"s": 1435,
"text": "Numbers 4, 8, 12, 16 and 20 are divisible by 4 and not 7."
},
{
"code": null,
"e": 1515,
"s": 1493,
"text": "We take an integer N."
},
{
"code": null,
"e": 1537,
"s": 1515,
"text": "We take an integer N."
},
{
"code": null,
"e": 1654,
"s": 1537,
"text": "Function divisibleXY(int x, int y, int n) returns a count of numbers from 1 to N which are divisible by X and not Y."
},
{
"code": null,
"e": 1771,
"s": 1654,
"text": "Function divisibleXY(int x, int y, int n) returns a count of numbers from 1 to N which are divisible by X and not Y."
},
{
"code": null,
"e": 1826,
"s": 1771,
"text": "Take the initial variable count as 0 for such numbers."
},
{
"code": null,
"e": 1881,
"s": 1826,
"text": "Take the initial variable count as 0 for such numbers."
},
{
"code": null,
"e": 1934,
"s": 1881,
"text": "Traverse range of numbers using for loop. i=1 to i=n"
},
{
"code": null,
"e": 1987,
"s": 1934,
"text": "Traverse range of numbers using for loop. i=1 to i=n"
},
{
"code": null,
"e": 2066,
"s": 1987,
"text": "Now for each number i, check if ( i%x==0 && i%y!=0 ), if true increment count."
},
{
"code": null,
"e": 2145,
"s": 2066,
"text": "Now for each number i, check if ( i%x==0 && i%y!=0 ), if true increment count."
},
{
"code": null,
"e": 2173,
"s": 2145,
"text": "Return the count as result."
},
{
"code": null,
"e": 2201,
"s": 2173,
"text": "Return the count as result."
},
{
"code": null,
"e": 2212,
"s": 2201,
"text": " Live Demo"
},
{
"code": null,
"e": 2573,
"s": 2212,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint divisibleXY(int x, int y, int n){\n int count = 0;\n for (int i = 1; i <= n; i++) {\n if(i%x==0 && i%y!=0 )\n { count++; }\n }\n return count;\n}\nint main(){\n int N = 100;\n int X=6, Y=8;\n cout <<\"Numbers from 1 to N which are divisible by X and not Y: \"<< divisibleXY(X,Y,N);\n return 0;\n}"
},
{
"code": null,
"e": 2638,
"s": 2573,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2697,
"s": 2638,
"text": "Numbers from 1 to N which are divisible by X and not Y: 12"
}
] |
Java program to swap two integers
|
Read integers from users using the nextInt() method of the Scanner class.
To swap them −
Create a variable (temp), initialize it with 0.
Assign 1st number to temp.
Assign 2nd number to 1st number.
Assign temp to second number.
import java.util.Scanner;
public class SwapTwoNumbers {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number :: ");
int num1 = sc.nextInt();
System.out.println("Enter second number :: ");
int num2 = sc.nextInt();
int temp = 0;
temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping ::");
System.out.println("Value of first number ::"+ num1);
System.out.println("Value of first number ::"+ num2);
}
}
Enter first number ::
22
Enter second number ::
33
After swapping ::
Value of first number ::33
Value of first number ::22
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "Read integers from users using the nextInt() method of the Scanner class."
},
{
"code": null,
"e": 1151,
"s": 1136,
"text": "To swap them −"
},
{
"code": null,
"e": 1199,
"s": 1151,
"text": "Create a variable (temp), initialize it with 0."
},
{
"code": null,
"e": 1226,
"s": 1199,
"text": "Assign 1st number to temp."
},
{
"code": null,
"e": 1259,
"s": 1226,
"text": "Assign 2nd number to 1st number."
},
{
"code": null,
"e": 1289,
"s": 1259,
"text": "Assign temp to second number."
},
{
"code": null,
"e": 1851,
"s": 1289,
"text": "import java.util.Scanner;\npublic class SwapTwoNumbers {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number :: \");\n int num1 = sc.nextInt();\n System.out.println(\"Enter second number :: \");\n int num2 = sc.nextInt();\n\n int temp = 0;\n temp = num1;\n num1 = num2;\n num2 = temp;\n\n System.out.println(\"After swapping ::\");\n System.out.println(\"Value of first number ::\"+ num1);\n System.out.println(\"Value of first number ::\"+ num2);\n }\n}"
},
{
"code": null,
"e": 1974,
"s": 1851,
"text": "Enter first number ::\n22\nEnter second number ::\n33\nAfter swapping ::\nValue of first number ::33\nValue of first number ::22"
}
] |
Part 1: Using YouTube’s Python API for Data Science | by Pres Nichols | Towards Data Science
|
Last week, I wrote a quick guide to using Google’s Speech Recognition API, which I described as “kinda-sorta-really confusing.” Well, guess what? Their YouTube Data API isn’t super clear either.
If you’re an expert coder with decades of experience, you can probably stop reading right now. However, if you’re an intermediate or self-taught programmer (like myself), this guide should help provide a jump-start to using YouTube for data science.
In the interest of time and overall readability, I’ve decided to break this tutorial into multiple parts. In part one, we will focus on getting the API library installed and authenticated, in addition to making simple keyword queries.
The parts to come will focus on other types of tasks, like comment collection, geographic queries and working with channels.
To complete this tutorial, you’ll need the following tools:
Python 2.7
A Google account
1) Clone the GitHub repository
git clone https://github.com/spnichol/youtube_tutorial.gitcd youtube_tutorial
2) Installing YouTube Official Python Client Library
pip install --upgrade google-api-python-client
3) Activating YouTube API
Note:In order to complete this step, you need to have a “project” created. If you’re unsure how to do this, check out my Speech Recognition tutorial for a quick guide.
Head over to the Google Cloud Console, click the hamburger menu on the top left-hand corner and select “API Manager”.
Select “YouTube Data API” from the YouTube APIs.
Click “Enable”
Click “Credentials” from the left-hand navigation panel and select “Create credentials.” You’ll want to choose API key from the drop-down list. You should see a message that says “API key created” with the alphanumeric API key. Copy and save this in a safe place!
Open youtube_videos.py in your code editor. This is a heavily modified version of YouTube’s sample code.
Replace the DEVELOPER_KEY variable on the 5th line with the API key we created earlier and save the file.
DEVELOPER_KEY = "REPLACETHISWITHYOURKEY_GOTIT?"
Cool, cool, cool. We’re ready to start writing the code to do our keyword queries. Go ahead and create a new python script and save it in the same directory.
We want to be able to use the functions in the youtube_search.py file where we saved our API key. One way to do this is by appending that directory to our Python path.
1) Append directory to Python path
import syssys.path.append("/home/your_name/youtube_tutorial/")
2) Import youtube_search function
Now that we have our path set, we can introduce the youtube_search function from the youtube_videos.py file with a simple import statement.
from youtube_videos.py import youtube_search
Let’s also import the json library, since it will come in handy when parsing the JSON output of the API.
import json
Great. We’re ready to try a quick keyword search with our youtube_search function.
4) Test out youtube_search function.
Let’s assume we love fidget spinners (we don’t) and we want to see what videos YouTube has about them.
test = youtube_search("spinners")test
Your output should look like this:
The output of our youtube_search is a tuple of len = 2. The first item is some weird six-character string. The second item is a bunch of JSON. Let's ignore the weird six-character string for a bit and select only the JSON.
just_json = test[1]len(just_json)
Now you should have this:
Now we can see we have a JSON object of len = 50. Each item is a YouTube video with details about that video, such as the ID, title, date published, thumbnail URL, duration, etc.
Let’s say we want to get the title of a video, we can easily loop through and parse it with the JSON library.
for video in just_json: print video['snippet']['title']
This gives us:
Fidget spinner pizza? Huh?
Ok, onward. Now, we figured out earlier that our output consisted of 50 distinct videos. That’s great and all — certainly way more videos about spinners than I’m interested in watching — but, that couldn’t be all of them, right?
Right. If we want more than 50 videos, which is the maximum we can get in one request, we have to ask for another round of 50. We can do this by using that weird six-character string we saw earlier ... also known as a token.
If we send the token with the next request, YouTube will know where it left off, and send us the next 50 most-relevant results. Let’s try.
token = test[0]youtube_search("spinners", token=token)
Now we have:
Awesome. Fifty more videos about spinners. Also, if you noticed, we got another token. If we want to keep going, we just rinse and repeat with that token.
Obviously doing it this way would really suck. Instead, we can write a function to automate the process a bit.
Instantiate a dictionary to store results
Instantiate a dictionary to store results
Before we write our function, let’s instantiate a dictionary outside of it with the variable names we want to save.
video_dict = {'youID':[], 'title':[], 'pub_date':[]}
2) Define our function
We can name our function grab_videos and add two parameters. The first is the keyword, while the second is an optional parameter for the token.
def grab_videos(keyword, token=None):
3) Add youtube_search and save our variables
Just like before, we’ll do a simple search with the youtube_search function and save our token and JSON results separately.
res = youtube_search(keyword)token = res[0]videos = res[1]
4) Loop through results, append to dictionary & return token
for vid in videos: video_dict['youID'].append(vid['id']['videoId']) video_dict['title'].append(vid['snippet']['title']) video_dict['pub_date'].append(vid['snippet']['publishedAt'])print "added " + str(len(videos)) + " videos to a total of " + str(len(video_dict['youID']))return token
I also added a little print statement here to update us on the number of videos we have collected each time the function is called.
Finally, we return the token so we can use it the next time we call the function.
5) Call function with while statement
Now that we’ve written the function, we can write a few short lines of code to put it to work.
First, we’ll call the function with our keyword, saving the results to the variable token.
We can then use a while statement to check if the function returned a valid token (i.e. there are more results) or if we’ve hoovered up everything. If it sees “last_page”, it will stop the execution of the code.
token = grab_videos("spinners")while token != "last_page": token = grab_videos("spinners", token=token)
Output should look like this:
Alright, now you’re at least in part ready to start doing your own data collection on YouTube.
If this article was helpful, please let me know via e-mail or in the comments section. If not, I’ll take up some other hobby! Stayed tuned for parts two and three.
|
[
{
"code": null,
"e": 366,
"s": 171,
"text": "Last week, I wrote a quick guide to using Google’s Speech Recognition API, which I described as “kinda-sorta-really confusing.” Well, guess what? Their YouTube Data API isn’t super clear either."
},
{
"code": null,
"e": 616,
"s": 366,
"text": "If you’re an expert coder with decades of experience, you can probably stop reading right now. However, if you’re an intermediate or self-taught programmer (like myself), this guide should help provide a jump-start to using YouTube for data science."
},
{
"code": null,
"e": 851,
"s": 616,
"text": "In the interest of time and overall readability, I’ve decided to break this tutorial into multiple parts. In part one, we will focus on getting the API library installed and authenticated, in addition to making simple keyword queries."
},
{
"code": null,
"e": 976,
"s": 851,
"text": "The parts to come will focus on other types of tasks, like comment collection, geographic queries and working with channels."
},
{
"code": null,
"e": 1036,
"s": 976,
"text": "To complete this tutorial, you’ll need the following tools:"
},
{
"code": null,
"e": 1047,
"s": 1036,
"text": "Python 2.7"
},
{
"code": null,
"e": 1064,
"s": 1047,
"text": "A Google account"
},
{
"code": null,
"e": 1095,
"s": 1064,
"text": "1) Clone the GitHub repository"
},
{
"code": null,
"e": 1173,
"s": 1095,
"text": "git clone https://github.com/spnichol/youtube_tutorial.gitcd youtube_tutorial"
},
{
"code": null,
"e": 1226,
"s": 1173,
"text": "2) Installing YouTube Official Python Client Library"
},
{
"code": null,
"e": 1273,
"s": 1226,
"text": "pip install --upgrade google-api-python-client"
},
{
"code": null,
"e": 1299,
"s": 1273,
"text": "3) Activating YouTube API"
},
{
"code": null,
"e": 1467,
"s": 1299,
"text": "Note:In order to complete this step, you need to have a “project” created. If you’re unsure how to do this, check out my Speech Recognition tutorial for a quick guide."
},
{
"code": null,
"e": 1585,
"s": 1467,
"text": "Head over to the Google Cloud Console, click the hamburger menu on the top left-hand corner and select “API Manager”."
},
{
"code": null,
"e": 1634,
"s": 1585,
"text": "Select “YouTube Data API” from the YouTube APIs."
},
{
"code": null,
"e": 1649,
"s": 1634,
"text": "Click “Enable”"
},
{
"code": null,
"e": 1913,
"s": 1649,
"text": "Click “Credentials” from the left-hand navigation panel and select “Create credentials.” You’ll want to choose API key from the drop-down list. You should see a message that says “API key created” with the alphanumeric API key. Copy and save this in a safe place!"
},
{
"code": null,
"e": 2018,
"s": 1913,
"text": "Open youtube_videos.py in your code editor. This is a heavily modified version of YouTube’s sample code."
},
{
"code": null,
"e": 2124,
"s": 2018,
"text": "Replace the DEVELOPER_KEY variable on the 5th line with the API key we created earlier and save the file."
},
{
"code": null,
"e": 2173,
"s": 2124,
"text": "DEVELOPER_KEY = \"REPLACETHISWITHYOURKEY_GOTIT?\" "
},
{
"code": null,
"e": 2331,
"s": 2173,
"text": "Cool, cool, cool. We’re ready to start writing the code to do our keyword queries. Go ahead and create a new python script and save it in the same directory."
},
{
"code": null,
"e": 2499,
"s": 2331,
"text": "We want to be able to use the functions in the youtube_search.py file where we saved our API key. One way to do this is by appending that directory to our Python path."
},
{
"code": null,
"e": 2534,
"s": 2499,
"text": "1) Append directory to Python path"
},
{
"code": null,
"e": 2597,
"s": 2534,
"text": "import syssys.path.append(\"/home/your_name/youtube_tutorial/\")"
},
{
"code": null,
"e": 2631,
"s": 2597,
"text": "2) Import youtube_search function"
},
{
"code": null,
"e": 2771,
"s": 2631,
"text": "Now that we have our path set, we can introduce the youtube_search function from the youtube_videos.py file with a simple import statement."
},
{
"code": null,
"e": 2816,
"s": 2771,
"text": "from youtube_videos.py import youtube_search"
},
{
"code": null,
"e": 2921,
"s": 2816,
"text": "Let’s also import the json library, since it will come in handy when parsing the JSON output of the API."
},
{
"code": null,
"e": 2933,
"s": 2921,
"text": "import json"
},
{
"code": null,
"e": 3016,
"s": 2933,
"text": "Great. We’re ready to try a quick keyword search with our youtube_search function."
},
{
"code": null,
"e": 3053,
"s": 3016,
"text": "4) Test out youtube_search function."
},
{
"code": null,
"e": 3156,
"s": 3053,
"text": "Let’s assume we love fidget spinners (we don’t) and we want to see what videos YouTube has about them."
},
{
"code": null,
"e": 3194,
"s": 3156,
"text": "test = youtube_search(\"spinners\")test"
},
{
"code": null,
"e": 3229,
"s": 3194,
"text": "Your output should look like this:"
},
{
"code": null,
"e": 3452,
"s": 3229,
"text": "The output of our youtube_search is a tuple of len = 2. The first item is some weird six-character string. The second item is a bunch of JSON. Let's ignore the weird six-character string for a bit and select only the JSON."
},
{
"code": null,
"e": 3486,
"s": 3452,
"text": "just_json = test[1]len(just_json)"
},
{
"code": null,
"e": 3512,
"s": 3486,
"text": "Now you should have this:"
},
{
"code": null,
"e": 3691,
"s": 3512,
"text": "Now we can see we have a JSON object of len = 50. Each item is a YouTube video with details about that video, such as the ID, title, date published, thumbnail URL, duration, etc."
},
{
"code": null,
"e": 3801,
"s": 3691,
"text": "Let’s say we want to get the title of a video, we can easily loop through and parse it with the JSON library."
},
{
"code": null,
"e": 3860,
"s": 3801,
"text": "for video in just_json: print video['snippet']['title']"
},
{
"code": null,
"e": 3875,
"s": 3860,
"text": "This gives us:"
},
{
"code": null,
"e": 3902,
"s": 3875,
"text": "Fidget spinner pizza? Huh?"
},
{
"code": null,
"e": 4131,
"s": 3902,
"text": "Ok, onward. Now, we figured out earlier that our output consisted of 50 distinct videos. That’s great and all — certainly way more videos about spinners than I’m interested in watching — but, that couldn’t be all of them, right?"
},
{
"code": null,
"e": 4356,
"s": 4131,
"text": "Right. If we want more than 50 videos, which is the maximum we can get in one request, we have to ask for another round of 50. We can do this by using that weird six-character string we saw earlier ... also known as a token."
},
{
"code": null,
"e": 4495,
"s": 4356,
"text": "If we send the token with the next request, YouTube will know where it left off, and send us the next 50 most-relevant results. Let’s try."
},
{
"code": null,
"e": 4550,
"s": 4495,
"text": "token = test[0]youtube_search(\"spinners\", token=token)"
},
{
"code": null,
"e": 4563,
"s": 4550,
"text": "Now we have:"
},
{
"code": null,
"e": 4718,
"s": 4563,
"text": "Awesome. Fifty more videos about spinners. Also, if you noticed, we got another token. If we want to keep going, we just rinse and repeat with that token."
},
{
"code": null,
"e": 4829,
"s": 4718,
"text": "Obviously doing it this way would really suck. Instead, we can write a function to automate the process a bit."
},
{
"code": null,
"e": 4871,
"s": 4829,
"text": "Instantiate a dictionary to store results"
},
{
"code": null,
"e": 4913,
"s": 4871,
"text": "Instantiate a dictionary to store results"
},
{
"code": null,
"e": 5029,
"s": 4913,
"text": "Before we write our function, let’s instantiate a dictionary outside of it with the variable names we want to save."
},
{
"code": null,
"e": 5082,
"s": 5029,
"text": "video_dict = {'youID':[], 'title':[], 'pub_date':[]}"
},
{
"code": null,
"e": 5105,
"s": 5082,
"text": "2) Define our function"
},
{
"code": null,
"e": 5249,
"s": 5105,
"text": "We can name our function grab_videos and add two parameters. The first is the keyword, while the second is an optional parameter for the token."
},
{
"code": null,
"e": 5287,
"s": 5249,
"text": "def grab_videos(keyword, token=None):"
},
{
"code": null,
"e": 5332,
"s": 5287,
"text": "3) Add youtube_search and save our variables"
},
{
"code": null,
"e": 5456,
"s": 5332,
"text": "Just like before, we’ll do a simple search with the youtube_search function and save our token and JSON results separately."
},
{
"code": null,
"e": 5515,
"s": 5456,
"text": "res = youtube_search(keyword)token = res[0]videos = res[1]"
},
{
"code": null,
"e": 5576,
"s": 5515,
"text": "4) Loop through results, append to dictionary & return token"
},
{
"code": null,
"e": 5865,
"s": 5576,
"text": "for vid in videos: video_dict['youID'].append(vid['id']['videoId']) video_dict['title'].append(vid['snippet']['title']) video_dict['pub_date'].append(vid['snippet']['publishedAt'])print \"added \" + str(len(videos)) + \" videos to a total of \" + str(len(video_dict['youID']))return token "
},
{
"code": null,
"e": 5997,
"s": 5865,
"text": "I also added a little print statement here to update us on the number of videos we have collected each time the function is called."
},
{
"code": null,
"e": 6079,
"s": 5997,
"text": "Finally, we return the token so we can use it the next time we call the function."
},
{
"code": null,
"e": 6117,
"s": 6079,
"text": "5) Call function with while statement"
},
{
"code": null,
"e": 6212,
"s": 6117,
"text": "Now that we’ve written the function, we can write a few short lines of code to put it to work."
},
{
"code": null,
"e": 6303,
"s": 6212,
"text": "First, we’ll call the function with our keyword, saving the results to the variable token."
},
{
"code": null,
"e": 6515,
"s": 6303,
"text": "We can then use a while statement to check if the function returned a valid token (i.e. there are more results) or if we’ve hoovered up everything. If it sees “last_page”, it will stop the execution of the code."
},
{
"code": null,
"e": 6622,
"s": 6515,
"text": "token = grab_videos(\"spinners\")while token != \"last_page\": token = grab_videos(\"spinners\", token=token)"
},
{
"code": null,
"e": 6652,
"s": 6622,
"text": "Output should look like this:"
},
{
"code": null,
"e": 6747,
"s": 6652,
"text": "Alright, now you’re at least in part ready to start doing your own data collection on YouTube."
}
] |
Difference between Direct and Indirect Addressing Modes - GeeksforGeeks
|
04 May, 2020
Prerequisite: Addressing Modes
1. Direct Addressing Mode:In direct addressing mode, address field in the instruction contains the effective address of the operand and no intermediate memory access is required. Now a days it is rarely used.
Example:Add the content of R1 and 1001 and store back to R1:
Add R1, (1001)
Here 1001 is the address where operand is stored.
2. Indirect Addressing Mode:In Indirect addressing mode, address field in the instruction contains the memory location or register where effective address of operand is present. It requires two memory access. It is further classified into two categories: Register Indirect, and Memory Indirect.
Example:
LOAD R1, @500
Above instruction is used to load the content of memory location stored at memory location 500 to register R1. In other words we can say, effective address is stored at memory location 500.
Difference between Direct and Indirect Addressing Modes:
pp_pankaj
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Computer Organization | RISC and CISC
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
|
[
{
"code": null,
"e": 24626,
"s": 24598,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 24657,
"s": 24626,
"text": "Prerequisite: Addressing Modes"
},
{
"code": null,
"e": 24866,
"s": 24657,
"text": "1. Direct Addressing Mode:In direct addressing mode, address field in the instruction contains the effective address of the operand and no intermediate memory access is required. Now a days it is rarely used."
},
{
"code": null,
"e": 24927,
"s": 24866,
"text": "Example:Add the content of R1 and 1001 and store back to R1:"
},
{
"code": null,
"e": 24943,
"s": 24927,
"text": "Add R1, (1001) "
},
{
"code": null,
"e": 24993,
"s": 24943,
"text": "Here 1001 is the address where operand is stored."
},
{
"code": null,
"e": 25288,
"s": 24993,
"text": "2. Indirect Addressing Mode:In Indirect addressing mode, address field in the instruction contains the memory location or register where effective address of operand is present. It requires two memory access. It is further classified into two categories: Register Indirect, and Memory Indirect."
},
{
"code": null,
"e": 25297,
"s": 25288,
"text": "Example:"
},
{
"code": null,
"e": 25311,
"s": 25297,
"text": "LOAD R1, @500"
},
{
"code": null,
"e": 25501,
"s": 25311,
"text": "Above instruction is used to load the content of memory location stored at memory location 500 to register R1. In other words we can say, effective address is stored at memory location 500."
},
{
"code": null,
"e": 25558,
"s": 25501,
"text": "Difference between Direct and Indirect Addressing Modes:"
},
{
"code": null,
"e": 25568,
"s": 25558,
"text": "pp_pankaj"
},
{
"code": null,
"e": 25605,
"s": 25568,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 25613,
"s": 25605,
"text": "GATE CS"
},
{
"code": null,
"e": 25711,
"s": 25613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25760,
"s": 25711,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 25855,
"s": 25760,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 25903,
"s": 25855,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 25952,
"s": 25903,
"text": "Computer Organization | Von Neumann architecture"
},
{
"code": null,
"e": 25990,
"s": 25952,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 26010,
"s": 25990,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 26034,
"s": 26010,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 26047,
"s": 26034,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 26096,
"s": 26047,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
pwdx - Unix, Linux Command
|
pwdx pids...
pwdx -V
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10601,
"s": 10579,
"text": "pwdx pids...\npwdx -V\n"
},
{
"code": null,
"e": 10628,
"s": 10611,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 10663,
"s": 10628,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 10691,
"s": 10663,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10725,
"s": 10691,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10742,
"s": 10725,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10775,
"s": 10742,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10786,
"s": 10775,
"text": " Pradeep D"
},
{
"code": null,
"e": 10821,
"s": 10786,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10837,
"s": 10821,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 10870,
"s": 10837,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10882,
"s": 10870,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 10914,
"s": 10882,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10922,
"s": 10914,
"text": " Uplatz"
},
{
"code": null,
"e": 10929,
"s": 10922,
"text": " Print"
},
{
"code": null,
"e": 10940,
"s": 10929,
"text": " Add Notes"
}
] |
How to detect airplane mode is on or off in Android?
|
This example demonstrates about How to detect airplane mode is on or off in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
checkAirplaneMode();
}
private void checkAirplaneMode() {
if (isAirplaneModeOn(getApplicationContext())) {
textView.setText("Airplane Mode is Enabled");
} else {
textView.setText("Airplane Mode is Disabled");
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates about How to detect airplane mode is on or off in Android"
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1843,
"s": 1340,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:gravity=\"center\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1900,
"s": 1843,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2818,
"s": 1900,
"text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.provider.Settings;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n checkAirplaneMode();\n }\n private void checkAirplaneMode() {\n if (isAirplaneModeOn(getApplicationContext())) {\n textView.setText(\"Airplane Mode is Enabled\");\n } else {\n textView.setText(\"Airplane Mode is Disabled\");\n }\n }\n private static boolean isAirplaneModeOn(Context context) {\n return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;\n }\n}"
},
{
"code": null,
"e": 2873,
"s": 2818,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3543,
"s": 2873,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3890,
"s": 3543,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3931,
"s": 3890,
"text": "Click here to download the project code."
}
] |
ios manipulators boolalpha() function in C++ - GeeksforGeeks
|
28 Aug, 2019
The boolalpha() method of stream manipulators in C++ is used to set the boolalpha format flag for the specified str stream.
Syntax:
ios_base& boolalpha (ios_base& str)
Parameters: This method accepts str as a a parameter which is the stream for which the format flag is affected.
Return Value: This method returns the stream str with boolalpha format flag set.
Example 1:
// C++ code to demonstrate// the working of boolalpha() function #include <iostream> using namespace std; int main(){ // Initializing the boolean flag bool flag = true; // Using boolalpha() cout << "boolalpha flag: " << boolalpha << flag << endl; return 0;}
boolalpha flag: true
Example 2:
// C++ code to demonstrate// the working of boolalpha() function #include <iostream> using namespace std; int main(){ // Initializing the boolean flag bool flag = false; // Using boolalpha() cout << "boolalpha flag: " << boolalpha << flag << endl; return 0;}
boolalpha flag: false
Reference: http://www.cplusplus.com/reference/ios/boolalpha/
cpp-ios
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
|
[
{
"code": null,
"e": 24369,
"s": 24341,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 24493,
"s": 24369,
"text": "The boolalpha() method of stream manipulators in C++ is used to set the boolalpha format flag for the specified str stream."
},
{
"code": null,
"e": 24501,
"s": 24493,
"text": "Syntax:"
},
{
"code": null,
"e": 24538,
"s": 24501,
"text": "ios_base& boolalpha (ios_base& str)\n"
},
{
"code": null,
"e": 24650,
"s": 24538,
"text": "Parameters: This method accepts str as a a parameter which is the stream for which the format flag is affected."
},
{
"code": null,
"e": 24731,
"s": 24650,
"text": "Return Value: This method returns the stream str with boolalpha format flag set."
},
{
"code": null,
"e": 24742,
"s": 24731,
"text": "Example 1:"
},
{
"code": "// C++ code to demonstrate// the working of boolalpha() function #include <iostream> using namespace std; int main(){ // Initializing the boolean flag bool flag = true; // Using boolalpha() cout << \"boolalpha flag: \" << boolalpha << flag << endl; return 0;}",
"e": 25032,
"s": 24742,
"text": null
},
{
"code": null,
"e": 25054,
"s": 25032,
"text": "boolalpha flag: true\n"
},
{
"code": null,
"e": 25065,
"s": 25054,
"text": "Example 2:"
},
{
"code": "// C++ code to demonstrate// the working of boolalpha() function #include <iostream> using namespace std; int main(){ // Initializing the boolean flag bool flag = false; // Using boolalpha() cout << \"boolalpha flag: \" << boolalpha << flag << endl; return 0;}",
"e": 25356,
"s": 25065,
"text": null
},
{
"code": null,
"e": 25379,
"s": 25356,
"text": "boolalpha flag: false\n"
},
{
"code": null,
"e": 25440,
"s": 25379,
"text": "Reference: http://www.cplusplus.com/reference/ios/boolalpha/"
},
{
"code": null,
"e": 25448,
"s": 25440,
"text": "cpp-ios"
},
{
"code": null,
"e": 25465,
"s": 25448,
"text": "cpp-manipulators"
},
{
"code": null,
"e": 25469,
"s": 25465,
"text": "C++"
},
{
"code": null,
"e": 25473,
"s": 25469,
"text": "CPP"
},
{
"code": null,
"e": 25571,
"s": 25473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25580,
"s": 25571,
"text": "Comments"
},
{
"code": null,
"e": 25593,
"s": 25580,
"text": "Old Comments"
},
{
"code": null,
"e": 25636,
"s": 25593,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25655,
"s": 25636,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 25679,
"s": 25655,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 25699,
"s": 25679,
"text": "Constructors in C++"
},
{
"code": null,
"e": 25726,
"s": 25699,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 25754,
"s": 25726,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 25782,
"s": 25754,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25817,
"s": 25782,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25841,
"s": 25817,
"text": "Copy Constructor in C++"
}
] |
Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap(), is_heap, is_heap_until() - GeeksforGeeks
|
17 Feb, 2021
Heap data structure can be implemented in a range using STL which allows faster input into heap and retrieval of a number always results in the largest number i.e. largest number of the remaining numbers is popped out each time. Other numbers of the heap are arranged depending upon the implementation.
Operations on heap :
1. make_heap() :- This function is used to convert a range in a container to a heap.
2. front() :- This function displays the first element of heap which is the maximum number.
// C++ code to demonstrate the working of // make_heap(), front()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << "The maximum element of heap is : "; cout << v1.front() << endl; return 0;}
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The maximum element of heap is : 40
3. push_heap() :- This function is used to insert elements into heap. The size of the heap is increased by 1. New element is placed appropriately in the heap.
4. pop_heap() :- This function is used to delete the maximum element of the heap. The size of heap is decreased by 1. The heap elements are reorganised accordingly after this operation.
// C++ code to demonstrate the working of // push_heap() and pop_heap()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << "The maximum element of heap is : "; cout << v1.front() << endl; // using push_back() to enter element // in vector v1.push_back(50); // using push_heap() to reorder elements push_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << "The maximum element of heap after push is : "; cout << v1.front() << endl; // using pop_heap() to delete maximum element pop_heap(v1.begin(), v1.end()); v1.pop_back(); // Displaying the maximum element of heap // using front() cout << "The maximum element of heap after pop is : "; cout << v1.front() << endl; return 0;}
Output:
The maximum element of heap is : 40
The maximum element of heap after push is : 50
The maximum element of heap after pop is : 40
5. sort_heap() :- This function is used to sort the heap. After this operation, the container is no longer a heap.
// C++ code to demonstrate the working of // sort_heap()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying heap elements cout << "The heap elements are : "; for (int &x : v1) cout << x << " "; cout << endl; // sorting heap using sort_heap() sort_heap(v1.begin(), v1.end()); // Displaying heap elements cout << "The heap elements after sorting are : "; for (int &x : v1) cout << x << " "; return 0;}
Output:
The heap elements are : 40 30 20 25 15
The heap elements after sorting are : 15 20 25 30 40
6. is_heap() :- This function is used to check whether the container is heap or not. Generally, in most implementations, the reverse sorted container is considered as heap. Returns true if container is heap else returns false.
6. is_heap_until() :- This function returns the iterator to the position till the container is the heap. Generally, in most implementations, the reverse sorted container is considered as heap.
// C++ code to demonstrate the working of // is_heap() and is_heap_until()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {40, 30, 25, 35, 15}; // Declaring heap iterator vector<int>::iterator it1; // Checking if container is heap // using is_heap() is_heap(v1.begin(), v1.end())? cout << "The container is heap ": cout << "The container is not heap"; cout << endl; // using is_heap_until() to check position // till which container is heap auto it = is_heap_until(v1.begin(), v1.end()); // Displaying heap range elements cout << "The heap elements in container are : "; for (it1=v1.begin(); it1!=it; it1++) cout << *it1 << " "; return 0;}
Output:
The container is not heap
The heap elements in container are : 40 30 25
YouTubeGeeksforGeeks507K subscribersC++ Programming Language Tutorial | Heap in C++ STL | GeeksforGeeksWatch laterShareCopy link21/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=BtZIpzxjQf4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SamirKhan
CPP-Library
STL
C++
Heap
Heap
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
Insertion and Deletion in Heaps
Building Heap from Array
|
[
{
"code": null,
"e": 25411,
"s": 25383,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 25714,
"s": 25411,
"text": "Heap data structure can be implemented in a range using STL which allows faster input into heap and retrieval of a number always results in the largest number i.e. largest number of the remaining numbers is popped out each time. Other numbers of the heap are arranged depending upon the implementation."
},
{
"code": null,
"e": 25735,
"s": 25714,
"text": "Operations on heap :"
},
{
"code": null,
"e": 25820,
"s": 25735,
"text": "1. make_heap() :- This function is used to convert a range in a container to a heap."
},
{
"code": null,
"e": 25912,
"s": 25820,
"text": "2. front() :- This function displays the first element of heap which is the maximum number."
},
{
"code": "// C++ code to demonstrate the working of // make_heap(), front()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << \"The maximum element of heap is : \"; cout << v1.front() << endl; return 0;}",
"e": 26381,
"s": 25912,
"text": null
},
{
"code": null,
"e": 26389,
"s": 26381,
"text": "Output:"
},
{
"code": null,
"e": 26398,
"s": 26389,
"text": "Chapters"
},
{
"code": null,
"e": 26425,
"s": 26398,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 26475,
"s": 26425,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 26498,
"s": 26475,
"text": "captions off, selected"
},
{
"code": null,
"e": 26506,
"s": 26498,
"text": "English"
},
{
"code": null,
"e": 26530,
"s": 26506,
"text": "This is a modal window."
},
{
"code": null,
"e": 26599,
"s": 26530,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 26621,
"s": 26599,
"text": "End of dialog window."
},
{
"code": null,
"e": 26658,
"s": 26621,
"text": "The maximum element of heap is : 40\n"
},
{
"code": null,
"e": 26819,
"s": 26660,
"text": "3. push_heap() :- This function is used to insert elements into heap. The size of the heap is increased by 1. New element is placed appropriately in the heap."
},
{
"code": null,
"e": 27005,
"s": 26819,
"text": "4. pop_heap() :- This function is used to delete the maximum element of the heap. The size of heap is decreased by 1. The heap elements are reorganised accordingly after this operation."
},
{
"code": "// C++ code to demonstrate the working of // push_heap() and pop_heap()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << \"The maximum element of heap is : \"; cout << v1.front() << endl; // using push_back() to enter element // in vector v1.push_back(50); // using push_heap() to reorder elements push_heap(v1.begin(), v1.end()); // Displaying the maximum element of heap // using front() cout << \"The maximum element of heap after push is : \"; cout << v1.front() << endl; // using pop_heap() to delete maximum element pop_heap(v1.begin(), v1.end()); v1.pop_back(); // Displaying the maximum element of heap // using front() cout << \"The maximum element of heap after pop is : \"; cout << v1.front() << endl; return 0;}",
"e": 28080,
"s": 27005,
"text": null
},
{
"code": null,
"e": 28088,
"s": 28080,
"text": "Output:"
},
{
"code": null,
"e": 28218,
"s": 28088,
"text": "The maximum element of heap is : 40\nThe maximum element of heap after push is : 50\nThe maximum element of heap after pop is : 40\n"
},
{
"code": null,
"e": 28333,
"s": 28218,
"text": "5. sort_heap() :- This function is used to sort the heap. After this operation, the container is no longer a heap."
},
{
"code": "// C++ code to demonstrate the working of // sort_heap()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {20, 30, 40, 25, 15}; // Converting vector into a heap // using make_heap() make_heap(v1.begin(), v1.end()); // Displaying heap elements cout << \"The heap elements are : \"; for (int &x : v1) cout << x << \" \"; cout << endl; // sorting heap using sort_heap() sort_heap(v1.begin(), v1.end()); // Displaying heap elements cout << \"The heap elements after sorting are : \"; for (int &x : v1) cout << x << \" \"; return 0;}",
"e": 29000,
"s": 28333,
"text": null
},
{
"code": null,
"e": 29008,
"s": 29000,
"text": "Output:"
},
{
"code": null,
"e": 29103,
"s": 29008,
"text": "The heap elements are : 40 30 20 25 15 \nThe heap elements after sorting are : 15 20 25 30 40 \n"
},
{
"code": null,
"e": 29332,
"s": 29105,
"text": "6. is_heap() :- This function is used to check whether the container is heap or not. Generally, in most implementations, the reverse sorted container is considered as heap. Returns true if container is heap else returns false."
},
{
"code": null,
"e": 29525,
"s": 29332,
"text": "6. is_heap_until() :- This function returns the iterator to the position till the container is the heap. Generally, in most implementations, the reverse sorted container is considered as heap."
},
{
"code": "// C++ code to demonstrate the working of // is_heap() and is_heap_until()#include<bits/stdc++.h> using namespace std;int main(){ // Initializing a vector vector<int> v1 = {40, 30, 25, 35, 15}; // Declaring heap iterator vector<int>::iterator it1; // Checking if container is heap // using is_heap() is_heap(v1.begin(), v1.end())? cout << \"The container is heap \": cout << \"The container is not heap\"; cout << endl; // using is_heap_until() to check position // till which container is heap auto it = is_heap_until(v1.begin(), v1.end()); // Displaying heap range elements cout << \"The heap elements in container are : \"; for (it1=v1.begin(); it1!=it; it1++) cout << *it1 << \" \"; return 0;}",
"e": 30306,
"s": 29525,
"text": null
},
{
"code": null,
"e": 30314,
"s": 30306,
"text": "Output:"
},
{
"code": null,
"e": 30388,
"s": 30314,
"text": "The container is not heap\nThe heap elements in container are : 40 30 25 \n"
},
{
"code": null,
"e": 31543,
"s": 30388,
"text": "YouTubeGeeksforGeeks507K subscribersC++ Programming Language Tutorial | Heap in C++ STL | GeeksforGeeksWatch laterShareCopy link21/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:25•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=BtZIpzxjQf4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31668,
"s": 31543,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31678,
"s": 31668,
"text": "SamirKhan"
},
{
"code": null,
"e": 31690,
"s": 31678,
"text": "CPP-Library"
},
{
"code": null,
"e": 31694,
"s": 31690,
"text": "STL"
},
{
"code": null,
"e": 31698,
"s": 31694,
"text": "C++"
},
{
"code": null,
"e": 31703,
"s": 31698,
"text": "Heap"
},
{
"code": null,
"e": 31708,
"s": 31703,
"text": "Heap"
},
{
"code": null,
"e": 31712,
"s": 31708,
"text": "STL"
},
{
"code": null,
"e": 31716,
"s": 31712,
"text": "CPP"
},
{
"code": null,
"e": 31814,
"s": 31716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31833,
"s": 31814,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31876,
"s": 31833,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31900,
"s": 31876,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 31924,
"s": 31900,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 31951,
"s": 31924,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 31982,
"s": 31951,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 32038,
"s": 31982,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 32082,
"s": 32038,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 32114,
"s": 32082,
"text": "Insertion and Deletion in Heaps"
}
] |
iomanip setiosflags() function in C++ with Examples - GeeksforGeeks
|
10 Jun, 2021
The setiosflags() method of iomanip library in C++ is used to set the ios library format flags specified as the parameter to this method.Syntax:
setiosflags (ios_base::format_flag)
Parameters: This method accepts format_flag as a parameter which is the ios library format flag to be set by this method.Return Value: This method does not returns anything. It only acts as stream manipulators.Example 1:
CPP
// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; // Using setiosflags() cout << "Setting showbase flag " << "using setiosflags: \n" << hex << setiosflags(ios::showbase) << num << endl; return 0;}
Setting showbase flag using setiosflags:
0x32
Example 2:
CPP
// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; // Using setiosflags() cout << "Setting showbase and uppercase" << " flag using setiosflags: \n" << hex << setiosflags( ios::showbase | ios::uppercase) << num << endl; return 0;}
Setting showbase and uppercase flag using setiosflags:
0X32
Reference: http://www.cplusplus.com/reference/iomanip/setiosflags/
kumud544131
CPP-Functions
cpp-input-output
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++
Substring in C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 26039,
"s": 26011,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 26186,
"s": 26039,
"text": "The setiosflags() method of iomanip library in C++ is used to set the ios library format flags specified as the parameter to this method.Syntax: "
},
{
"code": null,
"e": 26222,
"s": 26186,
"text": "setiosflags (ios_base::format_flag)"
},
{
"code": null,
"e": 26444,
"s": 26222,
"text": "Parameters: This method accepts format_flag as a parameter which is the ios library format flag to be set by this method.Return Value: This method does not returns anything. It only acts as stream manipulators.Example 1: "
},
{
"code": null,
"e": 26448,
"s": 26444,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; // Using setiosflags() cout << \"Setting showbase flag \" << \"using setiosflags: \\n\" << hex << setiosflags(ios::showbase) << num << endl; return 0;}",
"e": 26839,
"s": 26448,
"text": null
},
{
"code": null,
"e": 26886,
"s": 26839,
"text": "Setting showbase flag using setiosflags: \n0x32"
},
{
"code": null,
"e": 26900,
"s": 26888,
"text": "Example 2: "
},
{
"code": null,
"e": 26904,
"s": 26900,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; // Using setiosflags() cout << \"Setting showbase and uppercase\" << \" flag using setiosflags: \\n\" << hex << setiosflags( ios::showbase | ios::uppercase) << num << endl; return 0;}",
"e": 27357,
"s": 26904,
"text": null
},
{
"code": null,
"e": 27418,
"s": 27357,
"text": "Setting showbase and uppercase flag using setiosflags: \n0X32"
},
{
"code": null,
"e": 27488,
"s": 27420,
"text": "Reference: http://www.cplusplus.com/reference/iomanip/setiosflags/ "
},
{
"code": null,
"e": 27500,
"s": 27488,
"text": "kumud544131"
},
{
"code": null,
"e": 27514,
"s": 27500,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27531,
"s": 27514,
"text": "cpp-input-output"
},
{
"code": null,
"e": 27548,
"s": 27531,
"text": "cpp-manipulators"
},
{
"code": null,
"e": 27552,
"s": 27548,
"text": "C++"
},
{
"code": null,
"e": 27556,
"s": 27552,
"text": "CPP"
},
{
"code": null,
"e": 27654,
"s": 27556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27678,
"s": 27654,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27702,
"s": 27678,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27722,
"s": 27702,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27753,
"s": 27722,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27781,
"s": 27753,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27809,
"s": 27781,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27843,
"s": 27809,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 27878,
"s": 27843,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 27895,
"s": 27878,
"text": "Substring in C++"
}
] |
HashMap merge(key, value, BiFunction) method in Java with Examples - GeeksforGeeks
|
11 Oct, 2019
The merge(Key, Value, BiFunctional) method of HashMap class is used to combine multiple mapped values for a key using the given mapping function. Bucket is actually an index of array, that array is called table in HashMap implementation. So table[0] is referred to as bucket0, table[1] as bucket1 and so on.
If the key is not present or is associated with null, it simply outputs the key along with the corresponding value in the Hashmap as a new entry.
However, if the key already holds some value that Remapping Function merges both the old and new values with the given key
In case key is null, it is always mapped to bucket 0, as hash is not calculated for null keys due to NullPointerException
Syntax:
public V merge(K key, V value,
BiFunction remappingFunction)
Parameters:This method accepts three parameters:
Key: which is the key for which we have a particular value. If two keys have the same value they are merged.
Value: which is the index corresponding to the particular key which is stored in the bucket.
BiFunction: which is the function having two arguments to be used for calculating the new mapping from the old value and given value.
Return Value: This method returns the key along with its value if the key is not present or is associated with null. ELse if the key already holds any value, it merges the old value with the new value using the mapping technique.
Below programs illustrate the merge(Key, Value, BiFunctional) method:
Program 1:
// Java program to demonstrate// computeIfAbsent(Key, Function) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<Integer, String> map1 = new HashMap<>(); map1.put(1, "L"); map1.put(2, "M"); map1.put(3, "N"); HashMap<Integer, String> map2 = new HashMap<>(); map2.put(1, "B"); map2.put(2, "G"); map2.put(3, "R"); // print map details System.out.println("HashMap1: " + map1.toString()); System.out.println("HashMap2: " + map2.toString()); // provide value for new key which is absent // using computeIfAbsent method map2.forEach( (key, value) -> map1.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + ", " + v2)); // print new mapping System.out.println("New HashMap: " + map1); }}
HashMap1: {1=L, 2=M, 3=N}
HashMap2: {1=B, 2=G, 3=R}
New HashMap: {1=L, B, 2=M, G, 3=N, R}
Program 2:
// Java program to demonstrate// computeIfAbsent(Key, Function) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<Integer, String> map1 = new HashMap<>(); map1.put(1, "Ram"); map1.put(2, "Rohan"); map1.put(3, "Shivam"); HashMap<Integer, String> map2 = new HashMap<>(); map2.put(1, "Tushar"); map2.put(10, "Satya"); map2.put(12, "Sundar"); // print map details System.out.println("HashMap1: " + map1.toString()); System.out.println("HashMap2: " + map2.toString()); // provide value for new key which is absent // using computeIfAbsent method map2.forEach( (key, value) -> map1.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + ", " + v2)); // print new mapping System.out.println("New HashMap: " + map1); }}
HashMap1: {1=Ram, 2=Rohan, 3=Shivam}
HashMap2: {1=Tushar, 10=Satya, 12=Sundar}
New HashMap: {1=Ram, Tushar, 2=Rohan, 3=Shivam, 10=Satya, 12=Sundar}
References: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#merge-K-V-java.util.function.BiFunction-
Java - util package
Java-Functions
Java-HashMap
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25831,
"s": 25803,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 26139,
"s": 25831,
"text": "The merge(Key, Value, BiFunctional) method of HashMap class is used to combine multiple mapped values for a key using the given mapping function. Bucket is actually an index of array, that array is called table in HashMap implementation. So table[0] is referred to as bucket0, table[1] as bucket1 and so on."
},
{
"code": null,
"e": 26285,
"s": 26139,
"text": "If the key is not present or is associated with null, it simply outputs the key along with the corresponding value in the Hashmap as a new entry."
},
{
"code": null,
"e": 26408,
"s": 26285,
"text": "However, if the key already holds some value that Remapping Function merges both the old and new values with the given key"
},
{
"code": null,
"e": 26530,
"s": 26408,
"text": "In case key is null, it is always mapped to bucket 0, as hash is not calculated for null keys due to NullPointerException"
},
{
"code": null,
"e": 26538,
"s": 26530,
"text": "Syntax:"
},
{
"code": null,
"e": 26604,
"s": 26538,
"text": "public V merge(K key, V value,\n BiFunction remappingFunction)\n"
},
{
"code": null,
"e": 26653,
"s": 26604,
"text": "Parameters:This method accepts three parameters:"
},
{
"code": null,
"e": 26762,
"s": 26653,
"text": "Key: which is the key for which we have a particular value. If two keys have the same value they are merged."
},
{
"code": null,
"e": 26855,
"s": 26762,
"text": "Value: which is the index corresponding to the particular key which is stored in the bucket."
},
{
"code": null,
"e": 26989,
"s": 26855,
"text": "BiFunction: which is the function having two arguments to be used for calculating the new mapping from the old value and given value."
},
{
"code": null,
"e": 27219,
"s": 26989,
"text": "Return Value: This method returns the key along with its value if the key is not present or is associated with null. ELse if the key already holds any value, it merges the old value with the new value using the mapping technique."
},
{
"code": null,
"e": 27289,
"s": 27219,
"text": "Below programs illustrate the merge(Key, Value, BiFunctional) method:"
},
{
"code": null,
"e": 27300,
"s": 27289,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// computeIfAbsent(Key, Function) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<Integer, String> map1 = new HashMap<>(); map1.put(1, \"L\"); map1.put(2, \"M\"); map1.put(3, \"N\"); HashMap<Integer, String> map2 = new HashMap<>(); map2.put(1, \"B\"); map2.put(2, \"G\"); map2.put(3, \"R\"); // print map details System.out.println(\"HashMap1: \" + map1.toString()); System.out.println(\"HashMap2: \" + map2.toString()); // provide value for new key which is absent // using computeIfAbsent method map2.forEach( (key, value) -> map1.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + \", \" + v2)); // print new mapping System.out.println(\"New HashMap: \" + map1); }}",
"e": 28485,
"s": 27300,
"text": null
},
{
"code": null,
"e": 28576,
"s": 28485,
"text": "HashMap1: {1=L, 2=M, 3=N}\nHashMap2: {1=B, 2=G, 3=R}\nNew HashMap: {1=L, B, 2=M, G, 3=N, R}\n"
},
{
"code": null,
"e": 28587,
"s": 28576,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// computeIfAbsent(Key, Function) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<Integer, String> map1 = new HashMap<>(); map1.put(1, \"Ram\"); map1.put(2, \"Rohan\"); map1.put(3, \"Shivam\"); HashMap<Integer, String> map2 = new HashMap<>(); map2.put(1, \"Tushar\"); map2.put(10, \"Satya\"); map2.put(12, \"Sundar\"); // print map details System.out.println(\"HashMap1: \" + map1.toString()); System.out.println(\"HashMap2: \" + map2.toString()); // provide value for new key which is absent // using computeIfAbsent method map2.forEach( (key, value) -> map1.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + \", \" + v2)); // print new mapping System.out.println(\"New HashMap: \" + map1); }}",
"e": 29799,
"s": 28587,
"text": null
},
{
"code": null,
"e": 29948,
"s": 29799,
"text": "HashMap1: {1=Ram, 2=Rohan, 3=Shivam}\nHashMap2: {1=Tushar, 10=Satya, 12=Sundar}\nNew HashMap: {1=Ram, Tushar, 2=Rohan, 3=Shivam, 10=Satya, 12=Sundar}\n"
},
{
"code": null,
"e": 30066,
"s": 29948,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#merge-K-V-java.util.function.BiFunction-"
},
{
"code": null,
"e": 30086,
"s": 30066,
"text": "Java - util package"
},
{
"code": null,
"e": 30101,
"s": 30086,
"text": "Java-Functions"
},
{
"code": null,
"e": 30114,
"s": 30101,
"text": "Java-HashMap"
},
{
"code": null,
"e": 30121,
"s": 30114,
"text": "Picked"
},
{
"code": null,
"e": 30126,
"s": 30121,
"text": "Java"
},
{
"code": null,
"e": 30131,
"s": 30126,
"text": "Java"
},
{
"code": null,
"e": 30229,
"s": 30131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30280,
"s": 30229,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30295,
"s": 30280,
"text": "Stream In Java"
},
{
"code": null,
"e": 30314,
"s": 30295,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30345,
"s": 30314,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30363,
"s": 30345,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30395,
"s": 30363,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30415,
"s": 30395,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30447,
"s": 30415,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30471,
"s": 30447,
"text": "Singleton Class in Java"
}
] |
Constant Propagation in Compiler Design - GeeksforGeeks
|
14 Dec, 2021
Constant Propagation is one of the local code optimization technique in Compiler Design. It can be defined as the process of replacing the constant value of variables in the expression. In simpler words, we can say that if some value is assigned a known constant, than we can simply replace the that value by constant. Constants assigned to a variable can be propagated through the flow graph and can be replaced when the variable is used.
Constant propagation is executed using reaching definition analysis results in compilers, which means that if reaching definition of all variables have same assignment which assigns a same constant to the variable, then the variable has a constant value and can be substituted with the constant.
Suppose we are using pi variable and assign it value of 22/7
pi = 22/7 = 3.14
In the above code the compiler has to first perform division operation, which is an expensive operation and then assign the computed result 3.14 to the variable pi. Now if anytime we have to use this constant value of pi, then the compiler again has to look – up for the value and again perform division operation and then assign it to pi and then use it. This is not a good idea when we can directly assign the value 3.14 to pi variable, thus reducing the time needed for code to run.
Also, Constant propagation reduces the number of cases where values are directly copied from one location or variable to another, in order to simply allocate their value to another variable. For an example :
Consider the following pseudocode :
a = 30
b = 20 - a /2
c = b * ( 30 / a + 2 ) - a
We can see that in the first expression value of a have assigned a constant value that is 30. Now, when the compiler comes to execute the second expression it encounters a, so it goes up to the first expression to look for the value of a and then assign the value of 30 to a again, and then it executes the second expression. Now it comes to the third expression and encounters b and a again, and then it needs to evaluate the first and second expression again in order to compute the value of c. Thus, a needs to be propagated 3 times This procedure is very time consuming.
We can instead , rewrite the same code as :
a = 30
b = 20 - 30/2
c = b * ( 30 / 30 + 2) - 30
This updated code is faster as compared to the previous code as the compiler does not need to again and again go back to the previous expressions looking up and copying the value of a variable in order to compute the current expressions. This saves a lot of time and thus, reducing time complexity and perform operations more efficiently.
Note that this constant propagation technique behavior depends on compiler like few compilers perform constant propagation operations within the basic blocks; while a few compilers perform constant propagation operations in more complex control flow.
as5853535
anikakapoor
Picked
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Issues in the design of a code generator
Error Handling in Compiler Design
Error detection and Recovery in Compiler
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 26108,
"s": 25665,
"text": "Constant Propagation is one of the local code optimization technique in Compiler Design. It can be defined as the process of replacing the constant value of variables in the expression. In simpler words, we can say that if some value is assigned a known constant, than we can simply replace the that value by constant. Constants assigned to a variable can be propagated through the flow graph and can be replaced when the variable is used. "
},
{
"code": null,
"e": 26405,
"s": 26108,
"text": "Constant propagation is executed using reaching definition analysis results in compilers, which means that if reaching definition of all variables have same assignment which assigns a same constant to the variable, then the variable has a constant value and can be substituted with the constant. "
},
{
"code": null,
"e": 26466,
"s": 26405,
"text": "Suppose we are using pi variable and assign it value of 22/7"
},
{
"code": null,
"e": 26483,
"s": 26466,
"text": "pi = 22/7 = 3.14"
},
{
"code": null,
"e": 26971,
"s": 26483,
"text": "In the above code the compiler has to first perform division operation, which is an expensive operation and then assign the computed result 3.14 to the variable pi. Now if anytime we have to use this constant value of pi, then the compiler again has to look – up for the value and again perform division operation and then assign it to pi and then use it. This is not a good idea when we can directly assign the value 3.14 to pi variable, thus reducing the time needed for code to run. "
},
{
"code": null,
"e": 27179,
"s": 26971,
"text": "Also, Constant propagation reduces the number of cases where values are directly copied from one location or variable to another, in order to simply allocate their value to another variable. For an example :"
},
{
"code": null,
"e": 27217,
"s": 27179,
"text": "Consider the following pseudocode : "
},
{
"code": null,
"e": 27266,
"s": 27217,
"text": "a = 30\nb = 20 - a /2\nc = b * ( 30 / a + 2 ) - a"
},
{
"code": null,
"e": 27842,
"s": 27266,
"text": "We can see that in the first expression value of a have assigned a constant value that is 30. Now, when the compiler comes to execute the second expression it encounters a, so it goes up to the first expression to look for the value of a and then assign the value of 30 to a again, and then it executes the second expression. Now it comes to the third expression and encounters b and a again, and then it needs to evaluate the first and second expression again in order to compute the value of c. Thus, a needs to be propagated 3 times This procedure is very time consuming."
},
{
"code": null,
"e": 27886,
"s": 27842,
"text": "We can instead , rewrite the same code as :"
},
{
"code": null,
"e": 27935,
"s": 27886,
"text": "a = 30\nb = 20 - 30/2\nc = b * ( 30 / 30 + 2) - 30"
},
{
"code": null,
"e": 28277,
"s": 27935,
"text": "This updated code is faster as compared to the previous code as the compiler does not need to again and again go back to the previous expressions looking up and copying the value of a variable in order to compute the current expressions. This saves a lot of time and thus, reducing time complexity and perform operations more efficiently. "
},
{
"code": null,
"e": 28531,
"s": 28277,
"text": "Note that this constant propagation technique behavior depends on compiler like few compilers perform constant propagation operations within the basic blocks; while a few compilers perform constant propagation operations in more complex control flow. "
},
{
"code": null,
"e": 28541,
"s": 28531,
"text": "as5853535"
},
{
"code": null,
"e": 28553,
"s": 28541,
"text": "anikakapoor"
},
{
"code": null,
"e": 28560,
"s": 28553,
"text": "Picked"
},
{
"code": null,
"e": 28576,
"s": 28560,
"text": "Compiler Design"
},
{
"code": null,
"e": 28584,
"s": 28576,
"text": "GATE CS"
},
{
"code": null,
"e": 28682,
"s": 28584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28740,
"s": 28682,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 28810,
"s": 28740,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 28851,
"s": 28810,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 28885,
"s": 28851,
"text": "Error Handling in Compiler Design"
},
{
"code": null,
"e": 28926,
"s": 28885,
"text": "Error detection and Recovery in Compiler"
},
{
"code": null,
"e": 28946,
"s": 28926,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28970,
"s": 28946,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28983,
"s": 28970,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 29010,
"s": 28983,
"text": "Types of Operating Systems"
}
] |
Simple Bill Splitter Application using Java Servlets - GeeksforGeeks
|
02 Dec, 2020
Pre-requisite: Java Servlets
Servlets is a Java Technology for server-side programming generally used to create web applications. It is a module that runs inside a Java-enabled web server.
Here, you will see the implementation by developing a Bill Splitter Application. In this Java Servlets app, there are two input columns one for the total bill amount and the second column is for the number of people in which the bill will be split. Let’s have a look.
Input :
Input your bill(Integer value) : GUI_User_Input Enter no. of people(Integer value) : GUI_User_Input
Output :
Result will display once user will give input and will click on submit button (Double data type value) =
Input your bill /Enter no. of people
Here, we will build a simple web application that will split the bill amount among the specified number of people.
Understanding how a Servlet works :
The client sends a request to the server and the request goes to the Web Container.
The Web Container uses a file named web.xml to detect which servlet to call and it calls the required servlet.
The servlet will process the information and will send a response to the client machine.
Setting up the Eclipse IDE:
Download the Eclipse IDE for Java EE Development from http://www.eclipse.org/downloads/
Download the Tomcat server from https://tomcat.apache.org
Go to File>New>Dynamic Web Project.
Add the link to the folder containing Tomcat to the Servlets tab at the bottom of the window and you’re all set to create your first servlet!
Creating the HTML file for Web layout :
Create a simple HTML file that includes a form to input details about the bill amount and the number of people.
HTML
<!DOCTYPE html><html> <head><meta charset="UTF-8"><title>Bill Splitter</title> <!-- CSS properties. --> <style type="text/css"> body{background-color:skyblue;text-align:center;}</style></head> <body><h1>Bill Splitter</h1> <!-- Application GUI form HTML code --> <form action="splitter">Input your bill: <input type="text" name="bill"><br>Enter no. of people: <input type="text" name="people"><br><input type="submit"></form></body> </html>
Creating the Java file:
Create a new class and extend the HttpServlet class to make your java class a servlet. In the case of Servlet file, response, and request object includes in servlet class. The req object is used to fetch data from the client while the res object is used to send a response to the client. These two functions parseInt and getParameter will help to take input from HTML form and will take integer value from that and then the calculation will be performed and you will see PrintWriter object to print the output value.
parseInt is used to convert string to integer.
getParameter is used to get the user input in string form.
PrintWriter is used to fetch output to the output window and not the console.
Java
package servlet; import java.io.IOException;import java.io.PrintWriter; import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class split extends HttpServlet{ public void service(HttpServletRequest req, HttpServletResponse res) throws IOException{ int i = Integer.parseInt(req.getParameter("bill")); int j = Integer.parseInt(req.getParameter("people")); double r = i/j; System.out.println(r); PrintWriter out=res.getWriter(); out.println("Bill per person is Rs" +r); }}
Configuring the web.xml file:
Whenever you create a new dynamic web project, you get a file named web.xml in your Project Folder which is the most important file for mapping together the servlet and the HTML file. The web.xml file uses two tags <servlet> & <servlet-mapping> to map the Servlet and HTML file together.
<servlet-name> is used to assign a universal name to the servlet.
<servlet-class> is used to assign the java class to be executed when servlet is called.
<url-pattern> is used to define the url pattern which when found will call the java class
defined in <servlet-class>
XML
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>servlet</display-name> <servlet> <servlet-name>serv1</servlet-name> <servlet-class>servlet.split</servlet-class> </servlet> <servlet-mapping> <servlet-name>serv1</servlet-name> <url-pattern>/splitter</url-pattern> </servlet-mapping> </web-app>
Running the Application:
Start the server and RUN!
ayeshafalak14
java-servlet
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 25278,
"s": 25249,
"text": "Pre-requisite: Java Servlets"
},
{
"code": null,
"e": 25439,
"s": 25278,
"text": "Servlets is a Java Technology for server-side programming generally used to create web applications. It is a module that runs inside a Java-enabled web server. "
},
{
"code": null,
"e": 25707,
"s": 25439,
"text": "Here, you will see the implementation by developing a Bill Splitter Application. In this Java Servlets app, there are two input columns one for the total bill amount and the second column is for the number of people in which the bill will be split. Let’s have a look."
},
{
"code": null,
"e": 25715,
"s": 25707,
"text": "Input :"
},
{
"code": null,
"e": 25819,
"s": 25715,
"text": "Input your bill(Integer value) : GUI_User_Input Enter no. of people(Integer value) : GUI_User_Input"
},
{
"code": null,
"e": 25828,
"s": 25819,
"text": "Output :"
},
{
"code": null,
"e": 25934,
"s": 25828,
"text": "Result will display once user will give input and will click on submit button (Double data type value) = "
},
{
"code": null,
"e": 25971,
"s": 25934,
"text": "Input your bill /Enter no. of people"
},
{
"code": null,
"e": 26086,
"s": 25971,
"text": "Here, we will build a simple web application that will split the bill amount among the specified number of people."
},
{
"code": null,
"e": 26122,
"s": 26086,
"text": "Understanding how a Servlet works :"
},
{
"code": null,
"e": 26206,
"s": 26122,
"text": "The client sends a request to the server and the request goes to the Web Container."
},
{
"code": null,
"e": 26317,
"s": 26206,
"text": "The Web Container uses a file named web.xml to detect which servlet to call and it calls the required servlet."
},
{
"code": null,
"e": 26406,
"s": 26317,
"text": "The servlet will process the information and will send a response to the client machine."
},
{
"code": null,
"e": 26434,
"s": 26406,
"text": "Setting up the Eclipse IDE:"
},
{
"code": null,
"e": 26522,
"s": 26434,
"text": "Download the Eclipse IDE for Java EE Development from http://www.eclipse.org/downloads/"
},
{
"code": null,
"e": 26580,
"s": 26522,
"text": "Download the Tomcat server from https://tomcat.apache.org"
},
{
"code": null,
"e": 26616,
"s": 26580,
"text": "Go to File>New>Dynamic Web Project."
},
{
"code": null,
"e": 26758,
"s": 26616,
"text": "Add the link to the folder containing Tomcat to the Servlets tab at the bottom of the window and you’re all set to create your first servlet!"
},
{
"code": null,
"e": 26798,
"s": 26758,
"text": "Creating the HTML file for Web layout :"
},
{
"code": null,
"e": 26911,
"s": 26798,
"text": "Create a simple HTML file that includes a form to input details about the bill amount and the number of people. "
},
{
"code": null,
"e": 26916,
"s": 26911,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head><meta charset=\"UTF-8\"><title>Bill Splitter</title> <!-- CSS properties. --> <style type=\"text/css\"> body{background-color:skyblue;text-align:center;}</style></head> <body><h1>Bill Splitter</h1> <!-- Application GUI form HTML code --> <form action=\"splitter\">Input your bill: <input type=\"text\" name=\"bill\"><br>Enter no. of people: <input type=\"text\" name=\"people\"><br><input type=\"submit\"></form></body> </html>",
"e": 27363,
"s": 26916,
"text": null
},
{
"code": null,
"e": 27391,
"s": 27366,
"text": "Creating the Java file: "
},
{
"code": null,
"e": 27908,
"s": 27391,
"text": "Create a new class and extend the HttpServlet class to make your java class a servlet. In the case of Servlet file, response, and request object includes in servlet class. The req object is used to fetch data from the client while the res object is used to send a response to the client. These two functions parseInt and getParameter will help to take input from HTML form and will take integer value from that and then the calculation will be performed and you will see PrintWriter object to print the output value."
},
{
"code": null,
"e": 28092,
"s": 27908,
"text": "parseInt is used to convert string to integer.\ngetParameter is used to get the user input in string form.\nPrintWriter is used to fetch output to the output window and not the console."
},
{
"code": null,
"e": 28097,
"s": 28092,
"text": "Java"
},
{
"code": "package servlet; import java.io.IOException;import java.io.PrintWriter; import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class split extends HttpServlet{ public void service(HttpServletRequest req, HttpServletResponse res) throws IOException{ int i = Integer.parseInt(req.getParameter(\"bill\")); int j = Integer.parseInt(req.getParameter(\"people\")); double r = i/j; System.out.println(r); PrintWriter out=res.getWriter(); out.println(\"Bill per person is Rs\" +r); }}",
"e": 28687,
"s": 28097,
"text": null
},
{
"code": null,
"e": 28719,
"s": 28687,
"text": " Configuring the web.xml file:"
},
{
"code": null,
"e": 29008,
"s": 28719,
"text": "Whenever you create a new dynamic web project, you get a file named web.xml in your Project Folder which is the most important file for mapping together the servlet and the HTML file. The web.xml file uses two tags <servlet> & <servlet-mapping> to map the Servlet and HTML file together. "
},
{
"code": null,
"e": 29280,
"s": 29008,
"text": "<servlet-name> is used to assign a universal name to the servlet.\n<servlet-class> is used to assign the java class to be executed when servlet is called.\n<url-pattern> is used to define the url pattern which when found will call the java class \ndefined in <servlet-class>"
},
{
"code": null,
"e": 29284,
"s": 29280,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\" xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd\" id=\"WebApp_ID\" version=\"4.0\"> <display-name>servlet</display-name> <servlet> <servlet-name>serv1</servlet-name> <servlet-class>servlet.split</servlet-class> </servlet> <servlet-mapping> <servlet-name>serv1</servlet-name> <url-pattern>/splitter</url-pattern> </servlet-mapping> </web-app>",
"e": 29881,
"s": 29284,
"text": null
},
{
"code": null,
"e": 29908,
"s": 29881,
"text": " Running the Application:"
},
{
"code": null,
"e": 29935,
"s": 29908,
"text": "Start the server and RUN! "
},
{
"code": null,
"e": 29951,
"s": 29937,
"text": "ayeshafalak14"
},
{
"code": null,
"e": 29964,
"s": 29951,
"text": "java-servlet"
},
{
"code": null,
"e": 29988,
"s": 29964,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29993,
"s": 29988,
"text": "Java"
},
{
"code": null,
"e": 30012,
"s": 29993,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30017,
"s": 30012,
"text": "Java"
},
{
"code": null,
"e": 30115,
"s": 30017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30130,
"s": 30115,
"text": "Stream In Java"
},
{
"code": null,
"e": 30151,
"s": 30130,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30170,
"s": 30151,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30200,
"s": 30170,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30246,
"s": 30200,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30263,
"s": 30246,
"text": "Generics in Java"
},
{
"code": null,
"e": 30284,
"s": 30263,
"text": "Introduction to Java"
},
{
"code": null,
"e": 30327,
"s": 30284,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30363,
"s": 30327,
"text": "Internal Working of HashMap in Java"
}
] |
Scala Map clone() method with example - GeeksforGeeks
|
13 Aug, 2019
The clone() method is utilized to make a copy of the receivers object. value clone is a member of scala.collection.mutable.Map[String, Int].
Method Definition: def clone(): Map[A, B]
Return Type: It returns the copy of the map used.
Example #1:
// Scala program of clone()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = scala.collection.mutable.Map("geeks" -> 5, "for" -> 3) // Applying clone method val result = m1.clone() // Displays output println(result) }}
Map(geeks -> 5, for -> 3)
Here, a mutable map is used as clone() is a member of scala.collection.mutable.Map[String, Int].Example #2:
// Scala program of clone()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = scala.collection.immutable.Map("geeks" -> 5, "for" -> 3) // Applying clone method val result = m1.clone() // Displays output println(result) }}
prog.scala:16: error: value clone is not a member of scala.collection.immutable.Map[String,Int]val result = m1.clone()^one error found
Here, one error is found as immutable map is utilized but clone method is a member of scala.collection.mutable.Map[String, Int].
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
|
[
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 25392,
"s": 25251,
"text": "The clone() method is utilized to make a copy of the receivers object. value clone is a member of scala.collection.mutable.Map[String, Int]."
},
{
"code": null,
"e": 25434,
"s": 25392,
"text": "Method Definition: def clone(): Map[A, B]"
},
{
"code": null,
"e": 25484,
"s": 25434,
"text": "Return Type: It returns the copy of the map used."
},
{
"code": null,
"e": 25496,
"s": 25484,
"text": "Example #1:"
},
{
"code": "// Scala program of clone()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = scala.collection.mutable.Map(\"geeks\" -> 5, \"for\" -> 3) // Applying clone method val result = m1.clone() // Displays output println(result) }}",
"e": 25868,
"s": 25496,
"text": null
},
{
"code": null,
"e": 25895,
"s": 25868,
"text": "Map(geeks -> 5, for -> 3)\n"
},
{
"code": null,
"e": 26003,
"s": 25895,
"text": "Here, a mutable map is used as clone() is a member of scala.collection.mutable.Map[String, Int].Example #2:"
},
{
"code": "// Scala program of clone()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = scala.collection.immutable.Map(\"geeks\" -> 5, \"for\" -> 3) // Applying clone method val result = m1.clone() // Displays output println(result) }}",
"e": 26377,
"s": 26003,
"text": null
},
{
"code": null,
"e": 26512,
"s": 26377,
"text": "prog.scala:16: error: value clone is not a member of scala.collection.immutable.Map[String,Int]val result = m1.clone()^one error found"
},
{
"code": null,
"e": 26641,
"s": 26512,
"text": "Here, one error is found as immutable map is utilized but clone method is a member of scala.collection.mutable.Map[String, Int]."
},
{
"code": null,
"e": 26647,
"s": 26641,
"text": "Scala"
},
{
"code": null,
"e": 26657,
"s": 26647,
"text": "Scala-Map"
},
{
"code": null,
"e": 26670,
"s": 26657,
"text": "Scala-Method"
},
{
"code": null,
"e": 26676,
"s": 26670,
"text": "Scala"
},
{
"code": null,
"e": 26774,
"s": 26676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26796,
"s": 26774,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26822,
"s": 26796,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26834,
"s": 26822,
"text": "Scala Lists"
},
{
"code": null,
"e": 26887,
"s": 26834,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26906,
"s": 26887,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26927,
"s": 26906,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26946,
"s": 26927,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26961,
"s": 26946,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 27006,
"s": 26961,
"text": "Scala String substring() method with example"
}
] |
Expression Tree | Practice | GeeksforGeeks
|
Given a full binary expression tree consisting of basic binary operators (+ , – ,*, /) and some integers, Your task is to evaluate the expression tree.
Example 1:
Input:
+
/ \
* -
/ \ / \
5 4 100 20
Output: 100
Explanation:
((5 * 4) + (100 - 20)) = 100
Example 2:
Input:
-
/ \
4 7
Output: -3
Explanation:
4 - 7 = -3
Your Task:
You dont need to read input or print anything. Complete the function evalTree() which takes root node as input parameter and returns an integer denoting the result obtained by simplifying the expression tree.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(height of tree)
Constraints:
1 ≤ N ≤ 500
0
bansallakshay0813 days ago
/*You are required to complete below method */ int evalTree(node* root) { // Your code here if(root->left==NULL&&root->right==NULL) return stoi(root->data); if (root->data=="+")return evalTree(root->left)+evalTree(root->right); if (root->data=="-")return evalTree(root->left)-evalTree(root->right); if (root->data=="*")return evalTree(root->left)*evalTree(root->right); if (root->data=="/")return evalTree(root->left)/evalTree(root->right); }
0
suyashsingh33 weeks ago
Java Solution
if(root==null) return 0;
if(root.left==null && root.right==null) return Integer.parseInt(root.data);
switch(root.data){
case "+" : return evalTree(root.left)+evalTree(root.right);
case "-": return evalTree(root.left)-evalTree(root.right);
case "*": return evalTree(root.left)*evalTree(root.right);
case "/": return evalTree(root.left)/evalTree(root.right);
}
return 0;
0
detroix072 months ago
int evalTree(node* root) {
// base case if(root==NULL) return 0; // postorder traversal int left = evalTree(root->left); int right = evalTree(root->right); if(root->data== "+") return left+right; if(root->data== "-") return left-right; if(root->data== "*") return left*right; if(root->data== "/") return left/right; return stoi(root->data); }
+2
tanujrajput00003 months ago
int evalTree(node* root) {
if(root==NULL)
return 0;
int l = evalTree(root->left);
int r = evalTree(root->right);
if(root->data=="*")return l*r;
else if(root->data=="+")return l+r;
else if(root->data=="/")return l/r;
else if(root->data=="-")return l-r;
else return stoi(root->data);
}
+1
ashwinkumar99313 months ago
int evalTree(node* root) { if(root==NULL){ return 0; } if(root->left==NULL&&root->right==NULL){ int x = 0; stringstream geek(root->data); geek >> x; return x; } //evaluaveare left and right int left = evalTree(root->left); int right = evalTree(root->right); if(root->data == "+"){ return left+right; } if(root->data == "*"){ return left*right; } if(root->data == "-"){ return left-right; } if(root->data == "/"){ return left/right; } }
+1
aaishuagarwal3 months ago
int evalTree(node* root) { // Your code here if(root->left==NULL&&root->right==NULL) return stoi(root->data); int l,r; if(root->right) r=evalTree(root->right); if(root->left) l=evalTree(root->left); if(root->data=="+") { int ans=l+r; return ans; } else if(root->data=="-") return l-r; else if(root->data=="*") return l*r; else if(root->data=="/") return l/r; else if(root->data=="%") return l%r; }
0
tarun2002ts0213 months ago
int evalTree(node* root) { // Your code here if(root->left==NULL && root->right==NULL) return stoi(root->data); int ans=evalTree(root->left); int ans1=evalTree(root->right); if(root->data=="+") return ans+ans1; else if(root->data=="-") return ans-ans1; else if(root->data=="*") return ans*ans1; else return ans/ans1; }
0
hamidnourashraf3 months ago
def evalTree(self, root):
if root.left is None and root.right is None:
return int(root.data)
left_val = self.evalTree(root.left)
right_val = self.evalTree(root.right)
if root.data == '+':
return left_val + right_val
if root.data == '-':
return left_val - right_val
if root.data == '*':
return left_val * right_val
if root.data == '/':
return int(left_val / right_val)
+2
shubh003 months ago
c++ solution...
Taken time - 0.0/1.2 sec
class Solution{ public: /*You are required to complete below method */ int evalTree(node* root) { // Your code here string val = root -> data; if(root == NULL){ return 0; } else if(val == "+"){ int res = evalTree(root -> left) + evalTree(root -> right); return res; } else if(val == "-"){ int res = evalTree(root -> left) - evalTree(root -> right); return res; } else if(val == "*"){ int res = evalTree(root -> left) * evalTree(root -> right); return res; } else if(val == "/"){ int res = evalTree(root -> left) / evalTree(root -> right); return res; } else{ return stoi(root -> data); } }};
0
badgujarsachin834 months ago
int evalTree(node* root) {
// Your code here
if(root->left==NULL && root->right==NULL){
return stoi(root->data);
}
if(root->data=="+"){
return evalTree(root->left)+evalTree(root->right);
}
if(root->data=="-"){
return evalTree(root->left)-evalTree(root->right);
}
if(root->data=="*"){
return evalTree(root->left)*evalTree(root->right);
}
if(root->data=="/"){
return evalTree(root->left)/evalTree(root->right);
}
}
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.
|
[
{
"code": null,
"e": 390,
"s": 238,
"text": "Given a full binary expression tree consisting of basic binary operators (+ , – ,*, /) and some integers, Your task is to evaluate the expression tree."
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Example 1:"
},
{
"code": null,
"e": 566,
"s": 401,
"text": "Input: \n +\n / \\\n * -\n / \\ / \\\n 5 4 100 20 \n\nOutput: 100\n\nExplanation:\n((5 * 4) + (100 - 20)) = 100"
},
{
"code": null,
"e": 578,
"s": 566,
"text": "\nExample 2:"
},
{
"code": null,
"e": 669,
"s": 578,
"text": "Input:\n -\n / \\\n 4 7\n\nOutput: -3\n\nExplanation:\n4 - 7 = -3"
},
{
"code": null,
"e": 892,
"s": 669,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function evalTree() which takes root node as input parameter and returns an integer denoting the result obtained by simplifying the expression tree."
},
{
"code": null,
"e": 968,
"s": 892,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)"
},
{
"code": null,
"e": 994,
"s": 968,
"text": "\nConstraints:\n1 ≤ N ≤ 500"
},
{
"code": null,
"e": 998,
"s": 996,
"text": "0"
},
{
"code": null,
"e": 1025,
"s": 998,
"text": "bansallakshay0813 days ago"
},
{
"code": null,
"e": 1525,
"s": 1025,
"text": " /*You are required to complete below method */ int evalTree(node* root) { // Your code here if(root->left==NULL&&root->right==NULL) return stoi(root->data); if (root->data==\"+\")return evalTree(root->left)+evalTree(root->right); if (root->data==\"-\")return evalTree(root->left)-evalTree(root->right); if (root->data==\"*\")return evalTree(root->left)*evalTree(root->right); if (root->data==\"/\")return evalTree(root->left)/evalTree(root->right); }"
},
{
"code": null,
"e": 1527,
"s": 1525,
"text": "0"
},
{
"code": null,
"e": 1551,
"s": 1527,
"text": "suyashsingh33 weeks ago"
},
{
"code": null,
"e": 1565,
"s": 1551,
"text": "Java Solution"
},
{
"code": null,
"e": 2040,
"s": 1565,
"text": "\n if(root==null) return 0;\n \n if(root.left==null && root.right==null) return Integer.parseInt(root.data);\n \n \n switch(root.data){\n case \"+\" : return evalTree(root.left)+evalTree(root.right);\n case \"-\": return evalTree(root.left)-evalTree(root.right);\n case \"*\": return evalTree(root.left)*evalTree(root.right);\n case \"/\": return evalTree(root.left)/evalTree(root.right);\n }\n \n return 0;"
},
{
"code": null,
"e": 2042,
"s": 2040,
"text": "0"
},
{
"code": null,
"e": 2064,
"s": 2042,
"text": "detroix072 months ago"
},
{
"code": null,
"e": 2091,
"s": 2064,
"text": "int evalTree(node* root) {"
},
{
"code": null,
"e": 2457,
"s": 2091,
"text": " // base case if(root==NULL) return 0; // postorder traversal int left = evalTree(root->left); int right = evalTree(root->right); if(root->data== \"+\") return left+right; if(root->data== \"-\") return left-right; if(root->data== \"*\") return left*right; if(root->data== \"/\") return left/right; return stoi(root->data); }"
},
{
"code": null,
"e": 2460,
"s": 2457,
"text": "+2"
},
{
"code": null,
"e": 2488,
"s": 2460,
"text": "tanujrajput00003 months ago"
},
{
"code": null,
"e": 2880,
"s": 2488,
"text": "int evalTree(node* root) {\n if(root==NULL)\n return 0;\n int l = evalTree(root->left);\n int r = evalTree(root->right);\n \n if(root->data==\"*\")return l*r;\n else if(root->data==\"+\")return l+r;\n else if(root->data==\"/\")return l/r;\n else if(root->data==\"-\")return l-r;\n else return stoi(root->data);\n \n \n\n }"
},
{
"code": null,
"e": 2883,
"s": 2880,
"text": "+1"
},
{
"code": null,
"e": 2911,
"s": 2883,
"text": "ashwinkumar99313 months ago"
},
{
"code": null,
"e": 3557,
"s": 2911,
"text": "int evalTree(node* root) { if(root==NULL){ return 0; } if(root->left==NULL&&root->right==NULL){ int x = 0; stringstream geek(root->data); geek >> x; return x; } //evaluaveare left and right int left = evalTree(root->left); int right = evalTree(root->right); if(root->data == \"+\"){ return left+right; } if(root->data == \"*\"){ return left*right; } if(root->data == \"-\"){ return left-right; } if(root->data == \"/\"){ return left/right; } }"
},
{
"code": null,
"e": 3560,
"s": 3557,
"text": "+1"
},
{
"code": null,
"e": 3586,
"s": 3560,
"text": "aaishuagarwal3 months ago"
},
{
"code": null,
"e": 4127,
"s": 3586,
"text": " int evalTree(node* root) { // Your code here if(root->left==NULL&&root->right==NULL) return stoi(root->data); int l,r; if(root->right) r=evalTree(root->right); if(root->left) l=evalTree(root->left); if(root->data==\"+\") { int ans=l+r; return ans; } else if(root->data==\"-\") return l-r; else if(root->data==\"*\") return l*r; else if(root->data==\"/\") return l/r; else if(root->data==\"%\") return l%r; }"
},
{
"code": null,
"e": 4129,
"s": 4127,
"text": "0"
},
{
"code": null,
"e": 4156,
"s": 4129,
"text": "tarun2002ts0213 months ago"
},
{
"code": null,
"e": 4555,
"s": 4156,
"text": "int evalTree(node* root) { // Your code here if(root->left==NULL && root->right==NULL) return stoi(root->data); int ans=evalTree(root->left); int ans1=evalTree(root->right); if(root->data==\"+\") return ans+ans1; else if(root->data==\"-\") return ans-ans1; else if(root->data==\"*\") return ans*ans1; else return ans/ans1; }"
},
{
"code": null,
"e": 4557,
"s": 4555,
"text": "0"
},
{
"code": null,
"e": 4585,
"s": 4557,
"text": "hamidnourashraf3 months ago"
},
{
"code": null,
"e": 5057,
"s": 4585,
"text": "def evalTree(self, root):\n if root.left is None and root.right is None:\n return int(root.data)\n left_val = self.evalTree(root.left)\n right_val = self.evalTree(root.right)\n if root.data == '+':\n return left_val + right_val\n if root.data == '-':\n return left_val - right_val\n if root.data == '*':\n return left_val * right_val\n if root.data == '/':\n return int(left_val / right_val)"
},
{
"code": null,
"e": 5060,
"s": 5057,
"text": "+2"
},
{
"code": null,
"e": 5080,
"s": 5060,
"text": "shubh003 months ago"
},
{
"code": null,
"e": 5096,
"s": 5080,
"text": "c++ solution..."
},
{
"code": null,
"e": 5121,
"s": 5096,
"text": "Taken time - 0.0/1.2 sec"
},
{
"code": null,
"e": 5885,
"s": 5123,
"text": "class Solution{ public: /*You are required to complete below method */ int evalTree(node* root) { // Your code here string val = root -> data; if(root == NULL){ return 0; } else if(val == \"+\"){ int res = evalTree(root -> left) + evalTree(root -> right); return res; } else if(val == \"-\"){ int res = evalTree(root -> left) - evalTree(root -> right); return res; } else if(val == \"*\"){ int res = evalTree(root -> left) * evalTree(root -> right); return res; } else if(val == \"/\"){ int res = evalTree(root -> left) / evalTree(root -> right); return res; } else{ return stoi(root -> data); } }};"
},
{
"code": null,
"e": 5887,
"s": 5885,
"text": "0"
},
{
"code": null,
"e": 5916,
"s": 5887,
"text": "badgujarsachin834 months ago"
},
{
"code": null,
"e": 6481,
"s": 5916,
"text": "int evalTree(node* root) {\n // Your code here\n if(root->left==NULL && root->right==NULL){\n return stoi(root->data);\n }\n if(root->data==\"+\"){\n return evalTree(root->left)+evalTree(root->right);\n }\n if(root->data==\"-\"){\n return evalTree(root->left)-evalTree(root->right);\n }\n if(root->data==\"*\"){\n return evalTree(root->left)*evalTree(root->right);\n }\n if(root->data==\"/\"){\n return evalTree(root->left)/evalTree(root->right);\n }\n }"
},
{
"code": null,
"e": 6627,
"s": 6481,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6663,
"s": 6627,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6673,
"s": 6663,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6683,
"s": 6673,
"text": "\nContest\n"
},
{
"code": null,
"e": 6746,
"s": 6683,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6894,
"s": 6746,
"text": "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."
},
{
"code": null,
"e": 7102,
"s": 6894,
"text": "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."
},
{
"code": null,
"e": 7208,
"s": 7102,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JSON Pretty Print using Python - GeeksforGeeks
|
08 Dec, 2020
JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages. It is commonly used for data transmission between client-server applications. Usually, minified versions of JSON text are transmitted to save bandwidth. However, for debugging and analysis, a beautified version or a pretty print of JSON is required. Essentially, pretty printing JSON means having proper indentation, white spaces and separators. This article explores how to pretty print JSON using Python.
Python has a built-in module called json that allows working with JSON data and how it can be used for out functionality is given in the following steps:
Import the JSON package.
Then depending on the scenario-
Reading from a JSON file and pretty printing it,Writing pretty printed JSON to a file, orsimply pretty printing JSON string data.
Reading from a JSON file and pretty printing it,
Writing pretty printed JSON to a file, or
simply pretty printing JSON string data.
Below are examples and steps to better understand these cases.
First, use json.loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json.dumps() method is used.
Syntax:
json.dumps(indent,separator)
This method has the parameter indent to specify the number of spaces and a separator parameter to specify the separator between key and value. By default, the separator is a comma between key-value pairs, and a colon between key and value. If the indent parameter of json.dumps() is negative, 0 or an empty string then there are no indentations and only newlines are inserted. By default, indent is None and the data is represented in a single line.
Example:
Python3
# Import required librariesimport json # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]}, \ {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]} ]' # Create Python object from JSON string dataobj = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(obj, indent=4)print(json_formatted_str)
Output:
[
{
"studentid": 1,
"name": "ABC",
"subjects": [
"Python",
"Data Structures"
]
},
{
"studentid": 2,
"name": "PQR",
"subjects": [
"Java",
"Operating System"
]
}
]
To write a Python object as JSON formatted data into a file, json.dump() method is used. Like json.dumps() method, it has the indents and separator parameters to write beautified JSON.
Example:
Python3
# Import required librariesimport json data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]}, {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}] # Write pretty print JSON data to filewith open("filename.json", "w") as write_file: json.dump(data, write_file, indent=4)
Output:
filename.json
To read JSON from a file or URL, use json.load(). Then use json.dumps() to convert the object (obtained from reading the file) into a pretty print JSON string.
Example:
Python3
# Import required librariesimport json # Read JSON data from file and pretty print itwith open("filename.json", "r") as read_file: # Convert JSON file to Python Types obj = json.load(read_file) # Pretty print JSON data pretty_json = json.dumps(obj, indent=4) print(pretty_json)
Output:
[
{
"studentid": 1,
"name": "ABC",
"subjects": [
"Python",
"Data Structures"
]
},
{
"studentid": 2,
"name": "PQR",
"subjects": [
"Java",
"Operating System"
]
}
]
Python-json
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25579,
"s": 25551,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 26107,
"s": 25579,
"text": "JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages. It is commonly used for data transmission between client-server applications. Usually, minified versions of JSON text are transmitted to save bandwidth. However, for debugging and analysis, a beautified version or a pretty print of JSON is required. Essentially, pretty printing JSON means having proper indentation, white spaces and separators. This article explores how to pretty print JSON using Python. "
},
{
"code": null,
"e": 26261,
"s": 26107,
"text": "Python has a built-in module called json that allows working with JSON data and how it can be used for out functionality is given in the following steps:"
},
{
"code": null,
"e": 26286,
"s": 26261,
"text": "Import the JSON package."
},
{
"code": null,
"e": 26318,
"s": 26286,
"text": "Then depending on the scenario-"
},
{
"code": null,
"e": 26448,
"s": 26318,
"text": "Reading from a JSON file and pretty printing it,Writing pretty printed JSON to a file, orsimply pretty printing JSON string data."
},
{
"code": null,
"e": 26497,
"s": 26448,
"text": "Reading from a JSON file and pretty printing it,"
},
{
"code": null,
"e": 26539,
"s": 26497,
"text": "Writing pretty printed JSON to a file, or"
},
{
"code": null,
"e": 26580,
"s": 26539,
"text": "simply pretty printing JSON string data."
},
{
"code": null,
"e": 26643,
"s": 26580,
"text": "Below are examples and steps to better understand these cases."
},
{
"code": null,
"e": 26803,
"s": 26643,
"text": "First, use json.loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json.dumps() method is used. "
},
{
"code": null,
"e": 26811,
"s": 26803,
"text": "Syntax:"
},
{
"code": null,
"e": 26840,
"s": 26811,
"text": "json.dumps(indent,separator)"
},
{
"code": null,
"e": 27290,
"s": 26840,
"text": "This method has the parameter indent to specify the number of spaces and a separator parameter to specify the separator between key and value. By default, the separator is a comma between key-value pairs, and a colon between key and value. If the indent parameter of json.dumps() is negative, 0 or an empty string then there are no indentations and only newlines are inserted. By default, indent is None and the data is represented in a single line."
},
{
"code": null,
"e": 27299,
"s": 27290,
"text": "Example:"
},
{
"code": null,
"e": 27307,
"s": 27299,
"text": "Python3"
},
{
"code": "# Import required librariesimport json # Initialize JSON datajson_data = '[ {\"studentid\": 1, \"name\": \"ABC\", \"subjects\": [\"Python\", \"Data Structures\"]}, \\ {\"studentid\": 2, \"name\": \"PQR\", \"subjects\": [\"Java\", \"Operating System\"]} ]' # Create Python object from JSON string dataobj = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(obj, indent=4)print(json_formatted_str)",
"e": 27719,
"s": 27307,
"text": null
},
{
"code": null,
"e": 27727,
"s": 27719,
"text": "Output:"
},
{
"code": null,
"e": 28001,
"s": 27727,
"text": "[\n {\n \"studentid\": 1,\n \"name\": \"ABC\",\n \"subjects\": [\n \"Python\",\n \"Data Structures\"\n ]\n },\n {\n \"studentid\": 2,\n \"name\": \"PQR\",\n \"subjects\": [\n \"Java\",\n \"Operating System\"\n ]\n }\n]"
},
{
"code": null,
"e": 28186,
"s": 28001,
"text": "To write a Python object as JSON formatted data into a file, json.dump() method is used. Like json.dumps() method, it has the indents and separator parameters to write beautified JSON."
},
{
"code": null,
"e": 28195,
"s": 28186,
"text": "Example:"
},
{
"code": null,
"e": 28203,
"s": 28195,
"text": "Python3"
},
{
"code": "# Import required librariesimport json data = [{\"studentid\": 1, \"name\": \"ABC\", \"subjects\": [\"Python\", \"Data Structures\"]}, {\"studentid\": 2, \"name\": \"PQR\", \"subjects\": [\"Java\", \"Operating System\"]}] # Write pretty print JSON data to filewith open(\"filename.json\", \"w\") as write_file: json.dump(data, write_file, indent=4)",
"e": 28536,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28544,
"s": 28536,
"text": "Output:"
},
{
"code": null,
"e": 28558,
"s": 28544,
"text": "filename.json"
},
{
"code": null,
"e": 28719,
"s": 28558,
"text": "To read JSON from a file or URL, use json.load(). Then use json.dumps() to convert the object (obtained from reading the file) into a pretty print JSON string. "
},
{
"code": null,
"e": 28728,
"s": 28719,
"text": "Example:"
},
{
"code": null,
"e": 28736,
"s": 28728,
"text": "Python3"
},
{
"code": "# Import required librariesimport json # Read JSON data from file and pretty print itwith open(\"filename.json\", \"r\") as read_file: # Convert JSON file to Python Types obj = json.load(read_file) # Pretty print JSON data pretty_json = json.dumps(obj, indent=4) print(pretty_json)",
"e": 29032,
"s": 28736,
"text": null
},
{
"code": null,
"e": 29040,
"s": 29032,
"text": "Output:"
},
{
"code": null,
"e": 29314,
"s": 29040,
"text": "[\n {\n \"studentid\": 1,\n \"name\": \"ABC\",\n \"subjects\": [\n \"Python\",\n \"Data Structures\"\n ]\n },\n {\n \"studentid\": 2,\n \"name\": \"PQR\",\n \"subjects\": [\n \"Java\",\n \"Operating System\"\n ]\n }\n]"
},
{
"code": null,
"e": 29326,
"s": 29314,
"text": "Python-json"
},
{
"code": null,
"e": 29333,
"s": 29326,
"text": "Python"
},
{
"code": null,
"e": 29431,
"s": 29333,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29463,
"s": 29431,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29505,
"s": 29463,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29547,
"s": 29505,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29603,
"s": 29547,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29630,
"s": 29603,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29661,
"s": 29630,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29700,
"s": 29661,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29729,
"s": 29700,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29751,
"s": 29729,
"text": "Defaultdict in Python"
}
] |
How to Display Suggestions for Input Field in HTML ? - GeeksforGeeks
|
09 Oct, 2021
Generally, we have seen most of the time, there is an input field that provides an autocomplete feature either by typing the specific input data or by seeing a drop-down list from pre-defined options while filling up the form. This feature can be designed & utilized using the HTML <datalist> tag in the form. The <datalist> tag is used to provide autocomplete feature in the HTML files. It can be used with an input tag so that users can easily fill the data in the forms using select the data. In this article, we will learn to create an input suggestion form using HTML and CSS & will implement the <datalist> tag to enable the autocomplete feature in HTML.
Syntax:
<datalist> ... </datalist>
Note: The element’s id attribute used in the <datalist> tag should be equal to the element’s list attribute in the <input> tag that will help to binds them together.
Approach:
Create a div with the class as a container. Inside of this div, create another div with a class as a text-container that will contain the <input> tag & <datalist> tag.
Declare the list attribute as programmingLanguages inside the <input> tag. Similarly, declare the id attribute as the same as the list attribute, inside the <datalist> tag.
Now, create the drop-down list of programming languages for building the pre-defined options.
We have used google font to build some awesome input forms & for decorating the text. In order to use the google font, we need to import the following font URL in our stylesheet.
@import url(‘https://fonts.googleapis.com/css2?family=Roboto+Condensed:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&display=swap’);
We will understand the input field suggestion concept through the below example.
Example: This example illustrates the use of the <datalist> tag to make input suggestions in HTML.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <style> @import url("https://fonts.googleapis.com/css2?family=Roboto+Condensed:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&display=swap"); * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: "Roboto Condensed", sans-serif; background-color: green; padding: 40px 550px; } h1, h3 { font-family: Arial; } .container { margin: 150px auto; font-size: 18px; color: white; } .container input { margin-top: 4px; height: 50px; width: 100%; outline: none; border: none; padding: 0 20px 0 20px; font-size: 20px; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h3>HTML <datalist> Tag</h3> <label for="programmingLanguages"> Choose Your Favourite Programming Language: </label> <div class="text-container"> <input type="text" list="programmingLanguages" placeholder="Enter Here" /> <datalist id="programmingLanguages"> <option value="Objective C">Objective C</option> <option value="C++">C++</option> <option value="C#">C#</option> <option value="Cobol">Cobol</option> <option value="Go">Go</option> <option value="Java">Java</option> <option value="JavaScript">JavaScript</option> <option value="Python">Python</option> <option value="PHP">PHP</option> <option value="Pascal">Pascal</option> <option value="Perl">Perl</option> <option value="R">R</option> <option value="Swift">Swift</option> </datalist> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26647,
"s": 26619,
"text": "\n09 Oct, 2021"
},
{
"code": null,
"e": 27309,
"s": 26647,
"text": "Generally, we have seen most of the time, there is an input field that provides an autocomplete feature either by typing the specific input data or by seeing a drop-down list from pre-defined options while filling up the form. This feature can be designed & utilized using the HTML <datalist> tag in the form. The <datalist> tag is used to provide autocomplete feature in the HTML files. It can be used with an input tag so that users can easily fill the data in the forms using select the data. In this article, we will learn to create an input suggestion form using HTML and CSS & will implement the <datalist> tag to enable the autocomplete feature in HTML. "
},
{
"code": null,
"e": 27317,
"s": 27309,
"text": "Syntax:"
},
{
"code": null,
"e": 27344,
"s": 27317,
"text": "<datalist> ... </datalist>"
},
{
"code": null,
"e": 27510,
"s": 27344,
"text": "Note: The element’s id attribute used in the <datalist> tag should be equal to the element’s list attribute in the <input> tag that will help to binds them together."
},
{
"code": null,
"e": 27520,
"s": 27510,
"text": "Approach:"
},
{
"code": null,
"e": 27688,
"s": 27520,
"text": "Create a div with the class as a container. Inside of this div, create another div with a class as a text-container that will contain the <input> tag & <datalist> tag."
},
{
"code": null,
"e": 27861,
"s": 27688,
"text": "Declare the list attribute as programmingLanguages inside the <input> tag. Similarly, declare the id attribute as the same as the list attribute, inside the <datalist> tag."
},
{
"code": null,
"e": 27955,
"s": 27861,
"text": "Now, create the drop-down list of programming languages for building the pre-defined options."
},
{
"code": null,
"e": 28134,
"s": 27955,
"text": "We have used google font to build some awesome input forms & for decorating the text. In order to use the google font, we need to import the following font URL in our stylesheet."
},
{
"code": null,
"e": 28267,
"s": 28134,
"text": "@import url(‘https://fonts.googleapis.com/css2?family=Roboto+Condensed:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&display=swap’);"
},
{
"code": null,
"e": 28348,
"s": 28267,
"text": "We will understand the input field suggestion concept through the below example."
},
{
"code": null,
"e": 28447,
"s": 28348,
"text": "Example: This example illustrates the use of the <datalist> tag to make input suggestions in HTML."
},
{
"code": null,
"e": 28452,
"s": 28447,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <style> @import url(\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&display=swap\"); * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: \"Roboto Condensed\", sans-serif; background-color: green; padding: 40px 550px; } h1, h3 { font-family: Arial; } .container { margin: 150px auto; font-size: 18px; color: white; } .container input { margin-top: 4px; height: 50px; width: 100%; outline: none; border: none; padding: 0 20px 0 20px; font-size: 20px; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h3>HTML <datalist> Tag</h3> <label for=\"programmingLanguages\"> Choose Your Favourite Programming Language: </label> <div class=\"text-container\"> <input type=\"text\" list=\"programmingLanguages\" placeholder=\"Enter Here\" /> <datalist id=\"programmingLanguages\"> <option value=\"Objective C\">Objective C</option> <option value=\"C++\">C++</option> <option value=\"C#\">C#</option> <option value=\"Cobol\">Cobol</option> <option value=\"Go\">Go</option> <option value=\"Java\">Java</option> <option value=\"JavaScript\">JavaScript</option> <option value=\"Python\">Python</option> <option value=\"PHP\">PHP</option> <option value=\"Pascal\">Pascal</option> <option value=\"Perl\">Perl</option> <option value=\"R\">R</option> <option value=\"Swift\">Swift</option> </datalist> </div> </div></body> </html>",
"e": 30635,
"s": 28452,
"text": null
},
{
"code": null,
"e": 30643,
"s": 30635,
"text": "Output:"
},
{
"code": null,
"e": 30780,
"s": 30643,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30795,
"s": 30780,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30809,
"s": 30795,
"text": "CSS-Questions"
},
{
"code": null,
"e": 30824,
"s": 30809,
"text": "HTML-Questions"
},
{
"code": null,
"e": 30834,
"s": 30824,
"text": "HTML-Tags"
},
{
"code": null,
"e": 30838,
"s": 30834,
"text": "CSS"
},
{
"code": null,
"e": 30843,
"s": 30838,
"text": "HTML"
},
{
"code": null,
"e": 30860,
"s": 30843,
"text": "Web Technologies"
},
{
"code": null,
"e": 30865,
"s": 30860,
"text": "HTML"
},
{
"code": null,
"e": 30963,
"s": 30865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31002,
"s": 30963,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31039,
"s": 31002,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31068,
"s": 31039,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31110,
"s": 31068,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 31145,
"s": 31110,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 31205,
"s": 31145,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31258,
"s": 31205,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31319,
"s": 31258,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31343,
"s": 31319,
"text": "REST API (Introduction)"
}
] |
Inequality Operator in SQL - GeeksforGeeks
|
09 Jul, 2021
In this article, we will discuss the overview of operators in SQL and mainly our focus will be on Inequality Operator in SQL. Let’s discuss it one by one.
Pre-requisite – Operators in SQL
Overview :SQL Operators are widely used to access information on the basis of conditions. In the Inequality operator, we will check the condition on a specific column. Operator in SQL is used to perform conditions and on the basis of condition, the output will come. For example, if you want to find the data from the database let’s say student name then you can use an equal operator to check the name. Inequality operator is a reserved word used in an SQL statement WHERE clause to compare the two elements.
Example –In this example, let’s suppose you want to access student names from the student table from the database. So, we will use an equal operator with WHERE clause as follows.
Select * from student where name = 'ABC';
Inequality Operator in SQL :Sometimes when we want to select data that doesn’t satisfy a condition, like all students that are not in their 2nd year. Consider the given below table for reference. In this table, students is a table name and name, year, subjects are the column’s name of the table.
Example-1 :So to select those who are not in their 2nd year. So, In this, we will use the inequality operator as follows.
SELECT * FROM students WHERE year <> 2;
Output :There will be 2 records selected. These are the results you should see with either one of the SQL statements as follows.
Like before, we start with selecting all items with *. This will give us students from all years.
Since year<>2 filters out student items with 2 in the year column, we only get a student from the fourth year.
Example-2 :We can also use the inequality operator with text values, like getting all students that don’t subject in ‘Java’.
SELECT * FROM students WHERE subjects <> 'Java';
There will be 2 records selected i.e “Compiler Design”, “Php”. These are the results you should see with either one of the SQL statements. In the example, both SELECT statements would return all rows from the subjects table where the subjects are not equal to Java.
Use : To check if a column’s value is not equal to another, we use the inequality operator <>.
Note :
What kind of value can we use the inequality operator <> with?Ans- Any kind like text and numbers.
When is the inequality sign useful ?Ans- When you want to get all items that don’t satisfy a criterion.
What kind of value can we use the inequality operator <> with?Ans- Any kind like text and numbers.
When is the inequality sign useful ?Ans- When you want to get all items that don’t satisfy a criterion.
DBMS-SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
What is Temporary Table in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
|
[
{
"code": null,
"e": 25585,
"s": 25554,
"text": " \n09 Jul, 2021\n"
},
{
"code": null,
"e": 25740,
"s": 25585,
"text": "In this article, we will discuss the overview of operators in SQL and mainly our focus will be on Inequality Operator in SQL. Let’s discuss it one by one."
},
{
"code": null,
"e": 25773,
"s": 25740,
"text": "Pre-requisite – Operators in SQL"
},
{
"code": null,
"e": 26283,
"s": 25773,
"text": "Overview :SQL Operators are widely used to access information on the basis of conditions. In the Inequality operator, we will check the condition on a specific column. Operator in SQL is used to perform conditions and on the basis of condition, the output will come. For example, if you want to find the data from the database let’s say student name then you can use an equal operator to check the name. Inequality operator is a reserved word used in an SQL statement WHERE clause to compare the two elements."
},
{
"code": null,
"e": 26462,
"s": 26283,
"text": "Example –In this example, let’s suppose you want to access student names from the student table from the database. So, we will use an equal operator with WHERE clause as follows."
},
{
"code": null,
"e": 26504,
"s": 26462,
"text": "Select * from student where name = 'ABC';"
},
{
"code": null,
"e": 26801,
"s": 26504,
"text": "Inequality Operator in SQL :Sometimes when we want to select data that doesn’t satisfy a condition, like all students that are not in their 2nd year. Consider the given below table for reference. In this table, students is a table name and name, year, subjects are the column’s name of the table."
},
{
"code": null,
"e": 26923,
"s": 26801,
"text": "Example-1 :So to select those who are not in their 2nd year. So, In this, we will use the inequality operator as follows."
},
{
"code": null,
"e": 26963,
"s": 26923,
"text": "SELECT * FROM students WHERE year <> 2;"
},
{
"code": null,
"e": 27092,
"s": 26963,
"text": "Output :There will be 2 records selected. These are the results you should see with either one of the SQL statements as follows."
},
{
"code": null,
"e": 27190,
"s": 27092,
"text": "Like before, we start with selecting all items with *. This will give us students from all years."
},
{
"code": null,
"e": 27302,
"s": 27190,
"text": "Since year<>2 filters out student items with 2 in the year column, we only get a student from the fourth year. "
},
{
"code": null,
"e": 27429,
"s": 27304,
"text": "Example-2 :We can also use the inequality operator with text values, like getting all students that don’t subject in ‘Java’."
},
{
"code": null,
"e": 27478,
"s": 27429,
"text": "SELECT * FROM students WHERE subjects <> 'Java';"
},
{
"code": null,
"e": 27744,
"s": 27478,
"text": "There will be 2 records selected i.e “Compiler Design”, “Php”. These are the results you should see with either one of the SQL statements. In the example, both SELECT statements would return all rows from the subjects table where the subjects are not equal to Java."
},
{
"code": null,
"e": 27841,
"s": 27746,
"text": "Use : To check if a column’s value is not equal to another, we use the inequality operator <>."
},
{
"code": null,
"e": 27848,
"s": 27841,
"text": "Note :"
},
{
"code": null,
"e": 28055,
"s": 27848,
"text": "\nWhat kind of value can we use the inequality operator <> with?Ans- Any kind like text and numbers. \nWhen is the inequality sign useful ?Ans- When you want to get all items that don’t satisfy a criterion. \n"
},
{
"code": null,
"e": 28155,
"s": 28055,
"text": "What kind of value can we use the inequality operator <> with?Ans- Any kind like text and numbers. "
},
{
"code": null,
"e": 28260,
"s": 28155,
"text": "When is the inequality sign useful ?Ans- When you want to get all items that don’t satisfy a criterion. "
},
{
"code": null,
"e": 28271,
"s": 28260,
"text": "\nDBMS-SQL\n"
},
{
"code": null,
"e": 28277,
"s": 28271,
"text": "\nSQL\n"
},
{
"code": null,
"e": 28482,
"s": 28277,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28548,
"s": 28482,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28563,
"s": 28548,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28595,
"s": 28563,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28652,
"s": 28595,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28730,
"s": 28652,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28747,
"s": 28730,
"text": "SQL using Python"
},
{
"code": null,
"e": 28783,
"s": 28747,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28814,
"s": 28783,
"text": "SQL Query to Compare Two Dates"
},
{
"code": null,
"e": 28880,
"s": 28814,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
Minimum deletions from string to reduce it to string with at most 2 unique characters - GeeksforGeeks
|
25 May, 2021
Given a string containing lowercase English alphabets. The task is to find the minimum number of characters needed to be removed so that the remaining string contains at most 2 unique characters.Note: The final string can have duplicate characters. The task is only to reduce the string with minimum deletions such that there can be a maximum of 2 unique characters in the resultant string.
Examples:
Input: S = “geeksforgeeks” Output: 7 After removing 7 characters, the final string will be “geegee”
Input: S = “helloworld” Output: 5
Approach: First count the occurrences of each character within the given string, then just select two characters with the maximum occurrence, i.e. the two most frequently occurring characters in the string. And the result will be:
String length – (Occurrence of 1st most frequent character + Occurrence of 2nd most frequent character)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include<bits/stdc++.h>using namespace std; // Function to find the minimum deletionsint check(string s){ int i, j; // Array to store the occurrences // of each characters int fr[26] = {0} ; // Length of the string int n = s.size() ; for(i = 0; i < n; i++) { // ASCII of the character char x = s[i] ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = INT_MAX; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = min(minimum, n - z) ; } } return minimum ;} /* Driver code */int main(){ string s ="geeksforgeeks" ; cout << check(s) ;} // This code is contributed by ihritik
// Java implementation of the above approach public class GFG{ // Function to find the minimum deletionsstatic int check(String s){ int i,j; // Array to store the occurrences // of each characters int fr[] = new int[26] ; // Length of the string int n = s.length() ; for(i = 0; i < n; i++) { // ASCII of the character char x = s.charAt(i) ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = Integer.MAX_VALUE; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.min(minimum, n-z) ; } } return minimum ;} /* Driver program to test above functions */ public static void main(String []args){ String s ="geeksforgeeks" ; System.out.println(check(s)) ; } // This code is contributed by ANKITRAI1}
# Python3 implementation of the above approach # Function to find the minimum deletionsdef check(s): # Array to store the occurrences # of each characters fr =[0]*26 # Length of the string n = len(s) for i in range(n): # ASCII of the character x = ord(s[i]) # Increasing the frequency for this character fr[x-97] += 1 minimum = 99999999999 for i in range(26): for j in range(i + 1, 26): # Choosing two character z = fr[i] + fr[j] # Finding the minimum deletion minimum = min(minimum, n-z) return minimum # Driver codes ="geeksforgeeks"print(check(s))
// C# implementation of the above approach using System;public class GFG{ // Function to find the minimum deletionsstatic int check(string s){ int i,j; // Array to store the occurrences // of each characters int[] fr = new int[26] ; // Length of the string int n = s.Length ; for(i = 0; i < n; i++) { // ASCII of the character char x = s[i] ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = int.MaxValue; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.Min(minimum, n-z) ; } } return minimum ;} /* Driver program to test above functions */ public static void Main(){ string s ="geeksforgeeks" ; Console.Write(check(s)) ; }}
<script> // Javascript implementation of the above approach // Function to find the minimum deletionsfunction check(s){ var i, j; // Array to store the occurrences // of each characters var fr = Array(26).fill(0); // Length of the string var n = s.length ; for(i = 0; i < n; i++) { // ASCII of the character var x = s[i] ; // Increasing the frequency for this character fr[x.charCodeAt(0) -'a'.charCodeAt(0)] += 1 ; } var minimum = 10000000000; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character var z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.min(minimum, n - z) ; } } return minimum ;} /* Driver code */var s ="geeksforgeeks" ;document.write( check(s)); </script>
7
Time Complexity: O(N), where N is the length of the given string.
ankthon
ukasp
ihritik
importantly
frequency-counting
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 26607,
"s": 26579,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26998,
"s": 26607,
"text": "Given a string containing lowercase English alphabets. The task is to find the minimum number of characters needed to be removed so that the remaining string contains at most 2 unique characters.Note: The final string can have duplicate characters. The task is only to reduce the string with minimum deletions such that there can be a maximum of 2 unique characters in the resultant string."
},
{
"code": null,
"e": 27010,
"s": 26998,
"text": "Examples: "
},
{
"code": null,
"e": 27110,
"s": 27010,
"text": "Input: S = “geeksforgeeks” Output: 7 After removing 7 characters, the final string will be “geegee”"
},
{
"code": null,
"e": 27145,
"s": 27110,
"text": "Input: S = “helloworld” Output: 5 "
},
{
"code": null,
"e": 27378,
"s": 27145,
"text": "Approach: First count the occurrences of each character within the given string, then just select two characters with the maximum occurrence, i.e. the two most frequently occurring characters in the string. And the result will be: "
},
{
"code": null,
"e": 27482,
"s": 27378,
"text": "String length – (Occurrence of 1st most frequent character + Occurrence of 2nd most frequent character)"
},
{
"code": null,
"e": 27535,
"s": 27482,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27539,
"s": 27535,
"text": "C++"
},
{
"code": null,
"e": 27544,
"s": 27539,
"text": "Java"
},
{
"code": null,
"e": 27552,
"s": 27544,
"text": "Python3"
},
{
"code": null,
"e": 27555,
"s": 27552,
"text": "C#"
},
{
"code": null,
"e": 27566,
"s": 27555,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include<bits/stdc++.h>using namespace std; // Function to find the minimum deletionsint check(string s){ int i, j; // Array to store the occurrences // of each characters int fr[26] = {0} ; // Length of the string int n = s.size() ; for(i = 0; i < n; i++) { // ASCII of the character char x = s[i] ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = INT_MAX; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = min(minimum, n - z) ; } } return minimum ;} /* Driver code */int main(){ string s =\"geeksforgeeks\" ; cout << check(s) ;} // This code is contributed by ihritik",
"e": 28485,
"s": 27566,
"text": null
},
{
"code": "// Java implementation of the above approach public class GFG{ // Function to find the minimum deletionsstatic int check(String s){ int i,j; // Array to store the occurrences // of each characters int fr[] = new int[26] ; // Length of the string int n = s.length() ; for(i = 0; i < n; i++) { // ASCII of the character char x = s.charAt(i) ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = Integer.MAX_VALUE; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.min(minimum, n-z) ; } } return minimum ;} /* Driver program to test above functions */ public static void main(String []args){ String s =\"geeksforgeeks\" ; System.out.println(check(s)) ; } // This code is contributed by ANKITRAI1}",
"e": 29525,
"s": 28485,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to find the minimum deletionsdef check(s): # Array to store the occurrences # of each characters fr =[0]*26 # Length of the string n = len(s) for i in range(n): # ASCII of the character x = ord(s[i]) # Increasing the frequency for this character fr[x-97] += 1 minimum = 99999999999 for i in range(26): for j in range(i + 1, 26): # Choosing two character z = fr[i] + fr[j] # Finding the minimum deletion minimum = min(minimum, n-z) return minimum # Driver codes =\"geeksforgeeks\"print(check(s))",
"e": 30191,
"s": 29525,
"text": null
},
{
"code": "// C# implementation of the above approach using System;public class GFG{ // Function to find the minimum deletionsstatic int check(string s){ int i,j; // Array to store the occurrences // of each characters int[] fr = new int[26] ; // Length of the string int n = s.Length ; for(i = 0; i < n; i++) { // ASCII of the character char x = s[i] ; // Increasing the frequency for this character fr[x-'a'] += 1 ; } int minimum = int.MaxValue; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character int z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.Min(minimum, n-z) ; } } return minimum ;} /* Driver program to test above functions */ public static void Main(){ string s =\"geeksforgeeks\" ; Console.Write(check(s)) ; }}",
"e": 31182,
"s": 30191,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to find the minimum deletionsfunction check(s){ var i, j; // Array to store the occurrences // of each characters var fr = Array(26).fill(0); // Length of the string var n = s.length ; for(i = 0; i < n; i++) { // ASCII of the character var x = s[i] ; // Increasing the frequency for this character fr[x.charCodeAt(0) -'a'.charCodeAt(0)] += 1 ; } var minimum = 10000000000; for(i = 0 ; i < 26; i++) { for( j = i + 1;j < 26; j++) { // Choosing two character var z = fr[i] + fr[j] ; // Finding the minimum deletion minimum = Math.min(minimum, n - z) ; } } return minimum ;} /* Driver code */var s =\"geeksforgeeks\" ;document.write( check(s)); </script>",
"e": 32073,
"s": 31182,
"text": null
},
{
"code": null,
"e": 32075,
"s": 32073,
"text": "7"
},
{
"code": null,
"e": 32144,
"s": 32077,
"text": "Time Complexity: O(N), where N is the length of the given string. "
},
{
"code": null,
"e": 32152,
"s": 32144,
"text": "ankthon"
},
{
"code": null,
"e": 32158,
"s": 32152,
"text": "ukasp"
},
{
"code": null,
"e": 32166,
"s": 32158,
"text": "ihritik"
},
{
"code": null,
"e": 32178,
"s": 32166,
"text": "importantly"
},
{
"code": null,
"e": 32197,
"s": 32178,
"text": "frequency-counting"
},
{
"code": null,
"e": 32202,
"s": 32197,
"text": "Hash"
},
{
"code": null,
"e": 32210,
"s": 32202,
"text": "Strings"
},
{
"code": null,
"e": 32215,
"s": 32210,
"text": "Hash"
},
{
"code": null,
"e": 32223,
"s": 32215,
"text": "Strings"
},
{
"code": null,
"e": 32321,
"s": 32223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32396,
"s": 32321,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 32453,
"s": 32396,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 32489,
"s": 32453,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32536,
"s": 32489,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 32589,
"s": 32536,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 32625,
"s": 32589,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 32663,
"s": 32625,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 32693,
"s": 32663,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 32745,
"s": 32693,
"text": "Check whether two strings are anagram of each other"
}
] |
Desugaring in Android - GeeksforGeeks
|
21 Dec, 2020
Google has officially announced Kotlin as a recommended language for Android Development and that’s why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of Android devices as well. So Desugaring is also one of the important features in Android that we should enable in our app which will allow our apps to work in lower API levels as well. So in this article, we will learn about Desugaring.
What is Desugaring?
Why we need Desugaring?
Practical Implementation of Desugaring.
What’s happening under the hood?
Android devices are getting optimized day by day. So many features in Android for users as well as developers are getting optimized. When any operating system of Android is developed, it is delivered with so many Java classes which provides support to different apps in user’s devices for various functionalities such as time, date, and many other features. Now if we consider time API it was introduced in API level 26 and the apps which use this API will crash on the lower API level devices such as Marshmallow and lower versions. So in this case to avoid the app crashes Desugaring comes into play. It allows lower API levels to work with new JAVA libraries.
Suppose for example we are using a new time API which is introduced in API level 26 and we have used this API of time in our app. This app will work perfectly for API level 26 and above but when we will install this app on the lower API level let suppose API level 23 or lower than that then our app will crash because our device OS supports the features provided from API level 23 and we are using features of API level 26 which will not work. So for avoiding this app crashes and to support the new features from API level 26 into API level 23 we have to add Desugaring in our app.
When we are using features provided by API level 26 in the devices lower than API level 26 then the app will crash. In the apps with a lower API level, we will get to see an error as NoClassDefFoundError. So to resolve this error we have to enable Desugaring in Android.
Step by Step implementation of Desugaring
Step 1: Navigate to the Gradle Scripts > build.gradle(:app) and inside your dependencies section add the dependency given below
coreLibraryDesugaring ‘com.android.tools:desugar_jdk_libs:1.0.9’
Now after adding this dependency you have to add the below line in your compileOptions part of your code
coreLibraryDesugaringEnabled true
Step 2: Now we have to enable multiDex in our app for that navigate to your Gradle file inside that in the section of defaultConfig section add the below line as
multiDexEnabled true
And sync your project. After the successful project sync, Desugaring has been implemented in our app and now we will not get to see NoClassDefFoundError in the devices with lower API levels. The complete code for the Gradle file is given below:
Kotlin
plugins { id 'com.android.application' id 'kotlin-android'} android { compileSdkVersion 30 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.gtappdevelopers.desugaring" minSdkVersion 19 multiDexEnabled true targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 coreLibraryDesugaringEnabled true } kotlinOptions { jvmTarget = '1.8' }} dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.3.2' coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.2.1' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'}
So what is happening here and how the java classes which were missing suddenly appear here. This is because of D8 and R8 tools. Previously for converting your app’s code in dex code we have to use Proguard but to reduce compile-time and to reduce app size the new R8 tool was introduced. This R8 tool provides the support of missing Java classes. When this tool converts your app’s code into dex code it also adds dex code of new java libraries which are then added in the APK. You can get a clear idea about this process from the below diagram.
In this way, Desugaring works and it provides backward compatibility for new Java libraries in the devices with lower API levels.
android
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26405,
"s": 26377,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 26941,
"s": 26405,
"text": "Google has officially announced Kotlin as a recommended language for Android Development and that’s why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of Android devices as well. So Desugaring is also one of the important features in Android that we should enable in our app which will allow our apps to work in lower API levels as well. So in this article, we will learn about Desugaring."
},
{
"code": null,
"e": 26961,
"s": 26941,
"text": "What is Desugaring?"
},
{
"code": null,
"e": 26985,
"s": 26961,
"text": "Why we need Desugaring?"
},
{
"code": null,
"e": 27025,
"s": 26985,
"text": "Practical Implementation of Desugaring."
},
{
"code": null,
"e": 27058,
"s": 27025,
"text": "What’s happening under the hood?"
},
{
"code": null,
"e": 27722,
"s": 27058,
"text": "Android devices are getting optimized day by day. So many features in Android for users as well as developers are getting optimized. When any operating system of Android is developed, it is delivered with so many Java classes which provides support to different apps in user’s devices for various functionalities such as time, date, and many other features. Now if we consider time API it was introduced in API level 26 and the apps which use this API will crash on the lower API level devices such as Marshmallow and lower versions. So in this case to avoid the app crashes Desugaring comes into play. It allows lower API levels to work with new JAVA libraries. "
},
{
"code": null,
"e": 28307,
"s": 27722,
"text": "Suppose for example we are using a new time API which is introduced in API level 26 and we have used this API of time in our app. This app will work perfectly for API level 26 and above but when we will install this app on the lower API level let suppose API level 23 or lower than that then our app will crash because our device OS supports the features provided from API level 23 and we are using features of API level 26 which will not work. So for avoiding this app crashes and to support the new features from API level 26 into API level 23 we have to add Desugaring in our app. "
},
{
"code": null,
"e": 28579,
"s": 28307,
"text": "When we are using features provided by API level 26 in the devices lower than API level 26 then the app will crash. In the apps with a lower API level, we will get to see an error as NoClassDefFoundError. So to resolve this error we have to enable Desugaring in Android. "
},
{
"code": null,
"e": 28621,
"s": 28579,
"text": "Step by Step implementation of Desugaring"
},
{
"code": null,
"e": 28750,
"s": 28621,
"text": "Step 1: Navigate to the Gradle Scripts > build.gradle(:app) and inside your dependencies section add the dependency given below "
},
{
"code": null,
"e": 28815,
"s": 28750,
"text": "coreLibraryDesugaring ‘com.android.tools:desugar_jdk_libs:1.0.9’"
},
{
"code": null,
"e": 28921,
"s": 28815,
"text": "Now after adding this dependency you have to add the below line in your compileOptions part of your code "
},
{
"code": null,
"e": 28955,
"s": 28921,
"text": "coreLibraryDesugaringEnabled true"
},
{
"code": null,
"e": 29118,
"s": 28955,
"text": "Step 2: Now we have to enable multiDex in our app for that navigate to your Gradle file inside that in the section of defaultConfig section add the below line as "
},
{
"code": null,
"e": 29139,
"s": 29118,
"text": "multiDexEnabled true"
},
{
"code": null,
"e": 29385,
"s": 29139,
"text": "And sync your project. After the successful project sync, Desugaring has been implemented in our app and now we will not get to see NoClassDefFoundError in the devices with lower API levels. The complete code for the Gradle file is given below: "
},
{
"code": null,
"e": 29392,
"s": 29385,
"text": "Kotlin"
},
{
"code": "plugins { id 'com.android.application' id 'kotlin-android'} android { compileSdkVersion 30 buildToolsVersion \"30.0.2\" defaultConfig { applicationId \"com.gtappdevelopers.desugaring\" minSdkVersion 19 multiDexEnabled true targetSdkVersion 30 versionCode 1 versionName \"1.0\" testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 coreLibraryDesugaringEnabled true } kotlinOptions { jvmTarget = '1.8' }} dependencies { implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\" implementation 'androidx.core:core-ktx:1.3.2' coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.2.1' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'}",
"e": 30775,
"s": 29392,
"text": null
},
{
"code": null,
"e": 31322,
"s": 30775,
"text": "So what is happening here and how the java classes which were missing suddenly appear here. This is because of D8 and R8 tools. Previously for converting your app’s code in dex code we have to use Proguard but to reduce compile-time and to reduce app size the new R8 tool was introduced. This R8 tool provides the support of missing Java classes. When this tool converts your app’s code into dex code it also adds dex code of new java libraries which are then added in the APK. You can get a clear idea about this process from the below diagram. "
},
{
"code": null,
"e": 31457,
"s": 31322,
"text": "In this way, Desugaring works and it provides backward compatibility for new Java libraries in the devices with lower API levels. "
},
{
"code": null,
"e": 31465,
"s": 31457,
"text": "android"
},
{
"code": null,
"e": 31473,
"s": 31465,
"text": "Android"
},
{
"code": null,
"e": 31480,
"s": 31473,
"text": "Kotlin"
},
{
"code": null,
"e": 31499,
"s": 31480,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31507,
"s": 31499,
"text": "Android"
},
{
"code": null,
"e": 31605,
"s": 31507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31643,
"s": 31605,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31682,
"s": 31643,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31732,
"s": 31682,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31774,
"s": 31732,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31825,
"s": 31774,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 31844,
"s": 31825,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 31857,
"s": 31844,
"text": "Kotlin Array"
},
{
"code": null,
"e": 31899,
"s": 31857,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31939,
"s": 31899,
"text": "How to Get Current Location in Android?"
}
] |
Leaf nodes from Preorder of a Binary Search Tree - GeeksforGeeks
|
09 Feb, 2022
Given a Preorder traversal of a Binary Search Tree. The task is to print leaf nodes of the Binary Search Tree from the given preorder.Examples:
Input : preorder[] = {890, 325, 290, 530, 965};
Output : 290 530 965
Explanation : Tree represented is,
890
/ \
325 965
/ \
290 530
Input : preorder[] = { 3, 2, 4 };
Output : 2 4
Method 1: (Simple)
The idea is to find Iorder, then traverse the tree in preorder fashion (using both inorder and postorder traversals) and while traversing print leaf nodes.How to traverse in preorder fashion using two arrays representing inorder and preorder traversals? We iterate the preorder array and for each element find that element in the inorder array. For searching, we can use binary search, since inorder traversal of the binary search tree is always sorted. Now, for each element of preorder array, in binary search, we set the range [L, R]. And when L == R, the leaf node is found. So, initially, L = 0 and R = n – 1 for first element (i.e root) of preorder array. Now, to search for the element on the left subtree of the root, set L = 0 and R = index of root – 1. Also, for all element of right subtree set L = index of root + 1 and R = n -1. Recursively, follow this, until L == R.Below is implementation of this approach:
C++
Java
Python3
C#
Javascript
// C++ program to print leaf node from// preorder of binary search tree.#include<bits/stdc++.h>using namespace std; // Binary Searchint binarySearch(int inorder[], int l, int r, int d){ int mid = (l + r)>>1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Function to print Leaf Nodes by doing preorder// traversal of tree using preorder and inorder arrays.void leafNodesRec(int preorder[], int inorder[], int l, int r, int *ind, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { printf("%d ", inorder[l]); *ind = *ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[*ind]); // Incrementing the index. *ind = *ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n);} // Finds leaf nodes from given preorder traversal.void leafNodes(int preorder[], int n){ int inorder[n]; // To store inorder traversal // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. sort(inorder, inorder + n); // Point to the index in preorder. int ind = 0; // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, &ind, n);} // Driven Programint main(){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNodes(preorder, n); return 0;}
// Java program to print leaf node from// preorder of binary search tree.import java.util.*; class GFG{ // Binary Searchstatic int binarySearch(int inorder[], int l, int r, int d){ int mid = (l + r) >> 1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Point to the index in preorder.static int ind; // Function to print Leaf Nodes by// doing preorder traversal of tree// using preorder and inorder arrays.static void leafNodesRec(int preorder[], int inorder[], int l, int r, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { System.out.printf("%d ", inorder[l]); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n);} // Finds leaf nodes from given preorder traversal.static void leafNodes(int preorder[], int n){ // To store inorder traversal int inorder[] = new int[n]; // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. Arrays.sort(inorder); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n);} // Driver Codepublic static void main(String args[]){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = preorder.length; leafNodes(preorder, n);}} // This code is contributed by Arnab Kundu
# Python3 program to print leaf node from# preorder of binary search tree. # Binary Searchdef binarySearch(inorder, l, r, d): mid = (l + r) >> 1 if (inorder[mid] == d): return mid elif (inorder[mid] > d): return binarySearch(inorder, l, mid - 1, d) else: return binarySearch(inorder, mid + 1, r, d) # Function to print Leaf Nodes by doing# preorder traversal of tree using# preorder and inorder arrays.def leafNodesRec(preorder, inorder, l, r, ind, n): # If l == r, therefore no right or left subtree. # So, it must be leaf Node, print it. if(l == r): print(inorder[l], end = " ") ind[0] = ind[0] + 1 return # If array is out of bound, return. if (l < 0 or l > r or r >= n): return # Finding the index of preorder element # in inorder array using binary search. loc = binarySearch(inorder, l, r, preorder[ind[0]]) # Incrementing the index. ind[0] = ind[0] + 1 # Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n) # Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n) # Finds leaf nodes from# given preorder traversal.def leafNodes(preorder, n): # To store inorder traversal inorder = [0] * n # Copy the preorder into another array. for i in range(n): inorder[i] = preorder[i] # Finding the inorder by sorting the array. inorder.sort() # Point to the index in preorder. ind = [0] # Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, ind, n) # Driver Codepreorder = [890, 325, 290, 530, 965]n = len(preorder)leafNodes(preorder, n) # This code is contributed# by SHUBHAMSINGH10
// C# program to print leaf node from// preorder of binary search tree.using System; class GFG{ // Binary Searchstatic int binarySearch(int []inorder, int l, int r, int d){ int mid = (l + r) >> 1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Point to the index in preorder.static int ind; // Function to print Leaf Nodes by// doing preorder traversal of tree// using preorder and inorder arrays.static void leafNodesRec(int []preorder, int []inorder, int l, int r, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { Console.Write("{0} ", inorder[l]); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n);} // Finds leaf nodes from given preorder traversal.static void leafNodes(int []preorder, int n){ // To store inorder traversal int []inorder = new int[n]; // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. Array.Sort(inorder); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n);} // Driver Codepublic static void Main(String []args){ int []preorder = { 890, 325, 290, 530, 965 }; int n = preorder.Length; leafNodes(preorder, n);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to print leaf node from // preorder of binary search tree. // Binary Search function binarySearch(inorder, l, r, d) { var mid = parseInt((l + r) / 2); if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d); } // Point to the index in preorder. var ind = 0; // Function to print Leaf Nodes by // doing preorder traversal of tree // using preorder and inorder arrays. function leafNodesRec(preorder, inorder, l, r, n) { // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if (l == r) { document.write(inorder[l] + " "); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. var loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n); } // Finds leaf nodes from given preorder traversal. function leafNodes(preorder, n) { // To store inorder traversal var inorder = new Array(n).fill(0); // Copy the preorder into another array. for (var i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. inorder.sort(); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n); } // Driver Code var preorder = [890, 325, 290, 530, 965]; var n = preorder.length; leafNodes(preorder, n); </script>
Output:
290 530 965
Time Complexity: O(n log n) Auxiliary Space: O(n)
Method 2:(using Stack)
The idea is to use the property of the Binary Search Tree and stack. Traverse the array using two pointer i and j to the array, initially i = 0 and j = 1. Whenever a[i] > a[j], we can say a[j] is left part of a[i], since preorder traversal follows Visit -> Left -> Right. So, we push a[i] into the stack. For those points violating the rule, we start to pop element from the stack till a[i] > top element of the stack and break when it doesn’t and print the corresponding jth value. Algorithm:
1. Set i = 0, j = 1.
2. Traverse the preorder array.
3. If a[i] > a[j], push a[i] to the stack.
4. Else
While (stack is not empty)
if (a[j] > top of stack)
pop element from the stack;
set found = true;
else
break;
5. if (found == true)
print a[i];
How this algorithm works? Preorder traversal traverse in the order: Visit, Left, Right. And we know the left node of any node in BST is always less than the node. So preorder traversal will first traverse from root to leftmost node. Therefore, preorder will be in decreasing order first. Now, after decreasing order, there may be a node that is greater or which breaks the decreasing order. So, there can be a case like this :
In case 1, 20 is a leaf node whereas in case 2, 20 is not the leaf node. So, our problem is how to identify if we have to print 20 as a leaf node or not? This is solved using stack. While running above algorithm on case 1 and case 2, when i = 2 and j = 3, state of a stack will be the same in both the case :
So, node 65 will pop 20 and 50 from the stack. This is because 65 is the right child of a node which is before 20. This information we store using the found variable. So, 20 is a root node. While in case 2, 40 will not able to pop any element from the stack. Because 40 is the right node of a node which is after 20. So, 20 is not a leaf node.Note: In the algorithm, we will not be able to check the condition of the leaf node of the rightmost node or rightmost element of the preorder. So, simply print the rightmost node because we know this will always be a leaf node in preorder traversal.Below is the implementation of this approach:
C++
Java
Python3
C#
Javascript
// Stack based C++ program to print leaf nodes// from preorder traversal.#include<bits/stdc++.h>using namespace std; // Print the leaf node from the given preorder of BST.void leafNode(int preorder[], int n){ stack<int> s; for (int i = 0, j = 1; j < n; i++, j++) { bool found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (!s.empty()) { if (preorder[j] > s.top()) { s.pop(); found = true; } else break; } } if (found) cout << preorder[i] << " "; } // Since rightmost element is always leaf node. cout << preorder[n - 1];} // Driver codeint main(){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNode(preorder, n); return 0;}
// Stack based Java program to print leaf nodes// from preorder traversal.import java.util.*;class GfG { // Print the leaf node from the given preorder of BST.static void leafNode(int preorder[], int n){ Stack<Integer> s = new Stack<Integer> (); for (int i = 0, j = 1; j < n; i++, j++) { boolean found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (!s.isEmpty()) { if (preorder[j] > s.peek()) { s.pop(); found = true; } else break; } } if (found) System.out.print(preorder[i] + " "); } // Since rightmost element is always leaf node. System.out.println(preorder[n - 1]);} // Driver codepublic static void main(String[] args){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = preorder.length; leafNode(preorder, n);}}
# Stack based Python program to print# leaf nodes from preorder traversal. # Print the leaf node from the given# preorder of BST.def leafNode(preorder, n): s = [] i = 0 for j in range(1, n): found = False if preorder[i] > preorder[j]: s.append(preorder[i]) else: while len(s) != 0: if preorder[j] > s[-1]: s.pop(-1) found = True else: break if found: print(preorder[i], end = " ") i += 1 # Since rightmost element is # always leaf node. print(preorder[n - 1]) # Driver codeif __name__ == '__main__': preorder = [890, 325, 290, 530, 965] n = len(preorder) leafNode(preorder, n) # This code is contributed by PranchalK
using System;using System.Collections.Generic; // Stack based C# program to print leaf nodes // from preorder traversal.public class GfG{ // Print the leaf node from the given preorder of BST. public static void leafNode(int[] preorder, int n){ Stack<int> s = new Stack<int> (); for (int i = 0, j = 1; j < n; i++, j++) { bool found = false; if (preorder[i] > preorder[j]) { s.Push(preorder[i]); } else { while (s.Count > 0) { if (preorder[j] > s.Peek()) { s.Pop(); found = true; } else { break; } } } if (found) { Console.Write(preorder[i] + " "); } } // Since rightmost element is always leaf node. Console.WriteLine(preorder[n - 1]);} // Driver code public static void Main(string[] args){ int[] preorder = new int[] {890, 325, 290, 530, 965}; int n = preorder.Length; leafNode(preorder, n);}} // This code is contributed by Shrikant13
<script> // Stack based Javascript program to print leaf nodes // from preorder traversal. // Print the leaf node from the given preorder of BST. function leafNode(preorder, n) { let s = []; for (let i = 0, j = 1; j < n; i++, j++) { let found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (s.length > 0) { if (preorder[j] > s[s.length - 1]) { s.pop(); found = true; } else break; } } if (found) document.write(preorder[i] + " "); } // Since rightmost element is always leaf node. document.write(preorder[n - 1]); } let preorder = [ 890, 325, 290, 530, 965 ]; let n = preorder.length; leafNode(preorder, n); // This code is contributed by mukesh07.</script>
Output:
290 530 965
Time Complexity: O(n)Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prerna saini
shrikanth13
PranchalKatiyar
SHUBHAMSINGH10
Akanksha_Rai
nidhi_biet
andrew1234
Rajput-Ji
Code_Mech
mukesh07
rdtank
surinderdawra388
simmytarika5
Binary Search
Binary Search Tree
Binary Search Tree
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Construct BST from given preorder traversal | Set 2
Red Black Tree vs AVL Tree
Find median of BST in O(n) time and O(1) space
Print BST keys in the given range
Binary Search Tree | Set 3 (Iterative Delete)
Find the largest BST subtree in a given Binary Tree | Set 1
Find the node with maximum value in a Binary Search Tree
Construct all possible BSTs for keys 1 to N
Construct BST from its given level order traversal
|
[
{
"code": null,
"e": 26469,
"s": 26441,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 26615,
"s": 26469,
"text": "Given a Preorder traversal of a Binary Search Tree. The task is to print leaf nodes of the Binary Search Tree from the given preorder.Examples: "
},
{
"code": null,
"e": 26818,
"s": 26615,
"text": "Input : preorder[] = {890, 325, 290, 530, 965};\nOutput : 290 530 965\nExplanation : Tree represented is,\n 890\n / \\\n 325 965\n / \\\n290 530\n\nInput : preorder[] = { 3, 2, 4 };\nOutput : 2 4"
},
{
"code": null,
"e": 26841,
"s": 26822,
"text": "Method 1: (Simple)"
},
{
"code": null,
"e": 27765,
"s": 26841,
"text": "The idea is to find Iorder, then traverse the tree in preorder fashion (using both inorder and postorder traversals) and while traversing print leaf nodes.How to traverse in preorder fashion using two arrays representing inorder and preorder traversals? We iterate the preorder array and for each element find that element in the inorder array. For searching, we can use binary search, since inorder traversal of the binary search tree is always sorted. Now, for each element of preorder array, in binary search, we set the range [L, R]. And when L == R, the leaf node is found. So, initially, L = 0 and R = n – 1 for first element (i.e root) of preorder array. Now, to search for the element on the left subtree of the root, set L = 0 and R = index of root – 1. Also, for all element of right subtree set L = index of root + 1 and R = n -1. Recursively, follow this, until L == R.Below is implementation of this approach: "
},
{
"code": null,
"e": 27769,
"s": 27765,
"text": "C++"
},
{
"code": null,
"e": 27774,
"s": 27769,
"text": "Java"
},
{
"code": null,
"e": 27782,
"s": 27774,
"text": "Python3"
},
{
"code": null,
"e": 27785,
"s": 27782,
"text": "C#"
},
{
"code": null,
"e": 27796,
"s": 27785,
"text": "Javascript"
},
{
"code": "// C++ program to print leaf node from// preorder of binary search tree.#include<bits/stdc++.h>using namespace std; // Binary Searchint binarySearch(int inorder[], int l, int r, int d){ int mid = (l + r)>>1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Function to print Leaf Nodes by doing preorder// traversal of tree using preorder and inorder arrays.void leafNodesRec(int preorder[], int inorder[], int l, int r, int *ind, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { printf(\"%d \", inorder[l]); *ind = *ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[*ind]); // Incrementing the index. *ind = *ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n);} // Finds leaf nodes from given preorder traversal.void leafNodes(int preorder[], int n){ int inorder[n]; // To store inorder traversal // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. sort(inorder, inorder + n); // Point to the index in preorder. int ind = 0; // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, &ind, n);} // Driven Programint main(){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNodes(preorder, n); return 0;}",
"e": 29702,
"s": 27796,
"text": null
},
{
"code": "// Java program to print leaf node from// preorder of binary search tree.import java.util.*; class GFG{ // Binary Searchstatic int binarySearch(int inorder[], int l, int r, int d){ int mid = (l + r) >> 1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Point to the index in preorder.static int ind; // Function to print Leaf Nodes by// doing preorder traversal of tree// using preorder and inorder arrays.static void leafNodesRec(int preorder[], int inorder[], int l, int r, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { System.out.printf(\"%d \", inorder[l]); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n);} // Finds leaf nodes from given preorder traversal.static void leafNodes(int preorder[], int n){ // To store inorder traversal int inorder[] = new int[n]; // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. Arrays.sort(inorder); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n);} // Driver Codepublic static void main(String args[]){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = preorder.length; leafNodes(preorder, n);}} // This code is contributed by Arnab Kundu",
"e": 31811,
"s": 29702,
"text": null
},
{
"code": "# Python3 program to print leaf node from# preorder of binary search tree. # Binary Searchdef binarySearch(inorder, l, r, d): mid = (l + r) >> 1 if (inorder[mid] == d): return mid elif (inorder[mid] > d): return binarySearch(inorder, l, mid - 1, d) else: return binarySearch(inorder, mid + 1, r, d) # Function to print Leaf Nodes by doing# preorder traversal of tree using# preorder and inorder arrays.def leafNodesRec(preorder, inorder, l, r, ind, n): # If l == r, therefore no right or left subtree. # So, it must be leaf Node, print it. if(l == r): print(inorder[l], end = \" \") ind[0] = ind[0] + 1 return # If array is out of bound, return. if (l < 0 or l > r or r >= n): return # Finding the index of preorder element # in inorder array using binary search. loc = binarySearch(inorder, l, r, preorder[ind[0]]) # Incrementing the index. ind[0] = ind[0] + 1 # Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n) # Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n) # Finds leaf nodes from# given preorder traversal.def leafNodes(preorder, n): # To store inorder traversal inorder = [0] * n # Copy the preorder into another array. for i in range(n): inorder[i] = preorder[i] # Finding the inorder by sorting the array. inorder.sort() # Point to the index in preorder. ind = [0] # Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, ind, n) # Driver Codepreorder = [890, 325, 290, 530, 965]n = len(preorder)leafNodes(preorder, n) # This code is contributed# by SHUBHAMSINGH10",
"e": 33673,
"s": 31811,
"text": null
},
{
"code": "// C# program to print leaf node from// preorder of binary search tree.using System; class GFG{ // Binary Searchstatic int binarySearch(int []inorder, int l, int r, int d){ int mid = (l + r) >> 1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d);} // Point to the index in preorder.static int ind; // Function to print Leaf Nodes by// doing preorder traversal of tree// using preorder and inorder arrays.static void leafNodesRec(int []preorder, int []inorder, int l, int r, int n){ // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { Console.Write(\"{0} \", inorder[l]); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n);} // Finds leaf nodes from given preorder traversal.static void leafNodes(int []preorder, int n){ // To store inorder traversal int []inorder = new int[n]; // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. Array.Sort(inorder); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n);} // Driver Codepublic static void Main(String []args){ int []preorder = { 890, 325, 290, 530, 965 }; int n = preorder.Length; leafNodes(preorder, n);}} // This code is contributed by Rajput-Ji",
"e": 35763,
"s": 33673,
"text": null
},
{
"code": "<script> // JavaScript program to print leaf node from // preorder of binary search tree. // Binary Search function binarySearch(inorder, l, r, d) { var mid = parseInt((l + r) / 2); if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d); } // Point to the index in preorder. var ind = 0; // Function to print Leaf Nodes by // doing preorder traversal of tree // using preorder and inorder arrays. function leafNodesRec(preorder, inorder, l, r, n) { // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if (l == r) { document.write(inorder[l] + \" \"); ind = ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. var loc = binarySearch(inorder, l, r, preorder[ind]); // Incrementing the index. ind = ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, n); } // Finds leaf nodes from given preorder traversal. function leafNodes(preorder, n) { // To store inorder traversal var inorder = new Array(n).fill(0); // Copy the preorder into another array. for (var i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. inorder.sort(); // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, n); } // Driver Code var preorder = [890, 325, 290, 530, 965]; var n = preorder.length; leafNodes(preorder, n); </script>",
"e": 37733,
"s": 35763,
"text": null
},
{
"code": null,
"e": 37743,
"s": 37733,
"text": "Output: "
},
{
"code": null,
"e": 37755,
"s": 37743,
"text": "290 530 965"
},
{
"code": null,
"e": 37806,
"s": 37755,
"text": "Time Complexity: O(n log n) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 37829,
"s": 37806,
"text": "Method 2:(using Stack)"
},
{
"code": null,
"e": 38325,
"s": 37829,
"text": "The idea is to use the property of the Binary Search Tree and stack. Traverse the array using two pointer i and j to the array, initially i = 0 and j = 1. Whenever a[i] > a[j], we can say a[j] is left part of a[i], since preorder traversal follows Visit -> Left -> Right. So, we push a[i] into the stack. For those points violating the rule, we start to pop element from the stack till a[i] > top element of the stack and break when it doesn’t and print the corresponding jth value. Algorithm: "
},
{
"code": null,
"e": 38612,
"s": 38325,
"text": "1. Set i = 0, j = 1.\n2. Traverse the preorder array.\n3. If a[i] > a[j], push a[i] to the stack.\n4. Else\n While (stack is not empty)\n if (a[j] > top of stack)\n pop element from the stack;\n set found = true;\n else\n break;\n5. if (found == true)\n print a[i];"
},
{
"code": null,
"e": 39041,
"s": 38612,
"text": "How this algorithm works? Preorder traversal traverse in the order: Visit, Left, Right. And we know the left node of any node in BST is always less than the node. So preorder traversal will first traverse from root to leftmost node. Therefore, preorder will be in decreasing order first. Now, after decreasing order, there may be a node that is greater or which breaks the decreasing order. So, there can be a case like this : "
},
{
"code": null,
"e": 39352,
"s": 39041,
"text": "In case 1, 20 is a leaf node whereas in case 2, 20 is not the leaf node. So, our problem is how to identify if we have to print 20 as a leaf node or not? This is solved using stack. While running above algorithm on case 1 and case 2, when i = 2 and j = 3, state of a stack will be the same in both the case : "
},
{
"code": null,
"e": 39993,
"s": 39352,
"text": "So, node 65 will pop 20 and 50 from the stack. This is because 65 is the right child of a node which is before 20. This information we store using the found variable. So, 20 is a root node. While in case 2, 40 will not able to pop any element from the stack. Because 40 is the right node of a node which is after 20. So, 20 is not a leaf node.Note: In the algorithm, we will not be able to check the condition of the leaf node of the rightmost node or rightmost element of the preorder. So, simply print the rightmost node because we know this will always be a leaf node in preorder traversal.Below is the implementation of this approach: "
},
{
"code": null,
"e": 39997,
"s": 39993,
"text": "C++"
},
{
"code": null,
"e": 40002,
"s": 39997,
"text": "Java"
},
{
"code": null,
"e": 40010,
"s": 40002,
"text": "Python3"
},
{
"code": null,
"e": 40013,
"s": 40010,
"text": "C#"
},
{
"code": null,
"e": 40024,
"s": 40013,
"text": "Javascript"
},
{
"code": "// Stack based C++ program to print leaf nodes// from preorder traversal.#include<bits/stdc++.h>using namespace std; // Print the leaf node from the given preorder of BST.void leafNode(int preorder[], int n){ stack<int> s; for (int i = 0, j = 1; j < n; i++, j++) { bool found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (!s.empty()) { if (preorder[j] > s.top()) { s.pop(); found = true; } else break; } } if (found) cout << preorder[i] << \" \"; } // Since rightmost element is always leaf node. cout << preorder[n - 1];} // Driver codeint main(){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNode(preorder, n); return 0;}",
"e": 40975,
"s": 40024,
"text": null
},
{
"code": "// Stack based Java program to print leaf nodes// from preorder traversal.import java.util.*;class GfG { // Print the leaf node from the given preorder of BST.static void leafNode(int preorder[], int n){ Stack<Integer> s = new Stack<Integer> (); for (int i = 0, j = 1; j < n; i++, j++) { boolean found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (!s.isEmpty()) { if (preorder[j] > s.peek()) { s.pop(); found = true; } else break; } } if (found) System.out.print(preorder[i] + \" \"); } // Since rightmost element is always leaf node. System.out.println(preorder[n - 1]);} // Driver codepublic static void main(String[] args){ int preorder[] = { 890, 325, 290, 530, 965 }; int n = preorder.length; leafNode(preorder, n);}}",
"e": 41971,
"s": 40975,
"text": null
},
{
"code": "# Stack based Python program to print# leaf nodes from preorder traversal. # Print the leaf node from the given# preorder of BST.def leafNode(preorder, n): s = [] i = 0 for j in range(1, n): found = False if preorder[i] > preorder[j]: s.append(preorder[i]) else: while len(s) != 0: if preorder[j] > s[-1]: s.pop(-1) found = True else: break if found: print(preorder[i], end = \" \") i += 1 # Since rightmost element is # always leaf node. print(preorder[n - 1]) # Driver codeif __name__ == '__main__': preorder = [890, 325, 290, 530, 965] n = len(preorder) leafNode(preorder, n) # This code is contributed by PranchalK",
"e": 42774,
"s": 41971,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // Stack based C# program to print leaf nodes // from preorder traversal.public class GfG{ // Print the leaf node from the given preorder of BST. public static void leafNode(int[] preorder, int n){ Stack<int> s = new Stack<int> (); for (int i = 0, j = 1; j < n; i++, j++) { bool found = false; if (preorder[i] > preorder[j]) { s.Push(preorder[i]); } else { while (s.Count > 0) { if (preorder[j] > s.Peek()) { s.Pop(); found = true; } else { break; } } } if (found) { Console.Write(preorder[i] + \" \"); } } // Since rightmost element is always leaf node. Console.WriteLine(preorder[n - 1]);} // Driver code public static void Main(string[] args){ int[] preorder = new int[] {890, 325, 290, 530, 965}; int n = preorder.Length; leafNode(preorder, n);}} // This code is contributed by Shrikant13",
"e": 43919,
"s": 42774,
"text": null
},
{
"code": "<script> // Stack based Javascript program to print leaf nodes // from preorder traversal. // Print the leaf node from the given preorder of BST. function leafNode(preorder, n) { let s = []; for (let i = 0, j = 1; j < n; i++, j++) { let found = false; if (preorder[i] > preorder[j]) s.push(preorder[i]); else { while (s.length > 0) { if (preorder[j] > s[s.length - 1]) { s.pop(); found = true; } else break; } } if (found) document.write(preorder[i] + \" \"); } // Since rightmost element is always leaf node. document.write(preorder[n - 1]); } let preorder = [ 890, 325, 290, 530, 965 ]; let n = preorder.length; leafNode(preorder, n); // This code is contributed by mukesh07.</script>",
"e": 44978,
"s": 43919,
"text": null
},
{
"code": null,
"e": 44988,
"s": 44978,
"text": "Output: "
},
{
"code": null,
"e": 45000,
"s": 44988,
"text": "290 530 965"
},
{
"code": null,
"e": 45508,
"s": 45000,
"text": "Time Complexity: O(n)Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 45521,
"s": 45508,
"text": "prerna saini"
},
{
"code": null,
"e": 45533,
"s": 45521,
"text": "shrikanth13"
},
{
"code": null,
"e": 45549,
"s": 45533,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 45564,
"s": 45549,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 45577,
"s": 45564,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 45588,
"s": 45577,
"text": "nidhi_biet"
},
{
"code": null,
"e": 45599,
"s": 45588,
"text": "andrew1234"
},
{
"code": null,
"e": 45609,
"s": 45599,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 45619,
"s": 45609,
"text": "Code_Mech"
},
{
"code": null,
"e": 45628,
"s": 45619,
"text": "mukesh07"
},
{
"code": null,
"e": 45635,
"s": 45628,
"text": "rdtank"
},
{
"code": null,
"e": 45652,
"s": 45635,
"text": "surinderdawra388"
},
{
"code": null,
"e": 45665,
"s": 45652,
"text": "simmytarika5"
},
{
"code": null,
"e": 45679,
"s": 45665,
"text": "Binary Search"
},
{
"code": null,
"e": 45698,
"s": 45679,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 45717,
"s": 45698,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 45731,
"s": 45717,
"text": "Binary Search"
},
{
"code": null,
"e": 45829,
"s": 45731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45861,
"s": 45829,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 45913,
"s": 45861,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 45940,
"s": 45913,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 45987,
"s": 45940,
"text": "Find median of BST in O(n) time and O(1) space"
},
{
"code": null,
"e": 46021,
"s": 45987,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 46067,
"s": 46021,
"text": "Binary Search Tree | Set 3 (Iterative Delete)"
},
{
"code": null,
"e": 46127,
"s": 46067,
"text": "Find the largest BST subtree in a given Binary Tree | Set 1"
},
{
"code": null,
"e": 46184,
"s": 46127,
"text": "Find the node with maximum value in a Binary Search Tree"
},
{
"code": null,
"e": 46228,
"s": 46184,
"text": "Construct all possible BSTs for keys 1 to N"
}
] |
Python | Pandas Series.quantile() - GeeksforGeeks
|
11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.quantile() function return value at the given quantile for the underlying data in the given Series object.
Syntax: Series.quantile(q=0.5, interpolation=’linear’)
Parameter :q : float or array-like, default 0.5 (50% quantile)interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
Returns : quantile : float or Series
Example #1: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.quantile() function to find the 40% quantile of the underlying data in the given series object.
# return the value of 40 % quantileresult = sr.quantile(q = 0.4) # Print the resultprint(result)
Output :
As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object.
Example #2: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Print the seriesprint(sr)
Output :
Now we will use Series.quantile() function to find the 90% quantile of the underlying data in the given series object.
# return the value of 90 % quantileresult = sr.quantile(q = 0.9) # Print the resultprint(result)
Output :
As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26119,
"s": 26091,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 26376,
"s": 26119,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 26497,
"s": 26376,
"text": "Pandas Series.quantile() function return value at the given quantile for the underlying data in the given Series object."
},
{
"code": null,
"e": 26552,
"s": 26497,
"text": "Syntax: Series.quantile(q=0.5, interpolation=’linear’)"
},
{
"code": null,
"e": 26683,
"s": 26552,
"text": "Parameter :q : float or array-like, default 0.5 (50% quantile)interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}"
},
{
"code": null,
"e": 26720,
"s": 26683,
"text": "Returns : quantile : float or Series"
},
{
"code": null,
"e": 26845,
"s": 26720,
"text": "Example #1: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 27101,
"s": 26845,
"text": null
},
{
"code": null,
"e": 27110,
"s": 27101,
"text": "Output :"
},
{
"code": null,
"e": 27229,
"s": 27110,
"text": "Now we will use Series.quantile() function to find the 40% quantile of the underlying data in the given series object."
},
{
"code": "# return the value of 40 % quantileresult = sr.quantile(q = 0.4) # Print the resultprint(result)",
"e": 27327,
"s": 27229,
"text": null
},
{
"code": null,
"e": 27336,
"s": 27327,
"text": "Output :"
},
{
"code": null,
"e": 27500,
"s": 27336,
"text": "As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object."
},
{
"code": null,
"e": 27625,
"s": 27500,
"text": "Example #2: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Print the seriesprint(sr)",
"e": 27779,
"s": 27625,
"text": null
},
{
"code": null,
"e": 27788,
"s": 27779,
"text": "Output :"
},
{
"code": null,
"e": 27907,
"s": 27788,
"text": "Now we will use Series.quantile() function to find the 90% quantile of the underlying data in the given series object."
},
{
"code": "# return the value of 90 % quantileresult = sr.quantile(q = 0.9) # Print the resultprint(result)",
"e": 28005,
"s": 27907,
"text": null
},
{
"code": null,
"e": 28014,
"s": 28005,
"text": "Output :"
},
{
"code": null,
"e": 28178,
"s": 28014,
"text": "As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object."
},
{
"code": null,
"e": 28199,
"s": 28178,
"text": "Python pandas-series"
},
{
"code": null,
"e": 28228,
"s": 28199,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 28242,
"s": 28228,
"text": "Python-pandas"
},
{
"code": null,
"e": 28249,
"s": 28242,
"text": "Python"
},
{
"code": null,
"e": 28347,
"s": 28249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28365,
"s": 28347,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28400,
"s": 28365,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28432,
"s": 28400,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28454,
"s": 28432,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28496,
"s": 28454,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28526,
"s": 28496,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28555,
"s": 28526,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28599,
"s": 28555,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28635,
"s": 28599,
"text": "Convert integer to string in Python"
}
] |
PyQt5 - Count the number of items in ComboBox - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can find the total number of items present in the combo box. We know we can add items in the combo box with the help of addItem method to add single item and addItems method to add multiple items. In order to get the count of all the items in the combo box we will use count method.
Syntax : combo_box.count()
Argument : It takes no argument
Return : It will return integer i.e number of items in combo box
Steps for implementation:
1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action count the items of combo box with the help of count method and store it in variable6. Show the count variable in label with the help of setText method
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button to clear the list button = QPushButton("Find Count ", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find_count) # creating label to show count self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find_count(self): # finding the number of items in cmbo box count = self.combo_box.count() # showing count on the screen though label self.label.setText("Total number of items : " + str(count)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25667,
"s": 25639,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25985,
"s": 25667,
"text": "In this article we will see how we can find the total number of items present in the combo box. We know we can add items in the combo box with the help of addItem method to add single item and addItems method to add multiple items. In order to get the count of all the items in the combo box we will use count method."
},
{
"code": null,
"e": 26012,
"s": 25985,
"text": "Syntax : combo_box.count()"
},
{
"code": null,
"e": 26044,
"s": 26012,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 26109,
"s": 26044,
"text": "Return : It will return integer i.e number of items in combo box"
},
{
"code": null,
"e": 26135,
"s": 26109,
"text": "Steps for implementation:"
},
{
"code": null,
"e": 26435,
"s": 26135,
"text": "1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action count the items of combo box with the help of count method and store it in variable6. Show the count variable in label with the help of setText method"
},
{
"code": null,
"e": 26465,
"s": 26435,
"text": "Below is the implementation –"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button to clear the list button = QPushButton(\"Find Count \", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find_count) # creating label to show count self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find_count(self): # finding the number of items in cmbo box count = self.combo_box.count() # showing count on the screen though label self.label.setText(\"Total number of items : \" + str(count)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28104,
"s": 26465,
"text": null
},
{
"code": null,
"e": 28113,
"s": 28104,
"text": "Output :"
},
{
"code": null,
"e": 28135,
"s": 28113,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 28146,
"s": 28135,
"text": "Python-gui"
},
{
"code": null,
"e": 28158,
"s": 28146,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28165,
"s": 28158,
"text": "Python"
},
{
"code": null,
"e": 28263,
"s": 28165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28281,
"s": 28263,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28316,
"s": 28281,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28348,
"s": 28316,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28370,
"s": 28348,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28412,
"s": 28370,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28442,
"s": 28412,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28468,
"s": 28442,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28497,
"s": 28468,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28541,
"s": 28497,
"text": "Reading and Writing to text files in Python"
}
] |
'IPCS' command in Linux with examples - GeeksforGeeks
|
22 May, 2019
ipcs shows information on the inter-process communication facilities for which the calling process has read access. By default, it shows information about all three resources: shared memory segments, message queues, and semaphore arrays.Without options, the information shall be written in short format for message queues, shared memory segments, and semaphore sets that are currently active in the system. Otherwise, the information that is displayed is controlled by the options specified.
Options :
-q : Write information about active message queues.
-m : Write information about active shared memory segments.
-s : Write information about active semaphore sets.
-a : Use all print options. (This is a shorthand notation for -b, -c, -o, -p, and -t.)
-b : Write information on maximum allowable size. (Maximum number of bytes in messages on queue for message queues, size of segments for shared memory, and number of semaphores in each set for semaphores.)
-c : Write creator’s user name and group name;.
-o : Write information on outstanding usage. (Number of messages on queue and total number of bytes in messages on queue for message queues, and number of processes attached to shared memory segments.)
-p : Write process number information. (Process ID of the last process to send a message and process ID of the last process to receive a message on message queues, process ID of the creating process, and process ID of the last process to attach or detach on shared memory segments.)
-t : Write time information. (Time of the last control operation that changed the access permissions for all facilities, time of the last msgsnd() and msgrcv() operations on message queues, time of the last shmat() and shmdt() operations on shared memory, and time of the last semop() operation on semaphores.)
Examples on IPCS command:
1: To list all the IPC facility
# ipcs -a : It provides details about message queue, semaphore and shared memory.
All the IPC facility has unique key and identifier, which is used to identify an IPC facility.
2: To list all the Message Queue
$ ipcs -q : It lists only message queues for which the current process has read access.
3. To list all the Semaphores
# ipcs -s : To list the accessible semaphores.
4. To list all the Shared Memory
# ipcs -m : To lists the shared memories.
5. To get the detailed information about an IPC facility
# ipcs -m -i 425984 : To detailed information about an ipc facility(here for id-425984).
6. To lists the Limits for IPC facility
# ipcs -m -l : To get the system limits for each ipc facility.
# ipcs -l : To get the limits for all three IPC facilities.
7. To list Creator and Owner Details for IPC Facility
# ipcs -m -c : To list creator userid and groupid and owner userid and group id.
8. To get the process ids that accessed IPC facility recently
# ipcs -m -p : To displays creator id, and process id which accessed the corresponding ipc facility very recently.
9. To get the last Accessed Time
# ipcs -s -t : To get the last operation time in each ipc facility.
10. To get the status of current usage
# ipcs -u : To display current usage for all the IPC facility.
Reference: IPCS Linux Manual Page
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
linux-command
Linux-system-commands
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Top Programming Languages for Android App Development
Setting up the environment in Java
How to Run a Python Script using Docker?
|
[
{
"code": null,
"e": 25281,
"s": 25253,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 25773,
"s": 25281,
"text": "ipcs shows information on the inter-process communication facilities for which the calling process has read access. By default, it shows information about all three resources: shared memory segments, message queues, and semaphore arrays.Without options, the information shall be written in short format for message queues, shared memory segments, and semaphore sets that are currently active in the system. Otherwise, the information that is displayed is controlled by the options specified."
},
{
"code": null,
"e": 25783,
"s": 25773,
"text": "Options :"
},
{
"code": null,
"e": 25835,
"s": 25783,
"text": "-q : Write information about active message queues."
},
{
"code": null,
"e": 25895,
"s": 25835,
"text": "-m : Write information about active shared memory segments."
},
{
"code": null,
"e": 25947,
"s": 25895,
"text": "-s : Write information about active semaphore sets."
},
{
"code": null,
"e": 26034,
"s": 25947,
"text": "-a : Use all print options. (This is a shorthand notation for -b, -c, -o, -p, and -t.)"
},
{
"code": null,
"e": 26240,
"s": 26034,
"text": "-b : Write information on maximum allowable size. (Maximum number of bytes in messages on queue for message queues, size of segments for shared memory, and number of semaphores in each set for semaphores.)"
},
{
"code": null,
"e": 26288,
"s": 26240,
"text": "-c : Write creator’s user name and group name;."
},
{
"code": null,
"e": 26490,
"s": 26288,
"text": "-o : Write information on outstanding usage. (Number of messages on queue and total number of bytes in messages on queue for message queues, and number of processes attached to shared memory segments.)"
},
{
"code": null,
"e": 26773,
"s": 26490,
"text": "-p : Write process number information. (Process ID of the last process to send a message and process ID of the last process to receive a message on message queues, process ID of the creating process, and process ID of the last process to attach or detach on shared memory segments.)"
},
{
"code": null,
"e": 27084,
"s": 26773,
"text": "-t : Write time information. (Time of the last control operation that changed the access permissions for all facilities, time of the last msgsnd() and msgrcv() operations on message queues, time of the last shmat() and shmdt() operations on shared memory, and time of the last semop() operation on semaphores.)"
},
{
"code": null,
"e": 27110,
"s": 27084,
"text": "Examples on IPCS command:"
},
{
"code": null,
"e": 27142,
"s": 27110,
"text": "1: To list all the IPC facility"
},
{
"code": null,
"e": 27225,
"s": 27142,
"text": "# ipcs -a : It provides details about message queue, semaphore and shared memory.\n"
},
{
"code": null,
"e": 27320,
"s": 27225,
"text": "All the IPC facility has unique key and identifier, which is used to identify an IPC facility."
},
{
"code": null,
"e": 27353,
"s": 27320,
"text": "2: To list all the Message Queue"
},
{
"code": null,
"e": 27442,
"s": 27353,
"text": "$ ipcs -q : It lists only message queues for which the current process has read access.\n"
},
{
"code": null,
"e": 27472,
"s": 27442,
"text": "3. To list all the Semaphores"
},
{
"code": null,
"e": 27520,
"s": 27472,
"text": "# ipcs -s : To list the accessible semaphores.\n"
},
{
"code": null,
"e": 27553,
"s": 27520,
"text": "4. To list all the Shared Memory"
},
{
"code": null,
"e": 27596,
"s": 27553,
"text": "# ipcs -m : To lists the shared memories.\n"
},
{
"code": null,
"e": 27653,
"s": 27596,
"text": "5. To get the detailed information about an IPC facility"
},
{
"code": null,
"e": 27743,
"s": 27653,
"text": "# ipcs -m -i 425984 : To detailed information about an ipc facility(here for id-425984).\n"
},
{
"code": null,
"e": 27783,
"s": 27743,
"text": "6. To lists the Limits for IPC facility"
},
{
"code": null,
"e": 27847,
"s": 27783,
"text": "# ipcs -m -l : To get the system limits for each ipc facility.\n"
},
{
"code": null,
"e": 27908,
"s": 27847,
"text": "# ipcs -l : To get the limits for all three IPC facilities.\n"
},
{
"code": null,
"e": 27962,
"s": 27908,
"text": "7. To list Creator and Owner Details for IPC Facility"
},
{
"code": null,
"e": 28044,
"s": 27962,
"text": "# ipcs -m -c : To list creator userid and groupid and owner userid and group id.\n"
},
{
"code": null,
"e": 28106,
"s": 28044,
"text": "8. To get the process ids that accessed IPC facility recently"
},
{
"code": null,
"e": 28222,
"s": 28106,
"text": "# ipcs -m -p : To displays creator id, and process id which accessed the corresponding ipc facility very recently.\n"
},
{
"code": null,
"e": 28255,
"s": 28222,
"text": "9. To get the last Accessed Time"
},
{
"code": null,
"e": 28324,
"s": 28255,
"text": "# ipcs -s -t : To get the last operation time in each ipc facility.\n"
},
{
"code": null,
"e": 28363,
"s": 28324,
"text": "10. To get the status of current usage"
},
{
"code": null,
"e": 28427,
"s": 28363,
"text": "# ipcs -u : To display current usage for all the IPC facility.\n"
},
{
"code": null,
"e": 28461,
"s": 28427,
"text": "Reference: IPCS Linux Manual Page"
},
{
"code": null,
"e": 28762,
"s": 28461,
"text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 28887,
"s": 28762,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28901,
"s": 28887,
"text": "linux-command"
},
{
"code": null,
"e": 28923,
"s": 28901,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 28934,
"s": 28923,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28943,
"s": 28934,
"text": "TechTips"
},
{
"code": null,
"e": 29041,
"s": 28943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29076,
"s": 29041,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 29112,
"s": 29076,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 29150,
"s": 29112,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 29188,
"s": 29150,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29224,
"s": 29188,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 29277,
"s": 29224,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 29303,
"s": 29277,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 29357,
"s": 29303,
"text": "Top Programming Languages for Android App Development"
},
{
"code": null,
"e": 29392,
"s": 29357,
"text": "Setting up the environment in Java"
}
] |
Node.js stringDecoder.end() Method - GeeksforGeeks
|
08 Oct, 2021
The stringDecoder.end() method is used to return all the remaining input stored in the internal buffer as a string. This method ensures that any incomplete UTF-8 and UTF-16 characters are replaced with substitution characters that are appropriate for character encoding.
When the optional buffer argument is provided, the stringDecoder.write() method is called once with the data before returning the remaining buffer input.
Syntax:
stringDecoder.end( [buffer] )
Parameters: This function accepts single parameter as mentioned above and described below:
buffer: It is a Buffer, TypedArray, or DataView that contains the bytes that have to be decoded. It is an optional parameter.
Return Value: It returns the remaining input stored in a buffer as a string.Below programs illustrate the stringDecoder.end() method in Node.js:
Example 1:
Javascript
// Import the string_decoder module// and get the StringDecoder class // using object destructuringconst { StringDecoder } = require("string_decoder"); const decoder = new StringDecoder("utf-8"); // Using the end() methodconst text_one = Buffer.from("GeeksforGeeks", "utf-8");let decoded_text = decoder.end(text_one);console.log("Decoded Text:", decoded_text); // The Euro Symbol is denoted using// the bytes [0xE2, 0x82, 0xAC] console.log("Decoding the Euro Symbol:"); // Decoding the euro symbol// Using the write() method to// write the first two partsconsole.log(decoder.write(Buffer.from([0xE2])));console.log(decoder.write(Buffer.from([0x82]))); // Finishing the symbol using the end() method// with that gives an additional call to write()// using the last part of the bufferconsole.log(decoder.end(Buffer.from([0xAC])));
Output:
Decoded Text: GeeksforGeeks
Decoding the Euro Symbol:
€
Example 2:
Javascript
// Import the string_decoder module// and get the StringDecoder class // using object destructuringconst { StringDecoder } = require("string_decoder");const decoder = new StringDecoder("utf-8");// The Cent Symbol is denoted using// Buffer.from([0xc2, 0xa2]) // Decoding the complete cent symbol from bufferlet cent_symbol = Buffer.from([0xc2, 0xa2]);let cent_symbol_out = decoder.end(cent_symbol);console.log("Complete Cent Symbol:", cent_symbol_out); // Decoding incomplete cent symbol using// Buffer.write() methodcent_symbol = Buffer.from([0xc2]);cent_symbol_out = decoder.write(cent_symbol);console.log("Cent Symbol using write():", cent_symbol_out); // Decoding incomplete cent symbol// using Buffer.end() methodcent_symbol = Buffer.from([0xc2]);cent_symbol_out = decoder.end(cent_symbol);console.log("Cent Symbol using end():", cent_symbol_out);
Output:
Complete Cent Symbol: ¢
Cent Symbol using write():
Cent Symbol using end(): ??
Reference: https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_end_buffer
arorakashish0911
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 38501,
"s": 38473,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 38772,
"s": 38501,
"text": "The stringDecoder.end() method is used to return all the remaining input stored in the internal buffer as a string. This method ensures that any incomplete UTF-8 and UTF-16 characters are replaced with substitution characters that are appropriate for character encoding."
},
{
"code": null,
"e": 38926,
"s": 38772,
"text": "When the optional buffer argument is provided, the stringDecoder.write() method is called once with the data before returning the remaining buffer input."
},
{
"code": null,
"e": 38935,
"s": 38926,
"text": "Syntax: "
},
{
"code": null,
"e": 38965,
"s": 38935,
"text": "stringDecoder.end( [buffer] )"
},
{
"code": null,
"e": 39057,
"s": 38965,
"text": "Parameters: This function accepts single parameter as mentioned above and described below: "
},
{
"code": null,
"e": 39183,
"s": 39057,
"text": "buffer: It is a Buffer, TypedArray, or DataView that contains the bytes that have to be decoded. It is an optional parameter."
},
{
"code": null,
"e": 39328,
"s": 39183,
"text": "Return Value: It returns the remaining input stored in a buffer as a string.Below programs illustrate the stringDecoder.end() method in Node.js:"
},
{
"code": null,
"e": 39340,
"s": 39328,
"text": "Example 1: "
},
{
"code": null,
"e": 39351,
"s": 39340,
"text": "Javascript"
},
{
"code": "// Import the string_decoder module// and get the StringDecoder class // using object destructuringconst { StringDecoder } = require(\"string_decoder\"); const decoder = new StringDecoder(\"utf-8\"); // Using the end() methodconst text_one = Buffer.from(\"GeeksforGeeks\", \"utf-8\");let decoded_text = decoder.end(text_one);console.log(\"Decoded Text:\", decoded_text); // The Euro Symbol is denoted using// the bytes [0xE2, 0x82, 0xAC] console.log(\"Decoding the Euro Symbol:\"); // Decoding the euro symbol// Using the write() method to// write the first two partsconsole.log(decoder.write(Buffer.from([0xE2])));console.log(decoder.write(Buffer.from([0x82]))); // Finishing the symbol using the end() method// with that gives an additional call to write()// using the last part of the bufferconsole.log(decoder.end(Buffer.from([0xAC])));",
"e": 40186,
"s": 39351,
"text": null
},
{
"code": null,
"e": 40195,
"s": 40186,
"text": "Output: "
},
{
"code": null,
"e": 40253,
"s": 40195,
"text": "Decoded Text: GeeksforGeeks\nDecoding the Euro Symbol:\n\n\n€"
},
{
"code": null,
"e": 40265,
"s": 40253,
"text": "Example 2: "
},
{
"code": null,
"e": 40276,
"s": 40265,
"text": "Javascript"
},
{
"code": "// Import the string_decoder module// and get the StringDecoder class // using object destructuringconst { StringDecoder } = require(\"string_decoder\");const decoder = new StringDecoder(\"utf-8\");// The Cent Symbol is denoted using// Buffer.from([0xc2, 0xa2]) // Decoding the complete cent symbol from bufferlet cent_symbol = Buffer.from([0xc2, 0xa2]);let cent_symbol_out = decoder.end(cent_symbol);console.log(\"Complete Cent Symbol:\", cent_symbol_out); // Decoding incomplete cent symbol using// Buffer.write() methodcent_symbol = Buffer.from([0xc2]);cent_symbol_out = decoder.write(cent_symbol);console.log(\"Cent Symbol using write():\", cent_symbol_out); // Decoding incomplete cent symbol// using Buffer.end() methodcent_symbol = Buffer.from([0xc2]);cent_symbol_out = decoder.end(cent_symbol);console.log(\"Cent Symbol using end():\", cent_symbol_out);",
"e": 41173,
"s": 40276,
"text": null
},
{
"code": null,
"e": 41182,
"s": 41173,
"text": "Output: "
},
{
"code": null,
"e": 41261,
"s": 41182,
"text": "Complete Cent Symbol: ¢\nCent Symbol using write():\nCent Symbol using end(): ??"
},
{
"code": null,
"e": 41355,
"s": 41261,
"text": "Reference: https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_end_buffer"
},
{
"code": null,
"e": 41372,
"s": 41355,
"text": "arorakashish0911"
},
{
"code": null,
"e": 41388,
"s": 41372,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 41396,
"s": 41388,
"text": "Node.js"
},
{
"code": null,
"e": 41413,
"s": 41396,
"text": "Web Technologies"
},
{
"code": null,
"e": 41511,
"s": 41413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41559,
"s": 41511,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 41592,
"s": 41559,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 41622,
"s": 41592,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 41642,
"s": 41622,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 41696,
"s": 41642,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 41736,
"s": 41696,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41781,
"s": 41736,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41824,
"s": 41781,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 41874,
"s": 41824,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Get the SUM of records between two given dates in MySQL
|
For this, use BETWEEN keyword. Let us first create a −
mysql> create table DemoTable1444
-> (
-> Value int,
-> PurchaseDate datetime
-> );
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1444 values(40,'2019-01-10');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1444 values(100,'2019-10-03');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1444 values(170,'2019-11-21');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1444 values(70,'2018-12-05');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select −
mysql> select * from DemoTable1444;
This will produce the following output −
+-------+---------------------+
| Value | PurchaseDate |
+-------+---------------------+
| 40 | 2019-01-10 00:00:00 |
| 100 | 2019-10-03 00:00:00 |
| 170 | 2019-11-21 00:00:00 |
| 70 | 2018-12-05 00:00:00 |
+-------+---------------------+
4 rows in set (0.00 sec)
Following is the query to get the sum between two given dates −
mysql> select sum(Value) from DemoTable1444 where PurchaseDate between '2019-10-02' and '2019-12-31';
This will produce the following output −
+------------+
| sum(Value) |
+------------+
| 270 |
+------------+
1 row in set (0.02 sec)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "For this, use BETWEEN keyword. Let us first create a −"
},
{
"code": null,
"e": 1250,
"s": 1117,
"text": "mysql> create table DemoTable1444\n -> (\n -> Value int,\n -> PurchaseDate datetime\n -> );\nQuery OK, 0 rows affected (0.45 sec)"
},
{
"code": null,
"e": 1298,
"s": 1250,
"text": "Insert some records in the table using insert −"
},
{
"code": null,
"e": 1676,
"s": 1298,
"text": "mysql> insert into DemoTable1444 values(40,'2019-01-10');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1444 values(100,'2019-10-03');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1444 values(170,'2019-11-21');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1444 values(70,'2018-12-05');\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 1726,
"s": 1676,
"text": "Display all records from the table using select −"
},
{
"code": null,
"e": 1762,
"s": 1726,
"text": "mysql> select * from DemoTable1444;"
},
{
"code": null,
"e": 1803,
"s": 1762,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2084,
"s": 1803,
"text": "+-------+---------------------+\n| Value | PurchaseDate |\n+-------+---------------------+\n| 40 | 2019-01-10 00:00:00 |\n| 100 | 2019-10-03 00:00:00 |\n| 170 | 2019-11-21 00:00:00 |\n| 70 | 2018-12-05 00:00:00 |\n+-------+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2148,
"s": 2084,
"text": "Following is the query to get the sum between two given dates −"
},
{
"code": null,
"e": 2250,
"s": 2148,
"text": "mysql> select sum(Value) from DemoTable1444 where PurchaseDate between '2019-10-02' and '2019-12-31';"
},
{
"code": null,
"e": 2291,
"s": 2250,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2390,
"s": 2291,
"text": "+------------+\n| sum(Value) |\n+------------+\n| 270 |\n+------------+\n1 row in set (0.02 sec)"
}
] |
Combining two sorted lists in Python
|
Lists are one of the most extensively used python data structures. In this article we will see how to combine the elements of two lists and produce the final output in a sorted manner.
The + operator can join the elements of two lists into one. Then we apply the sorted function which will sort the elements of the final list created with this combination.
Live Demo
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Add and sort
res = sorted(listA + listB)
# Result
print("The combined sorted list is : \n" ,res)
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
The merge function from heapq module can combine the elements of two lists. Then we apply the sorted function to get the final output.
Live Demo
from heapq import merge
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Merge
res = list(merge(listA,listB))
# Result
print("The combined sorted list is : \n" ,sorted(res))
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "Lists are one of the most extensively used python data structures. In this article we will see how to combine the elements of two lists and produce the final output in a sorted manner."
},
{
"code": null,
"e": 1419,
"s": 1247,
"text": "The + operator can join the elements of two lists into one. Then we apply the sorted function which will sort the elements of the final list created with this combination."
},
{
"code": null,
"e": 1430,
"s": 1419,
"text": " Live Demo"
},
{
"code": null,
"e": 1669,
"s": 1430,
"text": "listA = ['Mon', 'Tue', 'Fri']\nlistB = ['Thu','Fri','Sat']\n# Given lists\nprint(\"Given list A is : \",listA)\nprint(\"Given list B is : \",listB)\n# Add and sort\nres = sorted(listA + listB)\n# Result\nprint(\"The combined sorted list is : \\n\" ,res)"
},
{
"code": null,
"e": 1724,
"s": 1669,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1877,
"s": 1724,
"text": "Given list A is : ['Mon', 'Tue', 'Fri']\nGiven list B is : ['Thu', 'Fri', 'Sat']\nThe combined sorted list is :\n['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']"
},
{
"code": null,
"e": 2012,
"s": 1877,
"text": "The merge function from heapq module can combine the elements of two lists. Then we apply the sorted function to get the final output."
},
{
"code": null,
"e": 2023,
"s": 2012,
"text": " Live Demo"
},
{
"code": null,
"e": 2290,
"s": 2023,
"text": "from heapq import merge\nlistA = ['Mon', 'Tue', 'Fri']\nlistB = ['Thu','Fri','Sat']\n# Given lists\nprint(\"Given list A is : \",listA)\nprint(\"Given list B is : \",listB)\n# Merge\nres = list(merge(listA,listB))\n# Result\nprint(\"The combined sorted list is : \\n\" ,sorted(res))"
},
{
"code": null,
"e": 2345,
"s": 2290,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2498,
"s": 2345,
"text": "Given list A is : ['Mon', 'Tue', 'Fri']\nGiven list B is : ['Thu', 'Fri', 'Sat']\nThe combined sorted list is :\n['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.