title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Boosting Your Jupyter Notebook Productivity | by Nazif Berat | Towards Data Science
|
First of all, I want to point out that it is very flexible tool to create readable analyses, because one can keep code, images, comments, formula and plots together:
Jupyter is very extensible, supports other programming languages, easily hosted on almost any server — you just only need to have ssh or http access to a server. And it is completely free.
List of hotkeys is shown in Help > Keyboard Shortcuts (list is extended from time to time, so don’t hesitate to look at it again).
This gives an idea of how you’re expected to interact with notebook. If you’re using notebook constantly, you’ll of course learn most of the list. In particular:
Esc + F Find and replace to search only over the code, not outputs
Esc + O Toggle cell output
You can select several cells in a row and delete / copy / cut / paste them. This is helpful when you need to move parts of a notebook
Simplest way is to share notebook file (.ipynb), but not everyone is using notebooks, so the options are
convert notebooks to html file
share it with gists , which are rendering the notebooks.
store your notebook e.g. in dropbox and put the link to nbviewer. nbviewer will render the notebook
github renders notebooks (with some limitations, but in most cases it is ok), which makes it very useful to keep history of your research (if research is public)
There are many plotting options:
matplotlib (de-facto standard), activated with %matplotlib inline
%matplotlib notebook is interactive regime, but very slow, since rendering is done on server-side.
mpld3 provides alternative renderer (using d3) for matplotlib code. Quite nice, though incomplete
bokeh is a better option for building interactive plots
plot.ly can generate nice plots, but those will cost you money
Magics are turning simple python into magical python. Magics are the key to power of ipython.
In [1]:
# list available python magics%lsmagic
Out[1]:
Available line magics:%alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmodeAvailable cell magics:%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefileAutomagic is ON, % prefix IS NOT needed for line magics.
You can manage environment variables of your notebook without restarting the jupyter server process. Some libraries (like theano) use environment variables to control behavior, %env is the most convenient way.
In [2]:
# %env - without arguments lists environmental variables%env OMP_NUM_THREADS=4env: OMP_NUM_THREADS=4
You can call any shell command. This in particular useful to manage your virtual environment.
In [3]:
!pip install numpy!pip list | grep TheanoRequirement already satisfied (use --upgrade to upgrade): numpy in /Users/axelr/.venvs/rep/lib/python2.7/site-packagesTheano (0.8.2)
sometimes output isn’t needed, so we can either use pass instruction on new line or semicolon at the end
In [4]:
%matplotlib inlinefrom matplotlib import pyplot as pltimport numpy
In [5]:
# if you don't put semicolon at the end, you'll have output of function printedplt.hist(numpy.linspace(0, 1, 1000)**1.5);
In [6]:
from sklearn.cross_validation import train_test_split# show the sources of train_test_split function in the pop-up windowtrain_test_split??
In [7]:
# you can use ? to get details about magics, for instance:%pycat?
will output in the pop-up window:
Show a syntax-highlighted file through a pager.This magic is similar to the cat utility, but it will assume the fileto be Python source and will show it with syntax highlighting.This magic command can either take a local filename, an url,an history range (see %history) or a macro as argument ::%pycat myscript.py%pycat 7-27%pycat myMacro%pycat http://www.example.com/myscript.py
%run can execute python code from .py files — this is a well-documented behavior.
But it also can execute other jupyter notebooks! Sometimes it is quite useful.
NB. %run is not the same as importing python module.
In [8]:
# this will execute all the code cells from different notebooks%run ./2015-09-29-NumpyTipsAndTricks1.ipynb[49 34 49 41 59 45 30 33 34 57][172 177 209 197 171 176 209 208 166 151][30 33 34 34 41 45 49 49 57 59][209 208 177 166 197 176 172 209 151 171][1 0 4 8 6 5 2 9 7 3]['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j']['b' 'a' 'e' 'i' 'g' 'f' 'c' 'j' 'h' 'd']['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'][1 0 6 9 2 5 4 8 3 7][1 0 6 9 2 5 4 8 3 7][ 0.93551212 0.75079687 0.87495146 0.3344709 0.99628591 0.34355057 0.90019059 0.88272132 0.67272068 0.24679158][8 4 5 1 9 2 7 6 3 0][-5 -4 -3 -2 -1 0 1 2 3 4][0 0 0 0 0 0 1 2 3 4]['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['ab' 'ac' 'ad' 'ae' 'af' 'ag' 'ah' 'ai' 'aj' 'ak' 'al' 'am' 'an' 'bc' 'bd' 'be' 'bf' 'bg' 'bh' 'bi' 'bj' 'bk' 'bl' 'bm' 'bn' 'cd' 'ce' 'cf' 'cg' 'ch' 'ci' 'cj' 'ck' 'cl' 'cm' 'cn' 'de' 'df' 'dg' 'dh' 'di' 'dj' 'dk' 'dl' 'dm' 'dn' 'ef' 'eg' 'eh' 'ei' 'ej' 'ek' 'el' 'em' 'en' 'fg' 'fh' 'fi' 'fj' 'fk' 'fl' 'fm' 'fn' 'gh' 'gi' 'gj' 'gk' 'gl' 'gm' 'gn' 'hi' 'hj' 'hk' 'hl' 'hm' 'hn' 'ij' 'ik' 'il' 'im' 'in' 'jk' 'jl' 'jm' 'jn' 'kl' 'km' 'kn' 'lm' 'ln' 'mn'][48 33 6 ..., 0 23 0]['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['bf' 'cl' 'dn' ..., 'dm' 'cn' 'dj']['bf' 'cl' 'dn' ..., 'dm' 'cn' 'dj'][ 2.29711325 1.82679746 2.65173344 ..., 2.15286813 2.308737 2.15286813]1000 loops, best of 3: 1.09 ms per loopThe slowest run took 8.44 times longer than the fastest. This could mean that an intermediate result is being cached.10000 loops, best of 3: 21.5 μs per loop0.4160.416
loading code directly into cell. You can pick local file or file on the web.
After uncommenting the code below and executing, it will replace the content of cell with contents of file.
In [9]:
# %load http://matplotlib.org/mpl_examples/pylab_examples/contour_demo.py
In [10]:
data = 'this is the string I want to pass to different notebook'%store datadel data # deleted variableStored 'data' (str)
In [11]:
# in second notebook I will use:%store -r dataprint datathis is the string I want to pass to different notebook
In [12]:
# pring names of string variables%who strdata
When you need to measure time spent or find the bottleneck in the code, ipython comes to the rescue.
In [13]:
%%timeimport timetime.sleep(2) # sleep for two secondsCPU times: user 1.23 ms, sys: 4.82 ms, total: 6.05 msWall time: 2 s
In [14]:
# measure small code snippets with timeit !import numpy%timeit numpy.random.normal(size=100)The slowest run took 13.85 times longer than the fastest. This could mean that an intermediate result is being cached.100000 loops, best of 3: 6.35 μs per loop
In [15]:
%%writefile pythoncode.pyimport numpydef append_if_not_exists(arr, x): if x not in arr: arr.append(x) def some_useless_slow_function(): arr = list() for i in range(10000): x = numpy.random.randint(0, 10000) append_if_not_exists(arr, x)Overwriting pythoncode.py
In [16]:
# shows highlighted source of the newly-created file%pycat pythoncode.py
In [17]:
from pythoncode import some_useless_slow_function, append_if_not_exists
In [18]:
# shows how much time program spent in each function%prun some_useless_slow_function()
Example of output:
26338 function calls in 0.713 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.684 0.000 0.685 0.000 pythoncode.py:3(append_if_not_exists) 10000 0.014 0.000 0.014 0.000 {method 'randint' of 'mtrand.RandomState' objects} 1 0.011 0.011 0.713 0.713 pythoncode.py:7(some_useless_slow_function) 1 0.003 0.003 0.003 0.003 {range} 6334 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.713 0.713 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
In [19]:
%load_ext memory_profiler
In [20]:
# tracking memory consumption (show in the pop-up)%mprun -f append_if_not_exists some_useless_slow_function()('',)
Example of output:
Line # Mem usage Increment Line Contents================================================ 3 20.6 MiB 0.0 MiB def append_if_not_exists(arr, x): 4 20.6 MiB 0.0 MiB if x not in arr: 5 20.6 MiB 0.0 MiB arr.append(x)
%lprun is line profiling, but it seems to be broken for latest IPython release, so we’ll manage without magic this time:
In [21]:
import line_profilerlp = line_profiler.LineProfiler()lp.add_function(some_useless_slow_function)lp.runctx('some_useless_slow_function()', locals=locals(), globals=globals())lp.print_stats()Timer unit: 1e-06 sTotal time: 1.27826 sFile: pythoncode.pyFunction: some_useless_slow_function at line 7Line # Hits Time Per Hit % Time Line Contents============================================================== 7 def some_useless_slow_function(): 8 1 5 5.0 0.0 arr = list() 9 10001 17838 1.8 1.4 for i in range(10000): 10 10000 38254 3.8 3.0 x = numpy.random.randint(0, 10000) 11 10000 1222162 122.2 95.6 append_if_not_exists(arr, x)
Jupyter has own interface for ipdb. Makes it possible to go inside the function and investigate what happens there.
This is not pycharm and requires much time to adapt, but when debugging on the server this can be the only option (or use pdb from terminal).
In [22]:
#%%debug filename:line_number_for_breakpoint# Here some code that fails. This will activate interactive context for debugging
A bit easier option is %pdb, which activates debugger when exception is raised:
In [23]:
# %pdb# def pick_and_take():# picked = numpy.random.randint(0, 1000)# raise NotImplementedError() # pick_and_take()
markdown cells render latex using MathJax.
P(A∣B)=P(B∣A)P(A)P(B)P(A∣B)=P(B∣A)P(A)P(B)
Markdown is an important part of notebooks, so don’t forget to use its expressiveness!
If you’re missing those much, using other computational kernels:
%%python2
%%python3
%%ruby
%%perl
%%bash
%%R
is possible, but obviously you’ll need to setup the corresponding kernel first.
In [24]:
%%rubyputs 'Hi, this is ruby.'Hi, this is ruby.
In [25]:
%%bashecho 'Hi, this is bash.'Hi, this is bash.
A number of solutions are available for querying/processing large data samples:
ipyparallel (formerly ipython cluster) is a good option for simple map-reduce operations in python. We use it in rep to train many machine learning models in parallel
pyspark
spark-sql magic %%sql
Services like mybinder give an access to machine with jupyter notebook with all the libraries installed, so user can play for half an hour with your code having only browser.
You can setup your own system with jupyterhub, this is very handy when you organize mini-course or workshop and don’t have time to care about students machines.
Sometimes the speed of numpy is not enough and I need to write some fast code. In principle, you can compile function in the dynamic library and write python wrappers...
But it is much better when this boring part is done for you, right?
You can write functions in cython or fortran and use those directly from python code.
First you’ll need to install:
!pip install cython fortran-magic
In [26]:
%load_ext Cython
In [27]:
%%cythondef myltiply_by_2(float x): return 2.0 * x
In [28]:
myltiply_by_2(23.)
Out[28]:
46.0
Personally I prefer to use fortran, which I found very convenient for writing number-crunching functions.
In [29]:
%load_ext fortranmagic/Users/axelr/.venvs/rep/lib/python2.7/site-packages/IPython/utils/path.py:265: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module warn("get_ipython_cache_dir has moved to the IPython.paths module")
In [30]:
%%fortransubroutine compute_fortran(x, y, z) real, intent(in) :: x(:), y(:) real, intent(out) :: z(size(x, 1)) z = sin(x + y)end subroutine compute_fortran
In [31]:
compute_fortran([1, 2, 3], [4, 5, 6])
Out[31]:
array([-0.95892429, 0.65698659, 0.41211849], dtype=float32)
I also should mention that there are different jitter systems which can speed up your python code.
Since recently jupyter supports multiple cursors (in a single cell), just like sublime ot intelliJ!
Gif taken from http://swanintelligence.com/multi-cursor-in-jupyter.html
are installed with
!pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master!pip install jupyter_nbextensions_configurator!jupyter contrib nbextension install --user!jupyter nbextensions_configurator enable --user
this is a family of different extensions, including e.g. jupyter spell-checker and code-formatter, that are missing in jupyter by default.
Extension by Damian Avila makes it possible to show notebooks as demonstrations. Example of such presentation: http://bollwyvl.github.io/live_reveal/#/7
It is very useful when you teach others e.g. to use some library.
Notebooks are displayed as HTML and the cell output can be HTML, so you can return virtually anything: video/audio/images.
In this example I scan the folder with images in my repository and show first five of them:
In [32]:
import osfrom IPython.display import display, Imagenames = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]for name in names[:5]: display(Image('../images/ml_demonstrations/' + name, width=300))
because magics and bash calls return python variables:
In [33]:
names = !ls ../images/ml_demonstrations/*.pngnames[:5]
Out[33]:
['../images/ml_demonstrations/colah_embeddings.png', '../images/ml_demonstrations/convnetjs.png', '../images/ml_demonstrations/decision_tree.png', '../images/ml_demonstrations/decision_tree_in_course.png', '../images/ml_demonstrations/dream_mnist.png']
Long before, when you started some long-taking process and at some point your connection to ipython server dropped, you completely lost the ability to track the computations process (unless you wrote this information to file). So either you interrupt the kernel and potentially lose some progress, or you wait till it completes without any idea of what is happening.
Reconnect to kernel option now makes it possible to connect again to running kernel without interrupting computations and get the newcoming output shown (but some part of output is already lost).
Like this one. Use nbconvert to export them to html.
IPython built-in magics
Nice interactive presentation about jupyter by Ben Zaitlen
Advanced notebooks part 1: magics and part 2: widgets
Profiling in python with jupyter
4 ways to extend notebooks
IPython notebook tricks
Jupyter vs Zeppelin for big data
|
[
{
"code": null,
"e": 338,
"s": 172,
"text": "First of all, I want to point out that it is very flexible tool to create readable analyses, because one can keep code, images, comments, formula and plots together:"
},
{
"code": null,
"e": 527,
"s": 338,
"text": "Jupyter is very extensible, supports other programming languages, easily hosted on almost any server — you just only need to have ssh or http access to a server. And it is completely free."
},
{
"code": null,
"e": 658,
"s": 527,
"text": "List of hotkeys is shown in Help > Keyboard Shortcuts (list is extended from time to time, so don’t hesitate to look at it again)."
},
{
"code": null,
"e": 820,
"s": 658,
"text": "This gives an idea of how you’re expected to interact with notebook. If you’re using notebook constantly, you’ll of course learn most of the list. In particular:"
},
{
"code": null,
"e": 887,
"s": 820,
"text": "Esc + F Find and replace to search only over the code, not outputs"
},
{
"code": null,
"e": 914,
"s": 887,
"text": "Esc + O Toggle cell output"
},
{
"code": null,
"e": 1048,
"s": 914,
"text": "You can select several cells in a row and delete / copy / cut / paste them. This is helpful when you need to move parts of a notebook"
},
{
"code": null,
"e": 1153,
"s": 1048,
"text": "Simplest way is to share notebook file (.ipynb), but not everyone is using notebooks, so the options are"
},
{
"code": null,
"e": 1184,
"s": 1153,
"text": "convert notebooks to html file"
},
{
"code": null,
"e": 1241,
"s": 1184,
"text": "share it with gists , which are rendering the notebooks."
},
{
"code": null,
"e": 1341,
"s": 1241,
"text": "store your notebook e.g. in dropbox and put the link to nbviewer. nbviewer will render the notebook"
},
{
"code": null,
"e": 1503,
"s": 1341,
"text": "github renders notebooks (with some limitations, but in most cases it is ok), which makes it very useful to keep history of your research (if research is public)"
},
{
"code": null,
"e": 1536,
"s": 1503,
"text": "There are many plotting options:"
},
{
"code": null,
"e": 1602,
"s": 1536,
"text": "matplotlib (de-facto standard), activated with %matplotlib inline"
},
{
"code": null,
"e": 1701,
"s": 1602,
"text": "%matplotlib notebook is interactive regime, but very slow, since rendering is done on server-side."
},
{
"code": null,
"e": 1799,
"s": 1701,
"text": "mpld3 provides alternative renderer (using d3) for matplotlib code. Quite nice, though incomplete"
},
{
"code": null,
"e": 1855,
"s": 1799,
"text": "bokeh is a better option for building interactive plots"
},
{
"code": null,
"e": 1918,
"s": 1855,
"text": "plot.ly can generate nice plots, but those will cost you money"
},
{
"code": null,
"e": 2012,
"s": 1918,
"text": "Magics are turning simple python into magical python. Magics are the key to power of ipython."
},
{
"code": null,
"e": 2020,
"s": 2012,
"text": "In [1]:"
},
{
"code": null,
"e": 2059,
"s": 2020,
"text": "# list available python magics%lsmagic"
},
{
"code": null,
"e": 2067,
"s": 2059,
"text": "Out[1]:"
},
{
"code": null,
"e": 3198,
"s": 2067,
"text": "Available line magics:%alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmodeAvailable cell magics:%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefileAutomagic is ON, % prefix IS NOT needed for line magics."
},
{
"code": null,
"e": 3408,
"s": 3198,
"text": "You can manage environment variables of your notebook without restarting the jupyter server process. Some libraries (like theano) use environment variables to control behavior, %env is the most convenient way."
},
{
"code": null,
"e": 3416,
"s": 3408,
"text": "In [2]:"
},
{
"code": null,
"e": 3517,
"s": 3416,
"text": "# %env - without arguments lists environmental variables%env OMP_NUM_THREADS=4env: OMP_NUM_THREADS=4"
},
{
"code": null,
"e": 3611,
"s": 3517,
"text": "You can call any shell command. This in particular useful to manage your virtual environment."
},
{
"code": null,
"e": 3619,
"s": 3611,
"text": "In [3]:"
},
{
"code": null,
"e": 3793,
"s": 3619,
"text": "!pip install numpy!pip list | grep TheanoRequirement already satisfied (use --upgrade to upgrade): numpy in /Users/axelr/.venvs/rep/lib/python2.7/site-packagesTheano (0.8.2)"
},
{
"code": null,
"e": 3898,
"s": 3793,
"text": "sometimes output isn’t needed, so we can either use pass instruction on new line or semicolon at the end"
},
{
"code": null,
"e": 3906,
"s": 3898,
"text": "In [4]:"
},
{
"code": null,
"e": 3973,
"s": 3906,
"text": "%matplotlib inlinefrom matplotlib import pyplot as pltimport numpy"
},
{
"code": null,
"e": 3981,
"s": 3973,
"text": "In [5]:"
},
{
"code": null,
"e": 4103,
"s": 3981,
"text": "# if you don't put semicolon at the end, you'll have output of function printedplt.hist(numpy.linspace(0, 1, 1000)**1.5);"
},
{
"code": null,
"e": 4111,
"s": 4103,
"text": "In [6]:"
},
{
"code": null,
"e": 4251,
"s": 4111,
"text": "from sklearn.cross_validation import train_test_split# show the sources of train_test_split function in the pop-up windowtrain_test_split??"
},
{
"code": null,
"e": 4259,
"s": 4251,
"text": "In [7]:"
},
{
"code": null,
"e": 4325,
"s": 4259,
"text": "# you can use ? to get details about magics, for instance:%pycat?"
},
{
"code": null,
"e": 4359,
"s": 4325,
"text": "will output in the pop-up window:"
},
{
"code": null,
"e": 4739,
"s": 4359,
"text": "Show a syntax-highlighted file through a pager.This magic is similar to the cat utility, but it will assume the fileto be Python source and will show it with syntax highlighting.This magic command can either take a local filename, an url,an history range (see %history) or a macro as argument ::%pycat myscript.py%pycat 7-27%pycat myMacro%pycat http://www.example.com/myscript.py"
},
{
"code": null,
"e": 4821,
"s": 4739,
"text": "%run can execute python code from .py files — this is a well-documented behavior."
},
{
"code": null,
"e": 4900,
"s": 4821,
"text": "But it also can execute other jupyter notebooks! Sometimes it is quite useful."
},
{
"code": null,
"e": 4953,
"s": 4900,
"text": "NB. %run is not the same as importing python module."
},
{
"code": null,
"e": 4961,
"s": 4953,
"text": "In [8]:"
},
{
"code": null,
"e": 6536,
"s": 4961,
"text": "# this will execute all the code cells from different notebooks%run ./2015-09-29-NumpyTipsAndTricks1.ipynb[49 34 49 41 59 45 30 33 34 57][172 177 209 197 171 176 209 208 166 151][30 33 34 34 41 45 49 49 57 59][209 208 177 166 197 176 172 209 151 171][1 0 4 8 6 5 2 9 7 3]['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j']['b' 'a' 'e' 'i' 'g' 'f' 'c' 'j' 'h' 'd']['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'][1 0 6 9 2 5 4 8 3 7][1 0 6 9 2 5 4 8 3 7][ 0.93551212 0.75079687 0.87495146 0.3344709 0.99628591 0.34355057 0.90019059 0.88272132 0.67272068 0.24679158][8 4 5 1 9 2 7 6 3 0][-5 -4 -3 -2 -1 0 1 2 3 4][0 0 0 0 0 0 1 2 3 4]['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['ab' 'ac' 'ad' 'ae' 'af' 'ag' 'ah' 'ai' 'aj' 'ak' 'al' 'am' 'an' 'bc' 'bd' 'be' 'bf' 'bg' 'bh' 'bi' 'bj' 'bk' 'bl' 'bm' 'bn' 'cd' 'ce' 'cf' 'cg' 'ch' 'ci' 'cj' 'ck' 'cl' 'cm' 'cn' 'de' 'df' 'dg' 'dh' 'di' 'dj' 'dk' 'dl' 'dm' 'dn' 'ef' 'eg' 'eh' 'ei' 'ej' 'ek' 'el' 'em' 'en' 'fg' 'fh' 'fi' 'fj' 'fk' 'fl' 'fm' 'fn' 'gh' 'gi' 'gj' 'gk' 'gl' 'gm' 'gn' 'hi' 'hj' 'hk' 'hl' 'hm' 'hn' 'ij' 'ik' 'il' 'im' 'in' 'jk' 'jl' 'jm' 'jn' 'kl' 'km' 'kn' 'lm' 'ln' 'mn'][48 33 6 ..., 0 23 0]['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['eh' 'cl' 'ah' ..., 'ab' 'bm' 'ab']['bf' 'cl' 'dn' ..., 'dm' 'cn' 'dj']['bf' 'cl' 'dn' ..., 'dm' 'cn' 'dj'][ 2.29711325 1.82679746 2.65173344 ..., 2.15286813 2.308737 2.15286813]1000 loops, best of 3: 1.09 ms per loopThe slowest run took 8.44 times longer than the fastest. This could mean that an intermediate result is being cached.10000 loops, best of 3: 21.5 μs per loop0.4160.416"
},
{
"code": null,
"e": 6613,
"s": 6536,
"text": "loading code directly into cell. You can pick local file or file on the web."
},
{
"code": null,
"e": 6721,
"s": 6613,
"text": "After uncommenting the code below and executing, it will replace the content of cell with contents of file."
},
{
"code": null,
"e": 6729,
"s": 6721,
"text": "In [9]:"
},
{
"code": null,
"e": 6803,
"s": 6729,
"text": "# %load http://matplotlib.org/mpl_examples/pylab_examples/contour_demo.py"
},
{
"code": null,
"e": 6812,
"s": 6803,
"text": "In [10]:"
},
{
"code": null,
"e": 6934,
"s": 6812,
"text": "data = 'this is the string I want to pass to different notebook'%store datadel data # deleted variableStored 'data' (str)"
},
{
"code": null,
"e": 6943,
"s": 6934,
"text": "In [11]:"
},
{
"code": null,
"e": 7055,
"s": 6943,
"text": "# in second notebook I will use:%store -r dataprint datathis is the string I want to pass to different notebook"
},
{
"code": null,
"e": 7064,
"s": 7055,
"text": "In [12]:"
},
{
"code": null,
"e": 7110,
"s": 7064,
"text": "# pring names of string variables%who strdata"
},
{
"code": null,
"e": 7211,
"s": 7110,
"text": "When you need to measure time spent or find the bottleneck in the code, ipython comes to the rescue."
},
{
"code": null,
"e": 7220,
"s": 7211,
"text": "In [13]:"
},
{
"code": null,
"e": 7342,
"s": 7220,
"text": "%%timeimport timetime.sleep(2) # sleep for two secondsCPU times: user 1.23 ms, sys: 4.82 ms, total: 6.05 msWall time: 2 s"
},
{
"code": null,
"e": 7351,
"s": 7342,
"text": "In [14]:"
},
{
"code": null,
"e": 7603,
"s": 7351,
"text": "# measure small code snippets with timeit !import numpy%timeit numpy.random.normal(size=100)The slowest run took 13.85 times longer than the fastest. This could mean that an intermediate result is being cached.100000 loops, best of 3: 6.35 μs per loop"
},
{
"code": null,
"e": 7612,
"s": 7603,
"text": "In [15]:"
},
{
"code": null,
"e": 7910,
"s": 7612,
"text": "%%writefile pythoncode.pyimport numpydef append_if_not_exists(arr, x): if x not in arr: arr.append(x) def some_useless_slow_function(): arr = list() for i in range(10000): x = numpy.random.randint(0, 10000) append_if_not_exists(arr, x)Overwriting pythoncode.py"
},
{
"code": null,
"e": 7919,
"s": 7910,
"text": "In [16]:"
},
{
"code": null,
"e": 7992,
"s": 7919,
"text": "# shows highlighted source of the newly-created file%pycat pythoncode.py"
},
{
"code": null,
"e": 8001,
"s": 7992,
"text": "In [17]:"
},
{
"code": null,
"e": 8073,
"s": 8001,
"text": "from pythoncode import some_useless_slow_function, append_if_not_exists"
},
{
"code": null,
"e": 8082,
"s": 8073,
"text": "In [18]:"
},
{
"code": null,
"e": 8169,
"s": 8082,
"text": "# shows how much time program spent in each function%prun some_useless_slow_function()"
},
{
"code": null,
"e": 8188,
"s": 8169,
"text": "Example of output:"
},
{
"code": null,
"e": 8887,
"s": 8188,
"text": "26338 function calls in 0.713 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.684 0.000 0.685 0.000 pythoncode.py:3(append_if_not_exists) 10000 0.014 0.000 0.014 0.000 {method 'randint' of 'mtrand.RandomState' objects} 1 0.011 0.011 0.713 0.713 pythoncode.py:7(some_useless_slow_function) 1 0.003 0.003 0.003 0.003 {range} 6334 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.713 0.713 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}"
},
{
"code": null,
"e": 8896,
"s": 8887,
"text": "In [19]:"
},
{
"code": null,
"e": 8922,
"s": 8896,
"text": "%load_ext memory_profiler"
},
{
"code": null,
"e": 8931,
"s": 8922,
"text": "In [20]:"
},
{
"code": null,
"e": 9046,
"s": 8931,
"text": "# tracking memory consumption (show in the pop-up)%mprun -f append_if_not_exists some_useless_slow_function()('',)"
},
{
"code": null,
"e": 9065,
"s": 9046,
"text": "Example of output:"
},
{
"code": null,
"e": 9341,
"s": 9065,
"text": "Line # Mem usage Increment Line Contents================================================ 3 20.6 MiB 0.0 MiB def append_if_not_exists(arr, x): 4 20.6 MiB 0.0 MiB if x not in arr: 5 20.6 MiB 0.0 MiB arr.append(x)"
},
{
"code": null,
"e": 9462,
"s": 9341,
"text": "%lprun is line profiling, but it seems to be broken for latest IPython release, so we’ll manage without magic this time:"
},
{
"code": null,
"e": 9471,
"s": 9462,
"text": "In [21]:"
},
{
"code": null,
"e": 10288,
"s": 9471,
"text": "import line_profilerlp = line_profiler.LineProfiler()lp.add_function(some_useless_slow_function)lp.runctx('some_useless_slow_function()', locals=locals(), globals=globals())lp.print_stats()Timer unit: 1e-06 sTotal time: 1.27826 sFile: pythoncode.pyFunction: some_useless_slow_function at line 7Line # Hits Time Per Hit % Time Line Contents============================================================== 7 def some_useless_slow_function(): 8 1 5 5.0 0.0 arr = list() 9 10001 17838 1.8 1.4 for i in range(10000): 10 10000 38254 3.8 3.0 x = numpy.random.randint(0, 10000) 11 10000 1222162 122.2 95.6 append_if_not_exists(arr, x)"
},
{
"code": null,
"e": 10404,
"s": 10288,
"text": "Jupyter has own interface for ipdb. Makes it possible to go inside the function and investigate what happens there."
},
{
"code": null,
"e": 10546,
"s": 10404,
"text": "This is not pycharm and requires much time to adapt, but when debugging on the server this can be the only option (or use pdb from terminal)."
},
{
"code": null,
"e": 10555,
"s": 10546,
"text": "In [22]:"
},
{
"code": null,
"e": 10681,
"s": 10555,
"text": "#%%debug filename:line_number_for_breakpoint# Here some code that fails. This will activate interactive context for debugging"
},
{
"code": null,
"e": 10761,
"s": 10681,
"text": "A bit easier option is %pdb, which activates debugger when exception is raised:"
},
{
"code": null,
"e": 10770,
"s": 10761,
"text": "In [23]:"
},
{
"code": null,
"e": 10897,
"s": 10770,
"text": "# %pdb# def pick_and_take():# picked = numpy.random.randint(0, 1000)# raise NotImplementedError() # pick_and_take()"
},
{
"code": null,
"e": 10940,
"s": 10897,
"text": "markdown cells render latex using MathJax."
},
{
"code": null,
"e": 10983,
"s": 10940,
"text": "P(A∣B)=P(B∣A)P(A)P(B)P(A∣B)=P(B∣A)P(A)P(B)"
},
{
"code": null,
"e": 11070,
"s": 10983,
"text": "Markdown is an important part of notebooks, so don’t forget to use its expressiveness!"
},
{
"code": null,
"e": 11135,
"s": 11070,
"text": "If you’re missing those much, using other computational kernels:"
},
{
"code": null,
"e": 11145,
"s": 11135,
"text": "%%python2"
},
{
"code": null,
"e": 11155,
"s": 11145,
"text": "%%python3"
},
{
"code": null,
"e": 11162,
"s": 11155,
"text": "%%ruby"
},
{
"code": null,
"e": 11169,
"s": 11162,
"text": "%%perl"
},
{
"code": null,
"e": 11176,
"s": 11169,
"text": "%%bash"
},
{
"code": null,
"e": 11180,
"s": 11176,
"text": "%%R"
},
{
"code": null,
"e": 11260,
"s": 11180,
"text": "is possible, but obviously you’ll need to setup the corresponding kernel first."
},
{
"code": null,
"e": 11269,
"s": 11260,
"text": "In [24]:"
},
{
"code": null,
"e": 11317,
"s": 11269,
"text": "%%rubyputs 'Hi, this is ruby.'Hi, this is ruby."
},
{
"code": null,
"e": 11326,
"s": 11317,
"text": "In [25]:"
},
{
"code": null,
"e": 11374,
"s": 11326,
"text": "%%bashecho 'Hi, this is bash.'Hi, this is bash."
},
{
"code": null,
"e": 11454,
"s": 11374,
"text": "A number of solutions are available for querying/processing large data samples:"
},
{
"code": null,
"e": 11621,
"s": 11454,
"text": "ipyparallel (formerly ipython cluster) is a good option for simple map-reduce operations in python. We use it in rep to train many machine learning models in parallel"
},
{
"code": null,
"e": 11629,
"s": 11621,
"text": "pyspark"
},
{
"code": null,
"e": 11651,
"s": 11629,
"text": "spark-sql magic %%sql"
},
{
"code": null,
"e": 11826,
"s": 11651,
"text": "Services like mybinder give an access to machine with jupyter notebook with all the libraries installed, so user can play for half an hour with your code having only browser."
},
{
"code": null,
"e": 11987,
"s": 11826,
"text": "You can setup your own system with jupyterhub, this is very handy when you organize mini-course or workshop and don’t have time to care about students machines."
},
{
"code": null,
"e": 12157,
"s": 11987,
"text": "Sometimes the speed of numpy is not enough and I need to write some fast code. In principle, you can compile function in the dynamic library and write python wrappers..."
},
{
"code": null,
"e": 12225,
"s": 12157,
"text": "But it is much better when this boring part is done for you, right?"
},
{
"code": null,
"e": 12311,
"s": 12225,
"text": "You can write functions in cython or fortran and use those directly from python code."
},
{
"code": null,
"e": 12341,
"s": 12311,
"text": "First you’ll need to install:"
},
{
"code": null,
"e": 12375,
"s": 12341,
"text": "!pip install cython fortran-magic"
},
{
"code": null,
"e": 12384,
"s": 12375,
"text": "In [26]:"
},
{
"code": null,
"e": 12401,
"s": 12384,
"text": "%load_ext Cython"
},
{
"code": null,
"e": 12410,
"s": 12401,
"text": "In [27]:"
},
{
"code": null,
"e": 12464,
"s": 12410,
"text": "%%cythondef myltiply_by_2(float x): return 2.0 * x"
},
{
"code": null,
"e": 12473,
"s": 12464,
"text": "In [28]:"
},
{
"code": null,
"e": 12492,
"s": 12473,
"text": "myltiply_by_2(23.)"
},
{
"code": null,
"e": 12501,
"s": 12492,
"text": "Out[28]:"
},
{
"code": null,
"e": 12506,
"s": 12501,
"text": "46.0"
},
{
"code": null,
"e": 12612,
"s": 12506,
"text": "Personally I prefer to use fortran, which I found very convenient for writing number-crunching functions."
},
{
"code": null,
"e": 12621,
"s": 12612,
"text": "In [29]:"
},
{
"code": null,
"e": 12864,
"s": 12621,
"text": "%load_ext fortranmagic/Users/axelr/.venvs/rep/lib/python2.7/site-packages/IPython/utils/path.py:265: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module warn(\"get_ipython_cache_dir has moved to the IPython.paths module\")"
},
{
"code": null,
"e": 12873,
"s": 12864,
"text": "In [30]:"
},
{
"code": null,
"e": 13038,
"s": 12873,
"text": "%%fortransubroutine compute_fortran(x, y, z) real, intent(in) :: x(:), y(:) real, intent(out) :: z(size(x, 1)) z = sin(x + y)end subroutine compute_fortran"
},
{
"code": null,
"e": 13047,
"s": 13038,
"text": "In [31]:"
},
{
"code": null,
"e": 13085,
"s": 13047,
"text": "compute_fortran([1, 2, 3], [4, 5, 6])"
},
{
"code": null,
"e": 13094,
"s": 13085,
"text": "Out[31]:"
},
{
"code": null,
"e": 13156,
"s": 13094,
"text": "array([-0.95892429, 0.65698659, 0.41211849], dtype=float32)"
},
{
"code": null,
"e": 13255,
"s": 13156,
"text": "I also should mention that there are different jitter systems which can speed up your python code."
},
{
"code": null,
"e": 13355,
"s": 13255,
"text": "Since recently jupyter supports multiple cursors (in a single cell), just like sublime ot intelliJ!"
},
{
"code": null,
"e": 13427,
"s": 13355,
"text": "Gif taken from http://swanintelligence.com/multi-cursor-in-jupyter.html"
},
{
"code": null,
"e": 13446,
"s": 13427,
"text": "are installed with"
},
{
"code": null,
"e": 13675,
"s": 13446,
"text": "!pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master!pip install jupyter_nbextensions_configurator!jupyter contrib nbextension install --user!jupyter nbextensions_configurator enable --user"
},
{
"code": null,
"e": 13814,
"s": 13675,
"text": "this is a family of different extensions, including e.g. jupyter spell-checker and code-formatter, that are missing in jupyter by default."
},
{
"code": null,
"e": 13967,
"s": 13814,
"text": "Extension by Damian Avila makes it possible to show notebooks as demonstrations. Example of such presentation: http://bollwyvl.github.io/live_reveal/#/7"
},
{
"code": null,
"e": 14033,
"s": 13967,
"text": "It is very useful when you teach others e.g. to use some library."
},
{
"code": null,
"e": 14156,
"s": 14033,
"text": "Notebooks are displayed as HTML and the cell output can be HTML, so you can return virtually anything: video/audio/images."
},
{
"code": null,
"e": 14248,
"s": 14156,
"text": "In this example I scan the folder with images in my repository and show first five of them:"
},
{
"code": null,
"e": 14257,
"s": 14248,
"text": "In [32]:"
},
{
"code": null,
"e": 14484,
"s": 14257,
"text": "import osfrom IPython.display import display, Imagenames = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]for name in names[:5]: display(Image('../images/ml_demonstrations/' + name, width=300))"
},
{
"code": null,
"e": 14539,
"s": 14484,
"text": "because magics and bash calls return python variables:"
},
{
"code": null,
"e": 14548,
"s": 14539,
"text": "In [33]:"
},
{
"code": null,
"e": 14603,
"s": 14548,
"text": "names = !ls ../images/ml_demonstrations/*.pngnames[:5]"
},
{
"code": null,
"e": 14612,
"s": 14603,
"text": "Out[33]:"
},
{
"code": null,
"e": 14865,
"s": 14612,
"text": "['../images/ml_demonstrations/colah_embeddings.png', '../images/ml_demonstrations/convnetjs.png', '../images/ml_demonstrations/decision_tree.png', '../images/ml_demonstrations/decision_tree_in_course.png', '../images/ml_demonstrations/dream_mnist.png']"
},
{
"code": null,
"e": 15232,
"s": 14865,
"text": "Long before, when you started some long-taking process and at some point your connection to ipython server dropped, you completely lost the ability to track the computations process (unless you wrote this information to file). So either you interrupt the kernel and potentially lose some progress, or you wait till it completes without any idea of what is happening."
},
{
"code": null,
"e": 15428,
"s": 15232,
"text": "Reconnect to kernel option now makes it possible to connect again to running kernel without interrupting computations and get the newcoming output shown (but some part of output is already lost)."
},
{
"code": null,
"e": 15481,
"s": 15428,
"text": "Like this one. Use nbconvert to export them to html."
},
{
"code": null,
"e": 15505,
"s": 15481,
"text": "IPython built-in magics"
},
{
"code": null,
"e": 15564,
"s": 15505,
"text": "Nice interactive presentation about jupyter by Ben Zaitlen"
},
{
"code": null,
"e": 15618,
"s": 15564,
"text": "Advanced notebooks part 1: magics and part 2: widgets"
},
{
"code": null,
"e": 15651,
"s": 15618,
"text": "Profiling in python with jupyter"
},
{
"code": null,
"e": 15678,
"s": 15651,
"text": "4 ways to extend notebooks"
},
{
"code": null,
"e": 15702,
"s": 15678,
"text": "IPython notebook tricks"
}
] |
Count and Say in Python
|
Here we will see the Count and Say sequence. This is a sequence whose few terms are like below −
1
11
21
1211
111221
The string will be read like
1 (One)
11 (One 1) So read the previous 1, and say “One 1”
21 (Two 1) So read the previous 11, and say “Two 1”
1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1”
111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1”
Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term.
To solve this, we will follow this approach −
set s := “1”
if n = 1, then return s
for i := 2 to n + 1j := 0, temp := “”, curr = “” and count := 0while j < length of s, doif curr is “”, then curr := s[j], count := 1 and increase j by 1else if curr is s[j], then increase count and j by 1otherwise temp := temp + count as string + curr, curr = “”, count := 0temp := temp + count as string + curr
j := 0, temp := “”, curr = “” and count := 0
while j < length of s, doif curr is “”, then curr := s[j], count := 1 and increase j by 1else if curr is s[j], then increase count and j by 1otherwise temp := temp + count as string + curr, curr = “”, count := 0
if curr is “”, then curr := s[j], count := 1 and increase j by 1
else if curr is s[j], then increase count and j by 1
otherwise temp := temp + count as string + curr, curr = “”, count := 0
temp := temp + count as string + curr
return s
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = "1"
if n == 1:
return s
for i in range(2,n+1):
j = 0
temp = ""
curr = ""
count = 0
while j<len(s):
#print(curr,count)
if curr =="":
#print(curr)
curr=s[j]
count=1
j+=1
elif curr == s[j]:
#print(curr)
count+=1
j+=1
else:
#print(count,curr)
temp+= str(count) + curr
curr=""
count = 0
#print(temp)
temp+=str(count) + curr
s=temp
return s
ob1 = Solution()
print(ob1.countAndSay(6))
print(ob1.countAndSay(6))
312211
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Here we will see the Count and Say sequence. This is a sequence whose few terms are like below −"
},
{
"code": null,
"e": 1161,
"s": 1159,
"text": "1"
},
{
"code": null,
"e": 1164,
"s": 1161,
"text": "11"
},
{
"code": null,
"e": 1167,
"s": 1164,
"text": "21"
},
{
"code": null,
"e": 1172,
"s": 1167,
"text": "1211"
},
{
"code": null,
"e": 1179,
"s": 1172,
"text": "111221"
},
{
"code": null,
"e": 1208,
"s": 1179,
"text": "The string will be read like"
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "1 (One)"
},
{
"code": null,
"e": 1267,
"s": 1216,
"text": "11 (One 1) So read the previous 1, and say “One 1”"
},
{
"code": null,
"e": 1319,
"s": 1267,
"text": "21 (Two 1) So read the previous 11, and say “Two 1”"
},
{
"code": null,
"e": 1385,
"s": 1319,
"text": "1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1”"
},
{
"code": null,
"e": 1467,
"s": 1385,
"text": "111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1”"
},
{
"code": null,
"e": 1545,
"s": 1467,
"text": "Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term."
},
{
"code": null,
"e": 1591,
"s": 1545,
"text": "To solve this, we will follow this approach −"
},
{
"code": null,
"e": 1604,
"s": 1591,
"text": "set s := “1”"
},
{
"code": null,
"e": 1628,
"s": 1604,
"text": "if n = 1, then return s"
},
{
"code": null,
"e": 1940,
"s": 1628,
"text": "for i := 2 to n + 1j := 0, temp := “”, curr = “” and count := 0while j < length of s, doif curr is “”, then curr := s[j], count := 1 and increase j by 1else if curr is s[j], then increase count and j by 1otherwise temp := temp + count as string + curr, curr = “”, count := 0temp := temp + count as string + curr"
},
{
"code": null,
"e": 1985,
"s": 1940,
"text": "j := 0, temp := “”, curr = “” and count := 0"
},
{
"code": null,
"e": 2197,
"s": 1985,
"text": "while j < length of s, doif curr is “”, then curr := s[j], count := 1 and increase j by 1else if curr is s[j], then increase count and j by 1otherwise temp := temp + count as string + curr, curr = “”, count := 0"
},
{
"code": null,
"e": 2262,
"s": 2197,
"text": "if curr is “”, then curr := s[j], count := 1 and increase j by 1"
},
{
"code": null,
"e": 2315,
"s": 2262,
"text": "else if curr is s[j], then increase count and j by 1"
},
{
"code": null,
"e": 2386,
"s": 2315,
"text": "otherwise temp := temp + count as string + curr, curr = “”, count := 0"
},
{
"code": null,
"e": 2424,
"s": 2386,
"text": "temp := temp + count as string + curr"
},
{
"code": null,
"e": 2433,
"s": 2424,
"text": "return s"
},
{
"code": null,
"e": 2503,
"s": 2433,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2514,
"s": 2503,
"text": " Live Demo"
},
{
"code": null,
"e": 3330,
"s": 2514,
"text": "class Solution(object):\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n s = \"1\"\n if n == 1:\n return s\n for i in range(2,n+1):\n j = 0\n temp = \"\"\n curr = \"\"\n count = 0\n while j<len(s):\n #print(curr,count)\n if curr ==\"\":\n #print(curr)\n curr=s[j]\n count=1\n j+=1\n elif curr == s[j]:\n #print(curr)\n count+=1\n j+=1\n else:\n #print(count,curr)\n temp+= str(count) + curr\n curr=\"\"\n count = 0\n #print(temp)\n temp+=str(count) + curr\n s=temp\n return s\nob1 = Solution()\nprint(ob1.countAndSay(6))"
},
{
"code": null,
"e": 3356,
"s": 3330,
"text": "print(ob1.countAndSay(6))"
},
{
"code": null,
"e": 3363,
"s": 3356,
"text": "312211"
}
] |
How to Build an EDA App in Python | by Chanin Nantasenamat | Towards Data Science
|
Exploratory data analysis (EDA) is an essential and preliminary first steps for exploring and summarizing the main characteristics of datasets. EDA provides the means to help us better understand variables and their relationships. This is achieved by non-graphical (descriptive statistics) and graphical (data visualization) techniques.
In this article, we will be creating an EDA web app that you can use to speed up your EDA analysis or allow your colleagues to perform EDA without having to code in Python. A simple upload of the input CSV file is all it takes to perform EDA analysis.
You can also refer to my YouTube video How to build an Exploratory Data Analysis app using Pandas Profiling on my YouTube channel (Data Professor) as a supplement to this article.
A simple and intuitive EDA tool is the pandas-profiling library in Python. It allows the generation of a profile report for a df dataframe via the df.profile_report() function.
The generated profile is an interactive HTML report that displays the following statistics for each variable (please see the documentation for more details):
Type inference: Identifies the data types of columns in a dataframe.
Essentials: Type, unique values and missing values.
Quantile statistics: Minimum, maximum, Q1, median, Q3, range and interquartile range.
Descriptive statistics: Mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis and skewness.
Most frequent values
Histograms: Distribution of value ranges.
Correlations: Highlighting highly correlated variables, Spearman, Pearson and Kendall matrices.
Missing values: Matrix, count, heatmap and dendrogram of missing values.
Duplicate rows: Lists the most occurring duplicate rows.
Text analysis: Learn about categories (Uppercase, Space), scripts (Latin, Cyrillic) and blocks (ASCII) of text data.
The EDA app that we are going to be building today will allows us to upload our own CSV dataset to the app, which will then automatically generate a profile report (an interactive HTML report that facilitates EDA analysis).
You can try it out for yourself here: EDA App demo
The code spans a little over 50 lines of code, 52 to be exact.
Let’s take a look at the tech behind the app. It is based on 5 Python libraries consisting of the following:
numpy — used for generating a synthetic dataset consisting of 5 columns (variables) that is used an example dataset (notice the Press to use Example Dataset button in the main panel under the web app’s page title).
pandas — used for housing the data in the form of a DataFrame.
streamlit — the web framework that makes it possible to build a simple web app.
pandas_profiling— the library that makes it possible to generate the interactive HTML report for performing EDA.
streamlit_pandas_profiling — the library that allows the pandas_profiling library to be used in a Streamlit web app.
Import prerequisite libraries consisting of numpy, pandas, streamlit, pandas_profiling and streamlit_pandas_profiling
Line 7 — commented text to denote that the subsequent code block pertains to the web app’s title.
Lines 8–13 — the st.markdown() function to print the web app’s title. The input arguments are in Markdown syntax .
Line 15 — Commented text to describe that Lines 16–20 is responsible for the CSV upload functionality.
Line 16 — with is used to structure the subsequent lines of code to belong to the code block. st.sidebar.header() specifies the use of the header() function to display the heading text 1. Upload your CSV data in the left panel.
Line 17 — The st.sidebar.file_uploader() function allows the creation of the upload box. It should be noted that st.sidebar specifies the location of the upload box to be in the sidebar (the collapsible left panel). The input argument type=["csv"] found inside the file_uploader() function specifies that the upload box would only accept the csv file type.
Line 18 — The st.sidebar.markdown() function specifies the use of the markdown() function to display a link to the example CSV file to be in the left panel.
Line 22 — Commented text to describe that the subsequent code blocks are responsible for creating the Pandas Profiling report. It should be noted here that this section consists of an if-else statement whereby the else code block (Lines 35–52) will be run at default every time the web app loads. Upon uploading an input CSV file, the if code block (Lines 23–34) will then be activated and run.
Lines 23–34 — This code block represents the if statement. As mentioned above in the previous bullet point, this code block will run upon uploading of the input CSV file. — Line 23 — An if condition is set to detect that a file is uploaded as indicated by the uploaded_file is not None. — Line 24 — The @st.cache decorator allows the app to skip a costly and repetitive of a function defined in the subsequent lines of code. — Lines 25–27 — A custom function called load_csv that reads in the input CSV file from the upload box via the uploaded_file variable. — Line 28 — Contents of the CSV file as read from the load_csv custom function is assigned to the df variable. — Line 29 — The ProfileReport() function is assigned to the pr variable. — Lines 30–31 — A header for **Input DataFrame** is printed as a heading text via the st.header() function (Line 30). Contents of the DataFrame stored in the df variable is printed (Line 31). — Line 32 — "- — -” prints a horizontal bar. — Line 33–34 — A header for **Pandas Profiling Report** is printed as a heading text via the st.header() function (Line 33). Contents of the pr variable, which stores the output from the ProfileReport() function is printed. Particularly, this is the interactive HTML profile report that allows EDA functionality.
Lines 35–52 — This code block represents the else statement. — Line 35 — An else condition is set as the default state that is run every time the web app loads. — Line 36 — A text saying Awaiting for CSV file to be uploaded. is printed in an info box via the st.info() function. — Lines 37–52 — An if condition is used to specify the consequences (statements underneath it will be run) of clicking the Press to use Example Dataset button, which is to use the example dataset to generate the profile report. — Line 38 — Commented text to indicate that the following lines of code pertains to the example data. — Line 39 — As described earlier for Line 24, the @st.cache decorator allows the app to skip a potentially costly run of the subsequent lines of code (i.e. otherwise the app will re-generate the synthetic dataset everytime the app is reloaded).— Lines 40–45 — A custom function is defined to create a synthetic dataset consisting of 5 columns using the NumPy library. — Line 46 — The synthetic dataset as defined by the custom function from Lines 40–45 is assigned to the df variable.
It’s now time to run the app.
Let’s assume that you are starting from scratch, thus you will have to create a new conda environment (which is a good idea in order to ensure reproducibility of your code).
Firstly, create a new conda environment called eda as follows in a terminal command line:
conda create -n eda python=3.7.9
Secondly, we will login to the eda environment
conda activate eda
Firstly, download the requirements.txt file
wget https://raw.githubusercontent.com/dataprofessor/eda-app/main/requirements.txt
Secondly, install the libraries as shown below
pip install -r requirements.txt
You can either download the web app files that are hosted on the GitHub repo of the Data Professor or you also use the 52 lines of code found above.
wget https://github.com/dataprofessor/eda-app/archive/main.zip
Next, unzip the file contents
unzip main.zip
Now enter the main directory via the cd command
cd main
Now that you’re inside the main directory you should be able to see the app.py file.
The app can be launched by typing the following commands into a terminal prompt (i.e. ensure that the app.py file is in the current working directory):
streamlit run app.py
Afterwards, you will see the following message in the terminal prompt.
> streamlit run app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501
Finally, a browser should pop up and the app appears.
You have now created an EDA app that will allow you to easily perform EDA analysis on-the-go, just simply upload an input CSV file to get started in performing EDA analysis.
If you would like to make your web app publicly available to the world, you can deploy it to the internet. I’ve created YouTube videos showing how you can do that on Heroku and Streamlit Sharing.
How to Deploy Data Science Web App to Heroku
How to Deploy Data Science Web App to Streamlit Sharing
An example of the deployed EDA App on the internet via the Streamlit Sharing platform can be accessible here: EDA App demo
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page).
www.youtube.com
✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
|
[
{
"code": null,
"e": 509,
"s": 172,
"text": "Exploratory data analysis (EDA) is an essential and preliminary first steps for exploring and summarizing the main characteristics of datasets. EDA provides the means to help us better understand variables and their relationships. This is achieved by non-graphical (descriptive statistics) and graphical (data visualization) techniques."
},
{
"code": null,
"e": 761,
"s": 509,
"text": "In this article, we will be creating an EDA web app that you can use to speed up your EDA analysis or allow your colleagues to perform EDA without having to code in Python. A simple upload of the input CSV file is all it takes to perform EDA analysis."
},
{
"code": null,
"e": 941,
"s": 761,
"text": "You can also refer to my YouTube video How to build an Exploratory Data Analysis app using Pandas Profiling on my YouTube channel (Data Professor) as a supplement to this article."
},
{
"code": null,
"e": 1118,
"s": 941,
"text": "A simple and intuitive EDA tool is the pandas-profiling library in Python. It allows the generation of a profile report for a df dataframe via the df.profile_report() function."
},
{
"code": null,
"e": 1276,
"s": 1118,
"text": "The generated profile is an interactive HTML report that displays the following statistics for each variable (please see the documentation for more details):"
},
{
"code": null,
"e": 1345,
"s": 1276,
"text": "Type inference: Identifies the data types of columns in a dataframe."
},
{
"code": null,
"e": 1397,
"s": 1345,
"text": "Essentials: Type, unique values and missing values."
},
{
"code": null,
"e": 1483,
"s": 1397,
"text": "Quantile statistics: Minimum, maximum, Q1, median, Q3, range and interquartile range."
},
{
"code": null,
"e": 1620,
"s": 1483,
"text": "Descriptive statistics: Mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis and skewness."
},
{
"code": null,
"e": 1641,
"s": 1620,
"text": "Most frequent values"
},
{
"code": null,
"e": 1683,
"s": 1641,
"text": "Histograms: Distribution of value ranges."
},
{
"code": null,
"e": 1779,
"s": 1683,
"text": "Correlations: Highlighting highly correlated variables, Spearman, Pearson and Kendall matrices."
},
{
"code": null,
"e": 1852,
"s": 1779,
"text": "Missing values: Matrix, count, heatmap and dendrogram of missing values."
},
{
"code": null,
"e": 1909,
"s": 1852,
"text": "Duplicate rows: Lists the most occurring duplicate rows."
},
{
"code": null,
"e": 2026,
"s": 1909,
"text": "Text analysis: Learn about categories (Uppercase, Space), scripts (Latin, Cyrillic) and blocks (ASCII) of text data."
},
{
"code": null,
"e": 2250,
"s": 2026,
"text": "The EDA app that we are going to be building today will allows us to upload our own CSV dataset to the app, which will then automatically generate a profile report (an interactive HTML report that facilitates EDA analysis)."
},
{
"code": null,
"e": 2301,
"s": 2250,
"text": "You can try it out for yourself here: EDA App demo"
},
{
"code": null,
"e": 2364,
"s": 2301,
"text": "The code spans a little over 50 lines of code, 52 to be exact."
},
{
"code": null,
"e": 2473,
"s": 2364,
"text": "Let’s take a look at the tech behind the app. It is based on 5 Python libraries consisting of the following:"
},
{
"code": null,
"e": 2688,
"s": 2473,
"text": "numpy — used for generating a synthetic dataset consisting of 5 columns (variables) that is used an example dataset (notice the Press to use Example Dataset button in the main panel under the web app’s page title)."
},
{
"code": null,
"e": 2751,
"s": 2688,
"text": "pandas — used for housing the data in the form of a DataFrame."
},
{
"code": null,
"e": 2831,
"s": 2751,
"text": "streamlit — the web framework that makes it possible to build a simple web app."
},
{
"code": null,
"e": 2944,
"s": 2831,
"text": "pandas_profiling— the library that makes it possible to generate the interactive HTML report for performing EDA."
},
{
"code": null,
"e": 3061,
"s": 2944,
"text": "streamlit_pandas_profiling — the library that allows the pandas_profiling library to be used in a Streamlit web app."
},
{
"code": null,
"e": 3179,
"s": 3061,
"text": "Import prerequisite libraries consisting of numpy, pandas, streamlit, pandas_profiling and streamlit_pandas_profiling"
},
{
"code": null,
"e": 3277,
"s": 3179,
"text": "Line 7 — commented text to denote that the subsequent code block pertains to the web app’s title."
},
{
"code": null,
"e": 3392,
"s": 3277,
"text": "Lines 8–13 — the st.markdown() function to print the web app’s title. The input arguments are in Markdown syntax ."
},
{
"code": null,
"e": 3495,
"s": 3392,
"text": "Line 15 — Commented text to describe that Lines 16–20 is responsible for the CSV upload functionality."
},
{
"code": null,
"e": 3723,
"s": 3495,
"text": "Line 16 — with is used to structure the subsequent lines of code to belong to the code block. st.sidebar.header() specifies the use of the header() function to display the heading text 1. Upload your CSV data in the left panel."
},
{
"code": null,
"e": 4080,
"s": 3723,
"text": "Line 17 — The st.sidebar.file_uploader() function allows the creation of the upload box. It should be noted that st.sidebar specifies the location of the upload box to be in the sidebar (the collapsible left panel). The input argument type=[\"csv\"] found inside the file_uploader() function specifies that the upload box would only accept the csv file type."
},
{
"code": null,
"e": 4237,
"s": 4080,
"text": "Line 18 — The st.sidebar.markdown() function specifies the use of the markdown() function to display a link to the example CSV file to be in the left panel."
},
{
"code": null,
"e": 4632,
"s": 4237,
"text": "Line 22 — Commented text to describe that the subsequent code blocks are responsible for creating the Pandas Profiling report. It should be noted here that this section consists of an if-else statement whereby the else code block (Lines 35–52) will be run at default every time the web app loads. Upon uploading an input CSV file, the if code block (Lines 23–34) will then be activated and run."
},
{
"code": null,
"e": 5926,
"s": 4632,
"text": "Lines 23–34 — This code block represents the if statement. As mentioned above in the previous bullet point, this code block will run upon uploading of the input CSV file. — Line 23 — An if condition is set to detect that a file is uploaded as indicated by the uploaded_file is not None. — Line 24 — The @st.cache decorator allows the app to skip a costly and repetitive of a function defined in the subsequent lines of code. — Lines 25–27 — A custom function called load_csv that reads in the input CSV file from the upload box via the uploaded_file variable. — Line 28 — Contents of the CSV file as read from the load_csv custom function is assigned to the df variable. — Line 29 — The ProfileReport() function is assigned to the pr variable. — Lines 30–31 — A header for **Input DataFrame** is printed as a heading text via the st.header() function (Line 30). Contents of the DataFrame stored in the df variable is printed (Line 31). — Line 32 — \"- — -” prints a horizontal bar. — Line 33–34 — A header for **Pandas Profiling Report** is printed as a heading text via the st.header() function (Line 33). Contents of the pr variable, which stores the output from the ProfileReport() function is printed. Particularly, this is the interactive HTML profile report that allows EDA functionality."
},
{
"code": null,
"e": 7020,
"s": 5926,
"text": "Lines 35–52 — This code block represents the else statement. — Line 35 — An else condition is set as the default state that is run every time the web app loads. — Line 36 — A text saying Awaiting for CSV file to be uploaded. is printed in an info box via the st.info() function. — Lines 37–52 — An if condition is used to specify the consequences (statements underneath it will be run) of clicking the Press to use Example Dataset button, which is to use the example dataset to generate the profile report. — Line 38 — Commented text to indicate that the following lines of code pertains to the example data. — Line 39 — As described earlier for Line 24, the @st.cache decorator allows the app to skip a potentially costly run of the subsequent lines of code (i.e. otherwise the app will re-generate the synthetic dataset everytime the app is reloaded).— Lines 40–45 — A custom function is defined to create a synthetic dataset consisting of 5 columns using the NumPy library. — Line 46 — The synthetic dataset as defined by the custom function from Lines 40–45 is assigned to the df variable."
},
{
"code": null,
"e": 7050,
"s": 7020,
"text": "It’s now time to run the app."
},
{
"code": null,
"e": 7224,
"s": 7050,
"text": "Let’s assume that you are starting from scratch, thus you will have to create a new conda environment (which is a good idea in order to ensure reproducibility of your code)."
},
{
"code": null,
"e": 7314,
"s": 7224,
"text": "Firstly, create a new conda environment called eda as follows in a terminal command line:"
},
{
"code": null,
"e": 7347,
"s": 7314,
"text": "conda create -n eda python=3.7.9"
},
{
"code": null,
"e": 7394,
"s": 7347,
"text": "Secondly, we will login to the eda environment"
},
{
"code": null,
"e": 7413,
"s": 7394,
"text": "conda activate eda"
},
{
"code": null,
"e": 7457,
"s": 7413,
"text": "Firstly, download the requirements.txt file"
},
{
"code": null,
"e": 7540,
"s": 7457,
"text": "wget https://raw.githubusercontent.com/dataprofessor/eda-app/main/requirements.txt"
},
{
"code": null,
"e": 7587,
"s": 7540,
"text": "Secondly, install the libraries as shown below"
},
{
"code": null,
"e": 7619,
"s": 7587,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 7768,
"s": 7619,
"text": "You can either download the web app files that are hosted on the GitHub repo of the Data Professor or you also use the 52 lines of code found above."
},
{
"code": null,
"e": 7831,
"s": 7768,
"text": "wget https://github.com/dataprofessor/eda-app/archive/main.zip"
},
{
"code": null,
"e": 7861,
"s": 7831,
"text": "Next, unzip the file contents"
},
{
"code": null,
"e": 7876,
"s": 7861,
"text": "unzip main.zip"
},
{
"code": null,
"e": 7924,
"s": 7876,
"text": "Now enter the main directory via the cd command"
},
{
"code": null,
"e": 7932,
"s": 7924,
"text": "cd main"
},
{
"code": null,
"e": 8017,
"s": 7932,
"text": "Now that you’re inside the main directory you should be able to see the app.py file."
},
{
"code": null,
"e": 8169,
"s": 8017,
"text": "The app can be launched by typing the following commands into a terminal prompt (i.e. ensure that the app.py file is in the current working directory):"
},
{
"code": null,
"e": 8190,
"s": 8169,
"text": "streamlit run app.py"
},
{
"code": null,
"e": 8261,
"s": 8190,
"text": "Afterwards, you will see the following message in the terminal prompt."
},
{
"code": null,
"e": 8402,
"s": 8261,
"text": "> streamlit run app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501"
},
{
"code": null,
"e": 8456,
"s": 8402,
"text": "Finally, a browser should pop up and the app appears."
},
{
"code": null,
"e": 8630,
"s": 8456,
"text": "You have now created an EDA app that will allow you to easily perform EDA analysis on-the-go, just simply upload an input CSV file to get started in performing EDA analysis."
},
{
"code": null,
"e": 8826,
"s": 8630,
"text": "If you would like to make your web app publicly available to the world, you can deploy it to the internet. I’ve created YouTube videos showing how you can do that on Heroku and Streamlit Sharing."
},
{
"code": null,
"e": 8871,
"s": 8826,
"text": "How to Deploy Data Science Web App to Heroku"
},
{
"code": null,
"e": 8927,
"s": 8871,
"text": "How to Deploy Data Science Web App to Streamlit Sharing"
},
{
"code": null,
"e": 9050,
"s": 8927,
"text": "An example of the deployed EDA App on the internet via the Streamlit Sharing platform can be accessible here: EDA App demo"
},
{
"code": null,
"e": 9412,
"s": 9050,
"text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)."
},
{
"code": null,
"e": 9428,
"s": 9412,
"text": "www.youtube.com"
}
] |
Firebase - Anonymous Authentication
|
In this chapter, we will authenticate users anonymously.
This is the same process as in our earlier chapters. You need to open the Firebase dashboard, click on Auth from the side menu and SIGN-IN-METHOD inside the tab bar. You need to enable anonymous authentication.
We can use signInAnonymously() method for this authentication.
Let us consider the following example.
firebase.auth().signInAnonymously()
.then(function() {
console.log('Logged in as Anonymous!')
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2223,
"s": 2166,
"text": "In this chapter, we will authenticate users anonymously."
},
{
"code": null,
"e": 2434,
"s": 2223,
"text": "This is the same process as in our earlier chapters. You need to open the Firebase dashboard, click on Auth from the side menu and SIGN-IN-METHOD inside the tab bar. You need to enable anonymous authentication."
},
{
"code": null,
"e": 2497,
"s": 2434,
"text": "We can use signInAnonymously() method for this authentication."
},
{
"code": null,
"e": 2536,
"s": 2497,
"text": "Let us consider the following example."
},
{
"code": null,
"e": 2796,
"s": 2536,
"text": "firebase.auth().signInAnonymously()\n.then(function() {\n console.log('Logged in as Anonymous!')\n \n }).catch(function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n console.log(errorCode);\n console.log(errorMessage);\n});"
},
{
"code": null,
"e": 2829,
"s": 2796,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2846,
"s": 2829,
"text": " University Code"
},
{
"code": null,
"e": 2881,
"s": 2846,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2892,
"s": 2881,
"text": " Appeteria"
},
{
"code": null,
"e": 2928,
"s": 2892,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 2939,
"s": 2928,
"text": " Appeteria"
},
{
"code": null,
"e": 2974,
"s": 2939,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2991,
"s": 2974,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 3026,
"s": 2991,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3041,
"s": 3026,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 3077,
"s": 3041,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 3092,
"s": 3077,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 3099,
"s": 3092,
"text": " Print"
},
{
"code": null,
"e": 3110,
"s": 3099,
"text": " Add Notes"
}
] |
Reorder an array according to given indexes - GeeksforGeeks
|
13 Jan, 2022
Given two integer arrays of same size, “arr[]” and “index[]”, reorder elements in “arr[]” according to given index array. It is not allowed to given array arr’s length.
Example:
Input: arr[] = [10, 11, 12];
index[] = [1, 0, 2];
Output: arr[] = [11, 10, 12]
index[] = [0, 1, 2]
Input: arr[] = [50, 40, 70, 60, 90]
index[] = [3, 0, 4, 1, 2]
Output: arr[] = [40, 60, 90, 50, 70]
index[] = [0, 1, 2, 3, 4]
Expected time complexity O(n) and auxiliary space O(1)
We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to use an auxiliary array temp[] of same size as given arrays. Traverse the given array and put all elements at their correct place in temp[] using index[]. Finally copy temp[] to arr[] and set all values of index[i] as i.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to sort an array according to given// indexes#include<iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index[], int n){ int temp[n]; // arr[i] should be present at index[i] index for (int i=0; i<n; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<n; i++) { arr[i] = temp[i]; index[i] = i; }} // Driver programint main(){ int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); reorder(arr, index, n); cout << "Reordered array is: \n"; for (int i=0; i<n; i++) cout << arr[i] << " "; cout << "\nModified Index array is: \n"; for (int i=0; i<n; i++) cout << index[i] << " "; return 0;}
//Java to find positions of zeroes flipping which// produces maximum number of consecutive 1's import java.util.Arrays; class Test{ static int arr[] = new int[]{50, 40, 70, 60, 90}; static int index[] = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { int temp[] = new int[arr.length]; // arr[i] should be present at index[i] index for (int i=0; i<arr.length; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<arr.length; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver method to test the above function public static void main(String[] args) { reorder(); System.out.println("Reordered array is: "); System.out.println(Arrays.toString(arr)); System.out.println("Modified Index array is:"); System.out.println(Arrays.toString(index)); }}
# Python3 program to sort# an array according to given# indexes # Function to reorder# elements of arr[] according# to index[]def reorder(arr,index, n): temp = [0] * n; # arr[i] should be # present at index[i] index for i in range(0,n): temp[index[i]] = arr[i] # Copy temp[] to arr[] for i in range(0,n): arr[i] = temp[i] index[i] = i # Driver programarr = [50, 40, 70, 60, 90]index = [3, 0, 4, 1, 2]n = len(arr) reorder(arr, index, n) print("Reordered array is:")for i in range(0,n): print(arr[i],end = " ") print("\nModified Index array is:")for i in range(0,n): print(index[i],end = " ") # This code is contributed by# Smitha Dinesh Semwal
// C# to find positions of zeroes flipping which// produces maximum number of consecutive 1'susing System; public class Test{ static int []arr = new int[]{50, 40, 70, 60, 90}; static int []index = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { int []temp = new int[arr.Length]; // arr[i] should be present at index[i] index for (int i=0; i<arr.Length; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<arr.Length; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver method to test the above function public static void Main() { reorder(); Console.WriteLine("Reordered array is: "); Console.WriteLine(string.Join(",", arr)); Console.WriteLine("Modified Index array is:"); Console.WriteLine(string.Join(",", index)); }}/*This code is contributed by 29AjayKumar*/
<?php// PHP program to sort an array// according to given indexes // Function to reorder elements// of arr[] according to index[]function reorder($arr, $index, $n){ // $temp[$n]; // arr[i] should be present // at index[i] index for ($i = 0; $i < $n; $i++) { $temp[$index[$i]] = $arr[$i]; } // Copy temp[] to arr[] for ($i = 0; $i < $n; $i++) { $arr[$i] = $temp[$i]; $index[$i] = $i; } echo "Reordered array is: \n";for ($i = 0; $i < $n; $i++){ echo $arr[$i] . " ";} echo "\nModified Index array is: \n";for ($i = 0; $i < $n; $i++){ echo $index[$i] . " ";}} // Driver Code$arr = array(50, 40, 70, 60, 90);$index = array(3, 0, 4, 1, 2);$n = sizeof($arr); reorder($arr, $index, $n); // This code is contributed// by Abby_akku?>
<script> // JavaScript program to sort an array according to given // indexes // Function to reorder elements of arr[] according // to index[] function reorder(arr, index, n) { var temp = [...Array(n)]; // arr[i] should be present at index[i] index for (var i = 0; i < n; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (var i = 0; i < n; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver program var arr = [50, 40, 70, 60, 90]; var index = [3, 0, 4, 1, 2]; var n = arr.length; reorder(arr, index, n); document.write("Reordered array is: "); document.write("<br>"); for (var i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br>"); document.write("Modified Index array is: "); document.write("<br>"); for (var i = 0; i < n; i++) document.write(index[i] + " "); // This code is contributed by rdtank. </script>
Output:
Reordered array is:
40 60 90 50 70
Modified Index array is:
0 1 2 3 4
Thanks to gccode for suggesting the above solution.
We can solve it Without Auxiliary Array. Below is the algorithm.
1) Do following for every element arr[i]
a) While index[i] is not equal to i
(i) Store array and index values of the target (or
correct) position where arr[i] should be placed.
The correct position for arr[i] is index[i]
(ii) Place arr[i] at its correct position. Also
update index value of correct position.
(iii) Copy old values of correct position (Stored in
step (i)) to arr[i] and index[i] as the while
loop continues for i.
Below is the implementation of the above algorithm.
C++
Java
Python3
C#
Javascript
// A O(n) time and O(1) extra space C++ program to// sort an array according to given indexes#include<iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index[], int n){ // Fix all elements one by one for (int i=0; i<n; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } }} // Driver programint main(){ int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); reorder(arr, index, n); cout << "Reordered array is: \n"; for (int i=0; i<n; i++) cout << arr[i] << " "; cout << "\nModified Index array is: \n"; for (int i=0; i<n; i++) cout << index[i] << " "; return 0;}
//A O(n) time and O(1) extra space Java program to//sort an array according to given indexes import java.util.Arrays; class Test{ static int arr[] = new int[]{50, 40, 70, 60, 90}; static int index[] = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { // Fix all elements one by one for (int i=0; i<arr.length; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = (char)arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } } } // Driver method to test the above function public static void main(String[] args) { reorder(); System.out.println("Reordered array is: "); System.out.println(Arrays.toString(arr)); System.out.println("Modified Index array is:"); System.out.println(Arrays.toString(index)); }}
# A O(n) time and O(1) extra space Python3 program to# sort an array according to given indexes # Function to reorder elements of arr[] according# to index[]def reorder(arr, index, n): # Fix all elements one by one for i in range(0,n): # While index[i] and arr[i] are not fixed while (index[i] != i): # Store values of the target (or correct) # position before placing arr[i] there oldTargetI = index[index[i]] oldTargetE = arr[index[i]] # Place arr[i] at its target (or correct) # position. Also copy corrected index for # new position arr[index[i]] = arr[i] index[index[i]] = index[i] # Copy old target values to arr[i] and # index[i] index[i] = oldTargetI arr[i] = oldTargetE # Driver programarr = [50, 40, 70, 60, 90]index= [3, 0, 4, 1, 2]n = len(arr) reorder(arr, index, n) print("Reordered array is:")for i in range(0, n): print(arr[i],end=" ") print("\nModified Index array is:")for i in range(0, n): print(index[i] ,end=" ") # This code is contributed by# Smitha Dinesh Semwal
//A O(n) time and O(1) extra space C# program to//sort an array according to given indexesusing System; public class Test{ static int []arr = new int[]{50, 40, 70, 60, 90}; static int []index = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { // Fix all elements one by one for (int i=0; i<arr.Length; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = (char)arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } } } // Driver method to test the above function public static void Main() { reorder(); Console.WriteLine("Reordered array is: "); Console.WriteLine(String.Join(" ",arr)); Console.WriteLine("Modified Index array is:"); Console.WriteLine(String.Join(" ",index)); }} // This code is contributed by PrinciRaj1992
<script>// A O(n) time and O(1) extra space JavaScript program to// sort an array according to given indexes // Function to reorder elements of arr[] according// to index[]function reorder(arr, index, n){ // Fix all elements one by one for (let i=0; i<n; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there let oldTargetI = index[index[i]]; let oldTargetE = arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } }} // Driver program let arr = [50, 40, 70, 60, 90]; let index = [3, 0, 4, 1, 2]; let n = arr.length; reorder(arr, index, n); document.write("Reordered array is: <br>"); for (let i=0; i<n; i++) document.write(arr[i] + " "); document.write("<br>Modified Index array is: <br>"); for (let i=0; i<n; i++) document.write(index[i] + " "); // This code is contributed by Surbhi Tyagi.</script>
Output:
Reordered array is:
40 60 90 50 70
Modified Index array is:
0 1 2 3 4
Thanks to shyamala_lokre for suggesting the above solution.
Another Method without using an auxiliary array is to sort the arrays. Sort the index array and customize the sort to swap the arr[] data whenever you swap the index[] data.
C++
Java
Python3
C#
Javascript
//C++ code to reorder an array according to given indices#include <bits/stdc++.h> using namespace std; int heapSize; void swap ( int &a, int &b ) { int temp = a; a = b; b = temp;} void heapify( int arr[], int index[], int i ){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // find largest index from root, left and right child if( left < heapSize && index[left] > index[largest] ) { largest = left; } if( right < heapSize && index[right] > index[largest] ) { largest = right; } if ( largest != i ) { //swap arr whenever index is swapped swap(arr[largest], arr[i]); swap(index[largest], index[i]); heapify(arr, index, largest); }} void heapSort( int arr[], int index[], int n ) {// Build heap for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i-- ) { heapify(arr, index, i); } // Swap the largest element of index(first element) // with the last element for ( int i = n - 1 ; i > 0 ; i-- ) { swap(index[0], index[i]); //swap arr whenever index is swapped swap(arr[0], arr[i]); heapSize--; heapify(arr, index, 0); }} // Driver Codeint main() { int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); heapSize = n; heapSort(arr, index, n); cout << "Reordered array is: \n"; for ( int i = 0 ; i < n ; i++ ) cout << arr[i] << " "; cout << "\nModified Index array is: \n"; for (int i=0; i<n; i++) cout << index[i] << " "; return 0;}
// Java code to reorder an array// according to given indicesclass GFG{ static int heapSize; public static void heapify(int arr[], int index[], int i){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // swap arr whenever index is swapped int temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} public static void heapSort(int arr[], int index[], int n){ // Build heap for(int i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(int i = n - 1 ; i > 0 ; i--) { int temp = index[0]; index[0] = index[i]; index[i] = temp; // swap arr whenever index is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver codepublic static void main(String[] args){ int arr[] = { 50, 40, 70, 60, 90 }; int index[] = { 3, 0, 4, 1, 2 }; int n = arr.length; heapSize = n; heapSort(arr, index, n); System.out.println("Reordered array is: "); for(int i = 0 ; i < n ; i++) System.out.print(arr[i] + " "); System.out.println(); System.out.println("Modified Index array is: "); for(int i = 0; i < n; i++) System.out.print(index[i] + " ");}} // This code is contributed by divyeshrabadiya07
# Python3 code to reorder an array# according to given indicesdef heapify(arr, index, i): largest = i # left child in 0 based indexing left = 2 * i + 1 # right child in 1 based indexing right = 2 * i + 2 global heapSize # Find largest index from root, # left and right child if (left < heapSize and index[left] > index[largest]): largest = left if (right < heapSize and index[right] > index[largest]): largest = right if (largest != i): # Swap arr whenever index is swapped arr[largest], arr[i] = arr[i], arr[largest] index[largest], index[i] = index[i], index[largest] heapify(arr, index, largest) def heapSort(arr, index, n): # Build heap global heapSize for i in range(int((n - 1) / 2), -1, -1): heapify(arr, index, i) # Swap the largest element of # index(first element) with # the last element for i in range(n - 1, 0, -1): index[0], index[i] = index[i], index[0] # Swap arr whenever index is swapped arr[0], arr[i] = arr[i], arr[0] heapSize -= 1 heapify(arr, index, 0) # Driver Codearr = [ 50, 40, 70, 60, 90 ]index = [ 3, 0, 4, 1, 2 ] n = len(arr)global heapSizeheapSize = nheapSort(arr, index, n) print("Reordered array is: ")print(*arr, sep = ' ')print("Modified Index array is: ")print(*index, sep = ' ') # This code is contributed by avanitrachhadiya2155
// C# code to reorder an array// according to given indicesusing System;using System.Collections.Generic; class GFG{ static int heapSize; public static void heapify(int[] arr, int[] index, int i){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // Swap arr whenever index is swapped int temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} public static void heapSort(int[] arr, int[] index, int n){ // Build heap for(int i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(int i = n - 1 ; i > 0 ; i--) { int temp = index[0]; index[0] = index[i]; index[i] = temp; // Swap arr whenever index // is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver Codestatic void Main(){ int[] arr = { 50, 40, 70, 60, 90 }; int[] index = { 3, 0, 4, 1, 2 }; int n = arr.Length; heapSize = n; heapSort(arr, index, n); Console.WriteLine("Reordered array is: "); for(int i = 0 ; i < n ; i++) Console.Write(arr[i] + " "); Console.WriteLine(); Console.WriteLine("Modified Index array is: "); for(int i = 0; i < n; i++) Console.Write(index[i] + " ");}} // This code is contributed by divyesh072019
<script>// Javascript code to reorder an array// according to given indices let heapSize; function heapify(arr,index,i){ let largest = i; // left child in 0 based indexing let left = 2 * i + 1; // right child in 1 based indexing let right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // swap arr whenever index is swapped let temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} function heapSort(arr,index,n){ // Build heap for(let i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(let i = n - 1 ; i > 0 ; i--) { let temp = index[0]; index[0] = index[i]; index[i] = temp; // swap arr whenever index is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver codelet arr=[50, 40, 70, 60, 90 ]; let index=[3, 0, 4, 1, 2];let n = arr.length; heapSize = n;heapSort(arr, index, n); document.write("Reordered array is: <br>");for(let i = 0 ; i < n ; i++) document.write(arr[i] + " "); document.write("<br>"); document.write("Modified Index array is: <br>");for(let i = 0; i < n; i++) document.write(index[i] + " "); // This code is contributed by ab2127</script>
Output:
Reordered array is:
40 60 90 50 70
Modified Index array is:
0 1 2 3 4
Time Complexity: O(nlogn)
Another method to solve the problem is with space Complexity of O(1) is :-
Swap the elements present in the arr until the index_arr[i] is not equal to the i.
Let’s dry run the below code for the given input :-
1st iteration :- (i=0)
arr = [ 50, 40, 70, 60, 90 ]
index_arr = [3, 0, 4, 1, 2 ]
since the index_arr[i] is not equal to i
swap the content present in the arr[i] with arr[index[i] and similarly swap for the index_arr also. After swapping we will have the following arr and index_arr values:-
arr = [ 60, 40, 70, 50, 90 ]
index_arr = [1, 0, 4, 3, 2 ]
Since index_arr[0] is not equal to i.
we again swap the content present at i with index_arr[i] for both the arrays (arr , index_arr).
arr = [ 40, 60, 70, 50, 90 ]
index_arr = [0, 1, 4, 3, 2 ]
2nd Iteration:- (i=1)
Since the value of index_arr[i] == i ; condition under the while loop does not get executed as the condition under the braces get false and hence move to the next iteration:-
3rd Iteration :- (i=2)
Since the value of index_arr[i] is not equal to i. Swap the content.
After Swapping we will get:-
arr = [ 40, 60, 90, 50, 70 ]
index_arr = [0, 1, 2, 3, 4].
Now for the next iteration (4th and 5th iteration) since the Value of index_arr[i] is equal to i . we just skip that loop ( because the condition under the while loop gets false and hence the while loop does not get executed.) and move to the next iteration.
C++
// A O(n) time and O(1) extra space C++ program to// sort an array according to given indexes#include <iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index_arr[], int n){ // Fix all elements one by one for (int i = 0; i < n; i++) { // While index[i] and arr[i] are not fixed while (index_arr[i] != i) { swap(arr[i], arr[index_arr[i]]); swap(index_arr[i], index_arr[index_arr[i]]); } }} // Driver programint main(){ int arr[] = { 50, 40, 70, 60, 90 }; int index[] = { 3, 0, 4, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); reorder(arr, index, n); cout << "Reordered array is: \n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\nModified Index array is: \n"; for (int i = 0; i < n; i++) cout << index[i] << " "; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
Reordered array is:
40 60 90 50 70
Modified Index array is:
0 1 2 3 4
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sakshi Parashar
Akanksha_Rai
29AjayKumar
princiraj1992
avanitrachhadiya2155
divyeshrabadiya07
divyesh072019
khushboogoyal499
rdtank
surbhityagi15
ab2127
adityakumar129
sagartomar9927
STL
Arrays
Arrays
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Subset Sum Problem | DP-25
Find the Missing Number
Array of Strings in C++ (5 Different Ways to Create)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find Second largest element in an array
Program to find largest element in an array
|
[
{
"code": null,
"e": 25438,
"s": 25410,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 25607,
"s": 25438,
"text": "Given two integer arrays of same size, “arr[]” and “index[]”, reorder elements in “arr[]” according to given index array. It is not allowed to given array arr’s length."
},
{
"code": null,
"e": 25617,
"s": 25607,
"text": "Example: "
},
{
"code": null,
"e": 25896,
"s": 25617,
"text": "Input: arr[] = [10, 11, 12];\n index[] = [1, 0, 2];\nOutput: arr[] = [11, 10, 12]\n index[] = [0, 1, 2] \n\nInput: arr[] = [50, 40, 70, 60, 90]\n index[] = [3, 0, 4, 1, 2]\nOutput: arr[] = [40, 60, 90, 50, 70]\n index[] = [0, 1, 2, 3, 4]"
},
{
"code": null,
"e": 25951,
"s": 25896,
"text": "Expected time complexity O(n) and auxiliary space O(1)"
},
{
"code": null,
"e": 26275,
"s": 25951,
"text": "We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to use an auxiliary array temp[] of same size as given arrays. Traverse the given array and put all elements at their correct place in temp[] using index[]. Finally copy temp[] to arr[] and set all values of index[i] as i. "
},
{
"code": null,
"e": 26279,
"s": 26275,
"text": "C++"
},
{
"code": null,
"e": 26284,
"s": 26279,
"text": "Java"
},
{
"code": null,
"e": 26292,
"s": 26284,
"text": "Python3"
},
{
"code": null,
"e": 26295,
"s": 26292,
"text": "C#"
},
{
"code": null,
"e": 26299,
"s": 26295,
"text": "PHP"
},
{
"code": null,
"e": 26310,
"s": 26299,
"text": "Javascript"
},
{
"code": "// C++ program to sort an array according to given// indexes#include<iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index[], int n){ int temp[n]; // arr[i] should be present at index[i] index for (int i=0; i<n; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<n; i++) { arr[i] = temp[i]; index[i] = i; }} // Driver programint main(){ int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); reorder(arr, index, n); cout << \"Reordered array is: \\n\"; for (int i=0; i<n; i++) cout << arr[i] << \" \"; cout << \"\\nModified Index array is: \\n\"; for (int i=0; i<n; i++) cout << index[i] << \" \"; return 0;}",
"e": 27139,
"s": 26310,
"text": null
},
{
"code": "//Java to find positions of zeroes flipping which// produces maximum number of consecutive 1's import java.util.Arrays; class Test{ static int arr[] = new int[]{50, 40, 70, 60, 90}; static int index[] = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { int temp[] = new int[arr.length]; // arr[i] should be present at index[i] index for (int i=0; i<arr.length; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<arr.length; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver method to test the above function public static void main(String[] args) { reorder(); System.out.println(\"Reordered array is: \"); System.out.println(Arrays.toString(arr)); System.out.println(\"Modified Index array is:\"); System.out.println(Arrays.toString(index)); }}",
"e": 28168,
"s": 27139,
"text": null
},
{
"code": "# Python3 program to sort# an array according to given# indexes # Function to reorder# elements of arr[] according# to index[]def reorder(arr,index, n): temp = [0] * n; # arr[i] should be # present at index[i] index for i in range(0,n): temp[index[i]] = arr[i] # Copy temp[] to arr[] for i in range(0,n): arr[i] = temp[i] index[i] = i # Driver programarr = [50, 40, 70, 60, 90]index = [3, 0, 4, 1, 2]n = len(arr) reorder(arr, index, n) print(\"Reordered array is:\")for i in range(0,n): print(arr[i],end = \" \") print(\"\\nModified Index array is:\")for i in range(0,n): print(index[i],end = \" \") # This code is contributed by# Smitha Dinesh Semwal",
"e": 28867,
"s": 28168,
"text": null
},
{
"code": "// C# to find positions of zeroes flipping which// produces maximum number of consecutive 1'susing System; public class Test{ static int []arr = new int[]{50, 40, 70, 60, 90}; static int []index = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { int []temp = new int[arr.Length]; // arr[i] should be present at index[i] index for (int i=0; i<arr.Length; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (int i=0; i<arr.Length; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver method to test the above function public static void Main() { reorder(); Console.WriteLine(\"Reordered array is: \"); Console.WriteLine(string.Join(\",\", arr)); Console.WriteLine(\"Modified Index array is:\"); Console.WriteLine(string.Join(\",\", index)); }}/*This code is contributed by 29AjayKumar*/",
"e": 29931,
"s": 28867,
"text": null
},
{
"code": "<?php// PHP program to sort an array// according to given indexes // Function to reorder elements// of arr[] according to index[]function reorder($arr, $index, $n){ // $temp[$n]; // arr[i] should be present // at index[i] index for ($i = 0; $i < $n; $i++) { $temp[$index[$i]] = $arr[$i]; } // Copy temp[] to arr[] for ($i = 0; $i < $n; $i++) { $arr[$i] = $temp[$i]; $index[$i] = $i; } echo \"Reordered array is: \\n\";for ($i = 0; $i < $n; $i++){ echo $arr[$i] . \" \";} echo \"\\nModified Index array is: \\n\";for ($i = 0; $i < $n; $i++){ echo $index[$i] . \" \";}} // Driver Code$arr = array(50, 40, 70, 60, 90);$index = array(3, 0, 4, 1, 2);$n = sizeof($arr); reorder($arr, $index, $n); // This code is contributed// by Abby_akku?>",
"e": 30732,
"s": 29931,
"text": null
},
{
"code": "<script> // JavaScript program to sort an array according to given // indexes // Function to reorder elements of arr[] according // to index[] function reorder(arr, index, n) { var temp = [...Array(n)]; // arr[i] should be present at index[i] index for (var i = 0; i < n; i++) temp[index[i]] = arr[i]; // Copy temp[] to arr[] for (var i = 0; i < n; i++) { arr[i] = temp[i]; index[i] = i; } } // Driver program var arr = [50, 40, 70, 60, 90]; var index = [3, 0, 4, 1, 2]; var n = arr.length; reorder(arr, index, n); document.write(\"Reordered array is: \"); document.write(\"<br>\"); for (var i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(\"<br>\"); document.write(\"Modified Index array is: \"); document.write(\"<br>\"); for (var i = 0; i < n; i++) document.write(index[i] + \" \"); // This code is contributed by rdtank. </script>",
"e": 31743,
"s": 30732,
"text": null
},
{
"code": null,
"e": 31751,
"s": 31743,
"text": "Output:"
},
{
"code": null,
"e": 31824,
"s": 31751,
"text": "Reordered array is: \n40 60 90 50 70 \nModified Index array is: \n0 1 2 3 4"
},
{
"code": null,
"e": 31877,
"s": 31824,
"text": "Thanks to gccode for suggesting the above solution. "
},
{
"code": null,
"e": 31943,
"s": 31877,
"text": "We can solve it Without Auxiliary Array. Below is the algorithm. "
},
{
"code": null,
"e": 32460,
"s": 31943,
"text": "1) Do following for every element arr[i]\n a) While index[i] is not equal to i\n (i) Store array and index values of the target (or \n correct) position where arr[i] should be placed.\n The correct position for arr[i] is index[i]\n (ii) Place arr[i] at its correct position. Also\n update index value of correct position.\n (iii) Copy old values of correct position (Stored in\n step (i)) to arr[i] and index[i] as the while \n loop continues for i."
},
{
"code": null,
"e": 32513,
"s": 32460,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 32517,
"s": 32513,
"text": "C++"
},
{
"code": null,
"e": 32522,
"s": 32517,
"text": "Java"
},
{
"code": null,
"e": 32530,
"s": 32522,
"text": "Python3"
},
{
"code": null,
"e": 32533,
"s": 32530,
"text": "C#"
},
{
"code": null,
"e": 32544,
"s": 32533,
"text": "Javascript"
},
{
"code": "// A O(n) time and O(1) extra space C++ program to// sort an array according to given indexes#include<iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index[], int n){ // Fix all elements one by one for (int i=0; i<n; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } }} // Driver programint main(){ int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); reorder(arr, index, n); cout << \"Reordered array is: \\n\"; for (int i=0; i<n; i++) cout << arr[i] << \" \"; cout << \"\\nModified Index array is: \\n\"; for (int i=0; i<n; i++) cout << index[i] << \" \"; return 0;}",
"e": 33888,
"s": 32544,
"text": null
},
{
"code": "//A O(n) time and O(1) extra space Java program to//sort an array according to given indexes import java.util.Arrays; class Test{ static int arr[] = new int[]{50, 40, 70, 60, 90}; static int index[] = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { // Fix all elements one by one for (int i=0; i<arr.length; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = (char)arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } } } // Driver method to test the above function public static void main(String[] args) { reorder(); System.out.println(\"Reordered array is: \"); System.out.println(Arrays.toString(arr)); System.out.println(\"Modified Index array is:\"); System.out.println(Arrays.toString(index)); }}",
"e": 35417,
"s": 33888,
"text": null
},
{
"code": "# A O(n) time and O(1) extra space Python3 program to# sort an array according to given indexes # Function to reorder elements of arr[] according# to index[]def reorder(arr, index, n): # Fix all elements one by one for i in range(0,n): # While index[i] and arr[i] are not fixed while (index[i] != i): # Store values of the target (or correct) # position before placing arr[i] there oldTargetI = index[index[i]] oldTargetE = arr[index[i]] # Place arr[i] at its target (or correct) # position. Also copy corrected index for # new position arr[index[i]] = arr[i] index[index[i]] = index[i] # Copy old target values to arr[i] and # index[i] index[i] = oldTargetI arr[i] = oldTargetE # Driver programarr = [50, 40, 70, 60, 90]index= [3, 0, 4, 1, 2]n = len(arr) reorder(arr, index, n) print(\"Reordered array is:\")for i in range(0, n): print(arr[i],end=\" \") print(\"\\nModified Index array is:\")for i in range(0, n): print(index[i] ,end=\" \") # This code is contributed by# Smitha Dinesh Semwal",
"e": 36632,
"s": 35417,
"text": null
},
{
"code": "//A O(n) time and O(1) extra space C# program to//sort an array according to given indexesusing System; public class Test{ static int []arr = new int[]{50, 40, 70, 60, 90}; static int []index = new int[]{3, 0, 4, 1, 2}; // Method to reorder elements of arr[] according // to index[] static void reorder() { // Fix all elements one by one for (int i=0; i<arr.Length; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there int oldTargetI = index[index[i]]; char oldTargetE = (char)arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } } } // Driver method to test the above function public static void Main() { reorder(); Console.WriteLine(\"Reordered array is: \"); Console.WriteLine(String.Join(\" \",arr)); Console.WriteLine(\"Modified Index array is:\"); Console.WriteLine(String.Join(\" \",index)); }} // This code is contributed by PrinciRaj1992",
"e": 38189,
"s": 36632,
"text": null
},
{
"code": "<script>// A O(n) time and O(1) extra space JavaScript program to// sort an array according to given indexes // Function to reorder elements of arr[] according// to index[]function reorder(arr, index, n){ // Fix all elements one by one for (let i=0; i<n; i++) { // While index[i] and arr[i] are not fixed while (index[i] != i) { // Store values of the target (or correct) // position before placing arr[i] there let oldTargetI = index[index[i]]; let oldTargetE = arr[index[i]]; // Place arr[i] at its target (or correct) // position. Also copy corrected index for // new position arr[index[i]] = arr[i]; index[index[i]] = index[i]; // Copy old target values to arr[i] and // index[i] index[i] = oldTargetI; arr[i] = oldTargetE; } }} // Driver program let arr = [50, 40, 70, 60, 90]; let index = [3, 0, 4, 1, 2]; let n = arr.length; reorder(arr, index, n); document.write(\"Reordered array is: <br>\"); for (let i=0; i<n; i++) document.write(arr[i] + \" \"); document.write(\"<br>Modified Index array is: <br>\"); for (let i=0; i<n; i++) document.write(index[i] + \" \"); // This code is contributed by Surbhi Tyagi.</script>",
"e": 39535,
"s": 38189,
"text": null
},
{
"code": null,
"e": 39543,
"s": 39535,
"text": "Output:"
},
{
"code": null,
"e": 39616,
"s": 39543,
"text": "Reordered array is: \n40 60 90 50 70 \nModified Index array is: \n0 1 2 3 4"
},
{
"code": null,
"e": 39676,
"s": 39616,
"text": "Thanks to shyamala_lokre for suggesting the above solution."
},
{
"code": null,
"e": 39850,
"s": 39676,
"text": "Another Method without using an auxiliary array is to sort the arrays. Sort the index array and customize the sort to swap the arr[] data whenever you swap the index[] data."
},
{
"code": null,
"e": 39854,
"s": 39850,
"text": "C++"
},
{
"code": null,
"e": 39859,
"s": 39854,
"text": "Java"
},
{
"code": null,
"e": 39867,
"s": 39859,
"text": "Python3"
},
{
"code": null,
"e": 39870,
"s": 39867,
"text": "C#"
},
{
"code": null,
"e": 39881,
"s": 39870,
"text": "Javascript"
},
{
"code": "//C++ code to reorder an array according to given indices#include <bits/stdc++.h> using namespace std; int heapSize; void swap ( int &a, int &b ) { int temp = a; a = b; b = temp;} void heapify( int arr[], int index[], int i ){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // find largest index from root, left and right child if( left < heapSize && index[left] > index[largest] ) { largest = left; } if( right < heapSize && index[right] > index[largest] ) { largest = right; } if ( largest != i ) { //swap arr whenever index is swapped swap(arr[largest], arr[i]); swap(index[largest], index[i]); heapify(arr, index, largest); }} void heapSort( int arr[], int index[], int n ) {// Build heap for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i-- ) { heapify(arr, index, i); } // Swap the largest element of index(first element) // with the last element for ( int i = n - 1 ; i > 0 ; i-- ) { swap(index[0], index[i]); //swap arr whenever index is swapped swap(arr[0], arr[i]); heapSize--; heapify(arr, index, 0); }} // Driver Codeint main() { int arr[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); heapSize = n; heapSort(arr, index, n); cout << \"Reordered array is: \\n\"; for ( int i = 0 ; i < n ; i++ ) cout << arr[i] << \" \"; cout << \"\\nModified Index array is: \\n\"; for (int i=0; i<n; i++) cout << index[i] << \" \"; return 0;}",
"e": 41548,
"s": 39881,
"text": null
},
{
"code": "// Java code to reorder an array// according to given indicesclass GFG{ static int heapSize; public static void heapify(int arr[], int index[], int i){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // swap arr whenever index is swapped int temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} public static void heapSort(int arr[], int index[], int n){ // Build heap for(int i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(int i = n - 1 ; i > 0 ; i--) { int temp = index[0]; index[0] = index[i]; index[i] = temp; // swap arr whenever index is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver codepublic static void main(String[] args){ int arr[] = { 50, 40, 70, 60, 90 }; int index[] = { 3, 0, 4, 1, 2 }; int n = arr.length; heapSize = n; heapSort(arr, index, n); System.out.println(\"Reordered array is: \"); for(int i = 0 ; i < n ; i++) System.out.print(arr[i] + \" \"); System.out.println(); System.out.println(\"Modified Index array is: \"); for(int i = 0; i < n; i++) System.out.print(index[i] + \" \");}} // This code is contributed by divyeshrabadiya07",
"e": 43606,
"s": 41548,
"text": null
},
{
"code": "# Python3 code to reorder an array# according to given indicesdef heapify(arr, index, i): largest = i # left child in 0 based indexing left = 2 * i + 1 # right child in 1 based indexing right = 2 * i + 2 global heapSize # Find largest index from root, # left and right child if (left < heapSize and index[left] > index[largest]): largest = left if (right < heapSize and index[right] > index[largest]): largest = right if (largest != i): # Swap arr whenever index is swapped arr[largest], arr[i] = arr[i], arr[largest] index[largest], index[i] = index[i], index[largest] heapify(arr, index, largest) def heapSort(arr, index, n): # Build heap global heapSize for i in range(int((n - 1) / 2), -1, -1): heapify(arr, index, i) # Swap the largest element of # index(first element) with # the last element for i in range(n - 1, 0, -1): index[0], index[i] = index[i], index[0] # Swap arr whenever index is swapped arr[0], arr[i] = arr[i], arr[0] heapSize -= 1 heapify(arr, index, 0) # Driver Codearr = [ 50, 40, 70, 60, 90 ]index = [ 3, 0, 4, 1, 2 ] n = len(arr)global heapSizeheapSize = nheapSort(arr, index, n) print(\"Reordered array is: \")print(*arr, sep = ' ')print(\"Modified Index array is: \")print(*index, sep = ' ') # This code is contributed by avanitrachhadiya2155",
"e": 45086,
"s": 43606,
"text": null
},
{
"code": "// C# code to reorder an array// according to given indicesusing System;using System.Collections.Generic; class GFG{ static int heapSize; public static void heapify(int[] arr, int[] index, int i){ int largest = i; // left child in 0 based indexing int left = 2 * i + 1; // right child in 1 based indexing int right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // Swap arr whenever index is swapped int temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} public static void heapSort(int[] arr, int[] index, int n){ // Build heap for(int i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(int i = n - 1 ; i > 0 ; i--) { int temp = index[0]; index[0] = index[i]; index[i] = temp; // Swap arr whenever index // is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver Codestatic void Main(){ int[] arr = { 50, 40, 70, 60, 90 }; int[] index = { 3, 0, 4, 1, 2 }; int n = arr.Length; heapSize = n; heapSort(arr, index, n); Console.WriteLine(\"Reordered array is: \"); for(int i = 0 ; i < n ; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); Console.WriteLine(\"Modified Index array is: \"); for(int i = 0; i < n; i++) Console.Write(index[i] + \" \");}} // This code is contributed by divyesh072019",
"e": 47230,
"s": 45086,
"text": null
},
{
"code": "<script>// Javascript code to reorder an array// according to given indices let heapSize; function heapify(arr,index,i){ let largest = i; // left child in 0 based indexing let left = 2 * i + 1; // right child in 1 based indexing let right = 2 * i + 2; // Find largest index from root, // left and right child if (left < heapSize && index[left] > index[largest] ) { largest = left; } if (right < heapSize && index[right] > index[largest] ) { largest = right; } if (largest != i) { // swap arr whenever index is swapped let temp = arr[largest]; arr[largest] = arr[i]; arr[i] = temp; temp = index[largest]; index[largest] = index[i]; index[i] = temp; heapify(arr, index, largest); }} function heapSort(arr,index,n){ // Build heap for(let i = (n - 1) / 2 ; i >= 0 ; i--) { heapify(arr, index, i); } // Swap the largest element of // index(first element) // with the last element for(let i = n - 1 ; i > 0 ; i--) { let temp = index[0]; index[0] = index[i]; index[i] = temp; // swap arr whenever index is swapped temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapSize--; heapify(arr, index, 0); }} // Driver codelet arr=[50, 40, 70, 60, 90 ]; let index=[3, 0, 4, 1, 2];let n = arr.length; heapSize = n;heapSort(arr, index, n); document.write(\"Reordered array is: <br>\");for(let i = 0 ; i < n ; i++) document.write(arr[i] + \" \"); document.write(\"<br>\"); document.write(\"Modified Index array is: <br>\");for(let i = 0; i < n; i++) document.write(index[i] + \" \"); // This code is contributed by ab2127</script>",
"e": 49053,
"s": 47230,
"text": null
},
{
"code": null,
"e": 49061,
"s": 49053,
"text": "Output:"
},
{
"code": null,
"e": 49134,
"s": 49061,
"text": "Reordered array is: \n40 60 90 50 70 \nModified Index array is: \n0 1 2 3 4"
},
{
"code": null,
"e": 49161,
"s": 49134,
"text": "Time Complexity: O(nlogn) "
},
{
"code": null,
"e": 49236,
"s": 49161,
"text": "Another method to solve the problem is with space Complexity of O(1) is :-"
},
{
"code": null,
"e": 49319,
"s": 49236,
"text": "Swap the elements present in the arr until the index_arr[i] is not equal to the i."
},
{
"code": null,
"e": 49372,
"s": 49319,
"text": "Let’s dry run the below code for the given input :- "
},
{
"code": null,
"e": 49395,
"s": 49372,
"text": "1st iteration :- (i=0)"
},
{
"code": null,
"e": 49424,
"s": 49395,
"text": "arr = [ 50, 40, 70, 60, 90 ]"
},
{
"code": null,
"e": 49453,
"s": 49424,
"text": "index_arr = [3, 0, 4, 1, 2 ]"
},
{
"code": null,
"e": 49494,
"s": 49453,
"text": "since the index_arr[i] is not equal to i"
},
{
"code": null,
"e": 49664,
"s": 49494,
"text": "swap the content present in the arr[i] with arr[index[i] and similarly swap for the index_arr also. After swapping we will have the following arr and index_arr values:- "
},
{
"code": null,
"e": 49693,
"s": 49664,
"text": "arr = [ 60, 40, 70, 50, 90 ]"
},
{
"code": null,
"e": 49722,
"s": 49693,
"text": "index_arr = [1, 0, 4, 3, 2 ]"
},
{
"code": null,
"e": 49760,
"s": 49722,
"text": "Since index_arr[0] is not equal to i."
},
{
"code": null,
"e": 49856,
"s": 49760,
"text": "we again swap the content present at i with index_arr[i] for both the arrays (arr , index_arr)."
},
{
"code": null,
"e": 49885,
"s": 49856,
"text": "arr = [ 40, 60, 70, 50, 90 ]"
},
{
"code": null,
"e": 49914,
"s": 49885,
"text": "index_arr = [0, 1, 4, 3, 2 ]"
},
{
"code": null,
"e": 49936,
"s": 49914,
"text": "2nd Iteration:- (i=1)"
},
{
"code": null,
"e": 50112,
"s": 49936,
"text": "Since the value of index_arr[i] == i ; condition under the while loop does not get executed as the condition under the braces get false and hence move to the next iteration:- "
},
{
"code": null,
"e": 50135,
"s": 50112,
"text": "3rd Iteration :- (i=2)"
},
{
"code": null,
"e": 50204,
"s": 50135,
"text": "Since the value of index_arr[i] is not equal to i. Swap the content."
},
{
"code": null,
"e": 50234,
"s": 50204,
"text": "After Swapping we will get:- "
},
{
"code": null,
"e": 50263,
"s": 50234,
"text": "arr = [ 40, 60, 90, 50, 70 ]"
},
{
"code": null,
"e": 50292,
"s": 50263,
"text": "index_arr = [0, 1, 2, 3, 4]."
},
{
"code": null,
"e": 50551,
"s": 50292,
"text": "Now for the next iteration (4th and 5th iteration) since the Value of index_arr[i] is equal to i . we just skip that loop ( because the condition under the while loop gets false and hence the while loop does not get executed.) and move to the next iteration."
},
{
"code": null,
"e": 50555,
"s": 50551,
"text": "C++"
},
{
"code": "// A O(n) time and O(1) extra space C++ program to// sort an array according to given indexes#include <iostream> using namespace std; // Function to reorder elements of arr[] according// to index[]void reorder(int arr[], int index_arr[], int n){ // Fix all elements one by one for (int i = 0; i < n; i++) { // While index[i] and arr[i] are not fixed while (index_arr[i] != i) { swap(arr[i], arr[index_arr[i]]); swap(index_arr[i], index_arr[index_arr[i]]); } }} // Driver programint main(){ int arr[] = { 50, 40, 70, 60, 90 }; int index[] = { 3, 0, 4, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); reorder(arr, index, n); cout << \"Reordered array is: \\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\nModified Index array is: \\n\"; for (int i = 0; i < n; i++) cout << index[i] << \" \"; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 51523,
"s": 50555,
"text": null
},
{
"code": null,
"e": 51597,
"s": 51523,
"text": "Reordered array is: \n40 60 90 50 70 \nModified Index array is: \n0 1 2 3 4 "
},
{
"code": null,
"e": 51722,
"s": 51597,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 51738,
"s": 51722,
"text": "Sakshi Parashar"
},
{
"code": null,
"e": 51751,
"s": 51738,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 51763,
"s": 51751,
"text": "29AjayKumar"
},
{
"code": null,
"e": 51777,
"s": 51763,
"text": "princiraj1992"
},
{
"code": null,
"e": 51798,
"s": 51777,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 51816,
"s": 51798,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 51830,
"s": 51816,
"text": "divyesh072019"
},
{
"code": null,
"e": 51847,
"s": 51830,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 51854,
"s": 51847,
"text": "rdtank"
},
{
"code": null,
"e": 51868,
"s": 51854,
"text": "surbhityagi15"
},
{
"code": null,
"e": 51875,
"s": 51868,
"text": "ab2127"
},
{
"code": null,
"e": 51890,
"s": 51875,
"text": "adityakumar129"
},
{
"code": null,
"e": 51905,
"s": 51890,
"text": "sagartomar9927"
},
{
"code": null,
"e": 51909,
"s": 51905,
"text": "STL"
},
{
"code": null,
"e": 51916,
"s": 51909,
"text": "Arrays"
},
{
"code": null,
"e": 51923,
"s": 51916,
"text": "Arrays"
},
{
"code": null,
"e": 51927,
"s": 51923,
"text": "STL"
},
{
"code": null,
"e": 52025,
"s": 51927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52034,
"s": 52025,
"text": "Comments"
},
{
"code": null,
"e": 52047,
"s": 52034,
"text": "Old Comments"
},
{
"code": null,
"e": 52070,
"s": 52047,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 52115,
"s": 52070,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 52169,
"s": 52115,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 52190,
"s": 52169,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 52217,
"s": 52190,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 52241,
"s": 52217,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 52294,
"s": 52241,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 52350,
"s": 52294,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 52390,
"s": 52350,
"text": "Find Second largest element in an array"
}
] |
Anonymous Union and Structure in C
|
Here we will see what is the anonymous union and structures in C. The anonymous unions and structures are unnamed unions and structures. As they have no names, so we cannot create direct objects of it. We use it as nested structures or unions.
These are the examples of anonymous union and structures.
struct {
datatype variable;
...
};
union {
datatype variable;
...
};
In this example we are making one structure, called point, it is holding an anonymous structure. This is holding two values x, y. We can access the anonymous structure or union members directly.
#include<stdio.h>
struct point {
// Anonymous structure
struct {
int x;
int y;
};
};
main() {
struct point pt;
pt.x = 10;
pt.y = 20;
printf("Point (%d,%d)", pt.x, pt.y); //anonymus members can be accessed directly
}
Point (10,20)
|
[
{
"code": null,
"e": 1306,
"s": 1062,
"text": "Here we will see what is the anonymous union and structures in C. The anonymous unions and structures are unnamed unions and structures. As they have no names, so we cannot create direct objects of it. We use it as nested structures or unions."
},
{
"code": null,
"e": 1364,
"s": 1306,
"text": "These are the examples of anonymous union and structures."
},
{
"code": null,
"e": 1445,
"s": 1364,
"text": "struct {\n datatype variable;\n ...\n};\nunion {\n datatype variable;\n ...\n};"
},
{
"code": null,
"e": 1640,
"s": 1445,
"text": "In this example we are making one structure, called point, it is holding an anonymous structure. This is holding two values x, y. We can access the anonymous structure or union members directly."
},
{
"code": null,
"e": 1889,
"s": 1640,
"text": "#include<stdio.h>\nstruct point {\n // Anonymous structure\n struct {\n int x;\n int y;\n };\n};\nmain() {\n struct point pt;\n pt.x = 10;\n pt.y = 20;\n printf(\"Point (%d,%d)\", pt.x, pt.y); //anonymus members can be accessed directly\n}"
},
{
"code": null,
"e": 1903,
"s": 1889,
"text": "Point (10,20)"
}
] |
Embedding for spelling correction | by Maxence Alluin | Towards Data Science
|
Automatic spelling correction, despite being worked on since the 70’s, remains hard to solve in the absence of significant user data.
Noisy text is problematic for many NLP tasks as it leads to a reduction of the accuracy of machine learning based techniques and increases the number of Out-Of-Vocabulary (OOV) words that cannot be handled by popular techniques such as Word2Vec or GloVe.
Hence as part of the preprocessing of our pipeline we have explored several approaches for proactive spelling correction of our input data in order to increase our accuracy on downstream tasks. We will focus here on trying to solve this problem through character-level embedding. Our work, which enables training from scratch, usage and visualization, is available for download and experimentation by following this link [1].
Spellings errors can be split into three groups that require different approaches:
Real Word Errors: ‘three’ spelled as ‘there’
Real Word Errors: ‘three’ spelled as ‘there’
Real word errors are the hardest kind to correct as they are context dependent, in order to correct them we have to analyze all the data to check for semantic consistency and grammar. Depending on the algorithm used we introduce the possibility of wrongly correcting accurate sentences and adding significant processing time. The most common way to handle this problem is seq2seq model or use of statistical data such as ngram token.
2. Short forms: ‘you’ spelled as ‘u’
Short forms have the characteristic of sharing few letters with the intended word. As far as edit distance is concerned ‘u’ is closer to ‘I’ than to ‘you’, therefore dictionary based approaches are less effective.
3. Non-word Errors: ‘fast’ spelled as ‘fsat’
Non-word errors are the most frequent and mostly arise from typos, these will be our focus here.
Spelling correction can be divided into three main tasks:
Taking a sentence as input, determine which words are misspelled.From a misspelled word, find a list of candidates for replacement.Choose the appropriate candidate from the list. (In the case of automatic correction)
Taking a sentence as input, determine which words are misspelled.
From a misspelled word, find a list of candidates for replacement.
Choose the appropriate candidate from the list. (In the case of automatic correction)
Since we are only interested in non-word errors, determining which words are misspelled is only a matter of checking them against a dictionary, though special care must be given regarding proper nouns.
There are a few different ways to select candidates:
The most naive approach is to compute your chosen edit distance between your word and your entire dictionary. While accurate, this approach is prohibitively expensive.
Phonetic algorithms [2] such as Soundex, Phonex or Metaphone. These algorithms will encode any string into a short sequence which allows string indexing by pronunciation. ‘hurry’ and ‘hirry’ will both return ‘H600’. By preprocessing your entire dictionary and indexing it by phonetic code, you can easily find phonetically similar candidates. Fast at runtime but it only corrects phonetic mistakes.
Computing a list of possible misspellings (insertion, deletion, transposition or replacement) for your word and matching it with your dictionary. While this is better than the naive approach it is quite slow due to the set of misspellings increasing in size at a rate of 54 * length+25. See the excellent article from Peter Norvig[3] for more explanation.
Symmetric spelling correction which takes the previous idea and extends it by computing misspellings both for the dictionary and the misspelled word. See Symspell[4] for more details. This technique is both accurate and blazing fast but at the cost of significant precomputing and disk-space and it requires a frequency list of your dictionary.
We have explored another approach to this problem by using word embeddings to represent words at the character level. Popular approaches for word embeddings such as Word2Vec seek to represent words by their semantics as it is very useful for a variety of tasks. However by using character based models it is possible to construct word embedding based on word spelling.
The idea is similar to phonetic algorithms which aim to represent similar words under the same single metric (a string or a floating point number) but we extends the idea by using an n-dimension embedding.
Our approach is as follows :
Train a model to produce character-level word embeddings
Vectorize our entire dictionary and build an index for efficient search
Vectorize misspelled word and look for the nearest neighbors
The model uses two layers of LSTM to build an embedding of a chosen size. A higher dimension provides more accurate results at the cost of longer computation time, for our usage we have settled for dimension 150. The model is trained by passing it a tuple of words which are either two completely different words or a word and a misspelling of it. The training objective is to minimize the norm of the difference between the two embeddings for similar tuple and maximize it for different words.
Training data has been generated using a dictionary of 600k words and generating several misspellings of edit distance 1 or 2 for each word. We have assigned higher probabilities to misspellings near the original characters on an AZERTY keyboard (since we are working in french) in order for the model to favor these. Due to the lack of clear training metrics it is difficult to know exactly when to stop training but after going through a few million training examples we were satisfied with the results.
Once trained the model can be used to vectorize words. By projecting them on a 2D plane with PCA we can obtain the following visualization:
python usage_visualisation.py
Success ! Similar words appear to be grouped together in the vector space.
This is not very useful by itself so now we are going to vectorize our entire 600k words dictionary. This process takes around 10 minutes on a modern CPU.
The final step is to construct an index which allows to efficiently search for the nearest vectors. Since we don’t need 100% accuracy and are more concerned with computing speed we will use nmslib[5], a library specialized in ANN (Approximate nearest neighbor) search.
This library allows us to run a search in the index for a number k of nearest neighbors of a given vector. We can adjust the number k nearest-neighbors to return to balance accuracy with computing time. Once we get the list of nearest neighbors we can further filter with edit distance to only keep relevant suggestions.
This gives us the following output (in French):
python usage_correction.py 'langqge'
Edit distance 1: langqge : [‘langage’]
Edit distance 2: langqge : [‘langages’, ‘lange’, ‘langé’, ‘langage’]
We have tested our model on a corpus that was generated through our spelling error generator (around 4k sentences). Our metric will be accuracy which we define as the % of times we catch the correct word in our candidates list.
On the whole corpus, the chars2vec model gives us an accuracy of 85% while standard phonetic algorithms stand around 40%. Combining the two approaches gives us 90% accuracy. The main bottleneck is around words of 4 characters or less which do not perform well.
This was to be expected as :
Words of that size have a lot of neighbors within short edit distance.
A typo in a 3-letter word is much more impactful than for a 10 letter one, which makes it much harder for the model to correctly map the words next to each other in the vector space.
While our previous example directly gives us the desired answer, there are often several candidates at edit distance and a choice has to be made.
We have tried two different approaches:
Probabilistic : Use a frequency list built on a large corpus and choose the most frequent word. The obvious con is that some infrequent words may never be chosen, while extremely simple this approach provides good accuracy.
Semantic : Rank candidates by their semantic similarity with the surrounding words in the sentence. This can be done by taking a pretrained skip-gram Word2Vec and calculating the mean distance between the embedding of the candidate and the surrounding words (or the whole sentence). While computing heavy this gives very good result for words with good semantic meaning though it is not very effective for words such as ‘there’, ‘I’, ‘are’ which can be used in any context.
Empirically we have found that the semantic approach works quite well for longer, less common words and the probabilistic approach is better for shorter words. Combining the two approaches with a handcrafted rules gives us around 70 % correction rate on our randomly generated corpus.
Instead of choosing between semantic and frequency the ideal approach would be to combine both. This can be achieved by using frequency tables of words N-grams.
To build these tables consecutive sequences of N words are counted and compiled on a very large corpus. The best resource available for this is Google Books N-gram[6] which has been built by analyzing around 5 million books in various languages.
The raw data is available via this link[7] though due to the sheer amount of text it takes significant time to download and compile it into an usable state.
Using character-level embeddings gives good overall performance and is particularly good for longer words. With handcrafted preprocessing rules and adequate candidates selection this provides a decent alternative to existing solutions for spelling correction.
Further works will include a proper benchmark with preexisting popular solutions and the use of n-gram tokens. In the meantime this package is free to be experimented with: char2vec [1].
[1] https://github.com/Lettria/Char2Vec
[2] https://en.wikipedia.org/wiki/Phonetic_algorithm
[3] https://norvig.com/spell-correct.html
[4] https://github.com/wolfgarbe/SymSpell
[5] https://github.com/nmslib/nmslib
[6] https://books.google.com/ngrams/
[7] http://storage.googleapis.com/books/ngrams/books/datasetsv2.html
Some rights reserved
|
[
{
"code": null,
"e": 306,
"s": 172,
"text": "Automatic spelling correction, despite being worked on since the 70’s, remains hard to solve in the absence of significant user data."
},
{
"code": null,
"e": 561,
"s": 306,
"text": "Noisy text is problematic for many NLP tasks as it leads to a reduction of the accuracy of machine learning based techniques and increases the number of Out-Of-Vocabulary (OOV) words that cannot be handled by popular techniques such as Word2Vec or GloVe."
},
{
"code": null,
"e": 987,
"s": 561,
"text": "Hence as part of the preprocessing of our pipeline we have explored several approaches for proactive spelling correction of our input data in order to increase our accuracy on downstream tasks. We will focus here on trying to solve this problem through character-level embedding. Our work, which enables training from scratch, usage and visualization, is available for download and experimentation by following this link [1]."
},
{
"code": null,
"e": 1070,
"s": 987,
"text": "Spellings errors can be split into three groups that require different approaches:"
},
{
"code": null,
"e": 1115,
"s": 1070,
"text": "Real Word Errors: ‘three’ spelled as ‘there’"
},
{
"code": null,
"e": 1160,
"s": 1115,
"text": "Real Word Errors: ‘three’ spelled as ‘there’"
},
{
"code": null,
"e": 1594,
"s": 1160,
"text": "Real word errors are the hardest kind to correct as they are context dependent, in order to correct them we have to analyze all the data to check for semantic consistency and grammar. Depending on the algorithm used we introduce the possibility of wrongly correcting accurate sentences and adding significant processing time. The most common way to handle this problem is seq2seq model or use of statistical data such as ngram token."
},
{
"code": null,
"e": 1631,
"s": 1594,
"text": "2. Short forms: ‘you’ spelled as ‘u’"
},
{
"code": null,
"e": 1845,
"s": 1631,
"text": "Short forms have the characteristic of sharing few letters with the intended word. As far as edit distance is concerned ‘u’ is closer to ‘I’ than to ‘you’, therefore dictionary based approaches are less effective."
},
{
"code": null,
"e": 1890,
"s": 1845,
"text": "3. Non-word Errors: ‘fast’ spelled as ‘fsat’"
},
{
"code": null,
"e": 1987,
"s": 1890,
"text": "Non-word errors are the most frequent and mostly arise from typos, these will be our focus here."
},
{
"code": null,
"e": 2045,
"s": 1987,
"text": "Spelling correction can be divided into three main tasks:"
},
{
"code": null,
"e": 2262,
"s": 2045,
"text": "Taking a sentence as input, determine which words are misspelled.From a misspelled word, find a list of candidates for replacement.Choose the appropriate candidate from the list. (In the case of automatic correction)"
},
{
"code": null,
"e": 2328,
"s": 2262,
"text": "Taking a sentence as input, determine which words are misspelled."
},
{
"code": null,
"e": 2395,
"s": 2328,
"text": "From a misspelled word, find a list of candidates for replacement."
},
{
"code": null,
"e": 2481,
"s": 2395,
"text": "Choose the appropriate candidate from the list. (In the case of automatic correction)"
},
{
"code": null,
"e": 2683,
"s": 2481,
"text": "Since we are only interested in non-word errors, determining which words are misspelled is only a matter of checking them against a dictionary, though special care must be given regarding proper nouns."
},
{
"code": null,
"e": 2736,
"s": 2683,
"text": "There are a few different ways to select candidates:"
},
{
"code": null,
"e": 2904,
"s": 2736,
"text": "The most naive approach is to compute your chosen edit distance between your word and your entire dictionary. While accurate, this approach is prohibitively expensive."
},
{
"code": null,
"e": 3303,
"s": 2904,
"text": "Phonetic algorithms [2] such as Soundex, Phonex or Metaphone. These algorithms will encode any string into a short sequence which allows string indexing by pronunciation. ‘hurry’ and ‘hirry’ will both return ‘H600’. By preprocessing your entire dictionary and indexing it by phonetic code, you can easily find phonetically similar candidates. Fast at runtime but it only corrects phonetic mistakes."
},
{
"code": null,
"e": 3659,
"s": 3303,
"text": "Computing a list of possible misspellings (insertion, deletion, transposition or replacement) for your word and matching it with your dictionary. While this is better than the naive approach it is quite slow due to the set of misspellings increasing in size at a rate of 54 * length+25. See the excellent article from Peter Norvig[3] for more explanation."
},
{
"code": null,
"e": 4004,
"s": 3659,
"text": "Symmetric spelling correction which takes the previous idea and extends it by computing misspellings both for the dictionary and the misspelled word. See Symspell[4] for more details. This technique is both accurate and blazing fast but at the cost of significant precomputing and disk-space and it requires a frequency list of your dictionary."
},
{
"code": null,
"e": 4373,
"s": 4004,
"text": "We have explored another approach to this problem by using word embeddings to represent words at the character level. Popular approaches for word embeddings such as Word2Vec seek to represent words by their semantics as it is very useful for a variety of tasks. However by using character based models it is possible to construct word embedding based on word spelling."
},
{
"code": null,
"e": 4579,
"s": 4373,
"text": "The idea is similar to phonetic algorithms which aim to represent similar words under the same single metric (a string or a floating point number) but we extends the idea by using an n-dimension embedding."
},
{
"code": null,
"e": 4608,
"s": 4579,
"text": "Our approach is as follows :"
},
{
"code": null,
"e": 4665,
"s": 4608,
"text": "Train a model to produce character-level word embeddings"
},
{
"code": null,
"e": 4737,
"s": 4665,
"text": "Vectorize our entire dictionary and build an index for efficient search"
},
{
"code": null,
"e": 4798,
"s": 4737,
"text": "Vectorize misspelled word and look for the nearest neighbors"
},
{
"code": null,
"e": 5293,
"s": 4798,
"text": "The model uses two layers of LSTM to build an embedding of a chosen size. A higher dimension provides more accurate results at the cost of longer computation time, for our usage we have settled for dimension 150. The model is trained by passing it a tuple of words which are either two completely different words or a word and a misspelling of it. The training objective is to minimize the norm of the difference between the two embeddings for similar tuple and maximize it for different words."
},
{
"code": null,
"e": 5799,
"s": 5293,
"text": "Training data has been generated using a dictionary of 600k words and generating several misspellings of edit distance 1 or 2 for each word. We have assigned higher probabilities to misspellings near the original characters on an AZERTY keyboard (since we are working in french) in order for the model to favor these. Due to the lack of clear training metrics it is difficult to know exactly when to stop training but after going through a few million training examples we were satisfied with the results."
},
{
"code": null,
"e": 5939,
"s": 5799,
"text": "Once trained the model can be used to vectorize words. By projecting them on a 2D plane with PCA we can obtain the following visualization:"
},
{
"code": null,
"e": 5969,
"s": 5939,
"text": "python usage_visualisation.py"
},
{
"code": null,
"e": 6044,
"s": 5969,
"text": "Success ! Similar words appear to be grouped together in the vector space."
},
{
"code": null,
"e": 6199,
"s": 6044,
"text": "This is not very useful by itself so now we are going to vectorize our entire 600k words dictionary. This process takes around 10 minutes on a modern CPU."
},
{
"code": null,
"e": 6468,
"s": 6199,
"text": "The final step is to construct an index which allows to efficiently search for the nearest vectors. Since we don’t need 100% accuracy and are more concerned with computing speed we will use nmslib[5], a library specialized in ANN (Approximate nearest neighbor) search."
},
{
"code": null,
"e": 6789,
"s": 6468,
"text": "This library allows us to run a search in the index for a number k of nearest neighbors of a given vector. We can adjust the number k nearest-neighbors to return to balance accuracy with computing time. Once we get the list of nearest neighbors we can further filter with edit distance to only keep relevant suggestions."
},
{
"code": null,
"e": 6837,
"s": 6789,
"text": "This gives us the following output (in French):"
},
{
"code": null,
"e": 6874,
"s": 6837,
"text": "python usage_correction.py 'langqge'"
},
{
"code": null,
"e": 6913,
"s": 6874,
"text": "Edit distance 1: langqge : [‘langage’]"
},
{
"code": null,
"e": 6984,
"s": 6913,
"text": "Edit distance 2: langqge : [‘langages’, ‘lange’, ‘langé’, ‘langage’]"
},
{
"code": null,
"e": 7212,
"s": 6984,
"text": "We have tested our model on a corpus that was generated through our spelling error generator (around 4k sentences). Our metric will be accuracy which we define as the % of times we catch the correct word in our candidates list."
},
{
"code": null,
"e": 7473,
"s": 7212,
"text": "On the whole corpus, the chars2vec model gives us an accuracy of 85% while standard phonetic algorithms stand around 40%. Combining the two approaches gives us 90% accuracy. The main bottleneck is around words of 4 characters or less which do not perform well."
},
{
"code": null,
"e": 7502,
"s": 7473,
"text": "This was to be expected as :"
},
{
"code": null,
"e": 7573,
"s": 7502,
"text": "Words of that size have a lot of neighbors within short edit distance."
},
{
"code": null,
"e": 7756,
"s": 7573,
"text": "A typo in a 3-letter word is much more impactful than for a 10 letter one, which makes it much harder for the model to correctly map the words next to each other in the vector space."
},
{
"code": null,
"e": 7902,
"s": 7756,
"text": "While our previous example directly gives us the desired answer, there are often several candidates at edit distance and a choice has to be made."
},
{
"code": null,
"e": 7942,
"s": 7902,
"text": "We have tried two different approaches:"
},
{
"code": null,
"e": 8166,
"s": 7942,
"text": "Probabilistic : Use a frequency list built on a large corpus and choose the most frequent word. The obvious con is that some infrequent words may never be chosen, while extremely simple this approach provides good accuracy."
},
{
"code": null,
"e": 8640,
"s": 8166,
"text": "Semantic : Rank candidates by their semantic similarity with the surrounding words in the sentence. This can be done by taking a pretrained skip-gram Word2Vec and calculating the mean distance between the embedding of the candidate and the surrounding words (or the whole sentence). While computing heavy this gives very good result for words with good semantic meaning though it is not very effective for words such as ‘there’, ‘I’, ‘are’ which can be used in any context."
},
{
"code": null,
"e": 8925,
"s": 8640,
"text": "Empirically we have found that the semantic approach works quite well for longer, less common words and the probabilistic approach is better for shorter words. Combining the two approaches with a handcrafted rules gives us around 70 % correction rate on our randomly generated corpus."
},
{
"code": null,
"e": 9086,
"s": 8925,
"text": "Instead of choosing between semantic and frequency the ideal approach would be to combine both. This can be achieved by using frequency tables of words N-grams."
},
{
"code": null,
"e": 9332,
"s": 9086,
"text": "To build these tables consecutive sequences of N words are counted and compiled on a very large corpus. The best resource available for this is Google Books N-gram[6] which has been built by analyzing around 5 million books in various languages."
},
{
"code": null,
"e": 9489,
"s": 9332,
"text": "The raw data is available via this link[7] though due to the sheer amount of text it takes significant time to download and compile it into an usable state."
},
{
"code": null,
"e": 9749,
"s": 9489,
"text": "Using character-level embeddings gives good overall performance and is particularly good for longer words. With handcrafted preprocessing rules and adequate candidates selection this provides a decent alternative to existing solutions for spelling correction."
},
{
"code": null,
"e": 9936,
"s": 9749,
"text": "Further works will include a proper benchmark with preexisting popular solutions and the use of n-gram tokens. In the meantime this package is free to be experimented with: char2vec [1]."
},
{
"code": null,
"e": 9976,
"s": 9936,
"text": "[1] https://github.com/Lettria/Char2Vec"
},
{
"code": null,
"e": 10029,
"s": 9976,
"text": "[2] https://en.wikipedia.org/wiki/Phonetic_algorithm"
},
{
"code": null,
"e": 10071,
"s": 10029,
"text": "[3] https://norvig.com/spell-correct.html"
},
{
"code": null,
"e": 10113,
"s": 10071,
"text": "[4] https://github.com/wolfgarbe/SymSpell"
},
{
"code": null,
"e": 10150,
"s": 10113,
"text": "[5] https://github.com/nmslib/nmslib"
},
{
"code": null,
"e": 10187,
"s": 10150,
"text": "[6] https://books.google.com/ngrams/"
},
{
"code": null,
"e": 10256,
"s": 10187,
"text": "[7] http://storage.googleapis.com/books/ngrams/books/datasetsv2.html"
}
] |
Python – Create a new column in a Pandas dataframe
|
To create a new column, we will use the already created column. At first, let us create a DataFrame and read our CSV −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
Now, we will create a new column “New_Reg_Price” from the already created column “Reg_Price” and add 100 to each value, forming a new column −
dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)
Following is the code −
import pandas as pd
# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("DataFrame...\n",dataFrame)
# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)
dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)
print("Updated DataFrame with a new column...\n",dataFrame)
print("\n[Updated] Number of rows and column in our DataFrame = ",dataFrame.shape)
This will produce the following output −
DataFrame...
Car Date_of_Purchase Reg_Price
0 BMW 10/10/2020 1000
1 Lexus 10/12/2020 750
2 Audi 10/17/2020 750
3 Jaguar 10/16/2020 1500
4 Mustang 10/19/2020 1100
5 Lamborghini 10/22/2020 1000
Number of rows and column in our DataFrame = (6, 3)
Updated DataFrame with a new column ...
Car Date_of_Purchase Reg_Price New_Reg_Price
0 BMW 10/10/2020 1000 1100
1 Lexus 10/12/2020 750 850
2 Audi 10/17/2020 750 850
3 Jaguar 10/16/2020 1500 1600
4 Mustang 10/19/2020 1100 1200
5 Lamborghini 10/22/2020 1000 1100
(Updated)Number of rows and column in our DataFrame = (6, 4)
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "To create a new column, we will use the already created column. At first, let us create a DataFrame and read our CSV −"
},
{
"code": null,
"e": 1252,
"s": 1181,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\SalesRecords.csv\")"
},
{
"code": null,
"e": 1395,
"s": 1252,
"text": "Now, we will create a new column “New_Reg_Price” from the already created column “Reg_Price” and add 100 to each value, forming a new column −"
},
{
"code": null,
"e": 1455,
"s": 1395,
"text": "dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)"
},
{
"code": null,
"e": 1479,
"s": 1455,
"text": "Following is the code −"
},
{
"code": null,
"e": 1950,
"s": 1479,
"text": "import pandas as pd\n\n# reading csv file\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\SalesRecords.csv\")\nprint(\"DataFrame...\\n\",dataFrame)\n\n# count the rows and columns in a DataFrame\nprint(\"\\nNumber of rows and column in our DataFrame = \",dataFrame.shape)\n\ndataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)\n\nprint(\"Updated DataFrame with a new column...\\n\",dataFrame)\n\nprint(\"\\n[Updated] Number of rows and column in our DataFrame = \",dataFrame.shape)\n\n"
},
{
"code": null,
"e": 1991,
"s": 1950,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2915,
"s": 1991,
"text": "DataFrame...\n Car Date_of_Purchase Reg_Price\n0 BMW 10/10/2020 1000\n1 Lexus 10/12/2020 750\n2 Audi 10/17/2020 750\n3 Jaguar 10/16/2020 1500\n4 Mustang 10/19/2020 1100\n5 Lamborghini 10/22/2020 1000\n\nNumber of rows and column in our DataFrame = (6, 3)\nUpdated DataFrame with a new column ...\n Car Date_of_Purchase Reg_Price New_Reg_Price\n0 BMW 10/10/2020 1000 1100\n1 Lexus 10/12/2020 750 850\n2 Audi 10/17/2020 750 850\n3 Jaguar 10/16/2020 1500 1600\n4 Mustang 10/19/2020 1100 1200\n5 Lamborghini 10/22/2020 1000 1100\n\n(Updated)Number of rows and column in our DataFrame = (6, 4)"
}
] |
gdbserver - Unix, Linux Command
|
Usage (server (target) side):
First, you need to have a copy of the program you want to debug put onto
the target system. The program can be stripped to save space if needed, as
GDBserver doesn’t care about symbols. All symbol handling is taken care of by
the GDB running on the host system.
To use the server, you log on to the target system, and run the ‘gdbserver’
program. You must tell it (a) how to communicate with GDB, (b) the name of
your program, and (c) its arguments. The general syntax is:
target> gdbserver COMM PROGRAM [ARGS ...]
For example, using a serial port, you might say:
target> gdbserver /dev/com1 emacs foo.txt
This tells gdbserver to debug emacs with an argument of foo.txt, and to
communicate with GDB via /dev/com1. Gdbserver now waits patiently for the
host GDB to communicate with it.
To use a TCP connection, you could say:
target> gdbserver host:2345 emacs foo.txt
This says pretty much the same thing as the last example, except that we are
going to communicate with the host GDB via TCP. The ‘host:2345’ argument means
that we are expecting to see a TCP connection from ‘host’ to local TCP port
2345. (Currently, the ‘host’ part is ignored.) You can choose any number you
want for the port number as long as it does not conflict with any existing TCP
ports on the target system. This same port number must be used in the host
GDBs ‘target remote’ command, which will be described shortly. Note that if
you chose a port number that conflicts with another service, gdbserver will
print an error message and exit.
On some targets, gdbserver can also attach to running programs.
This is accomplished via the --attach argument. The syntax is:
target> gdbserver COMM --attach PID
PID is the process ID of a currently running process. It isn’t
necessary to point gdbserver at a binary for the running process.
Usage (host side):
You need an unstripped copy of the target program on your host system, since
GDB needs to examine it’s symbol tables and such. Start up GDB as you normally
would, with the target program as the first argument. (You may need to use the
--baud option if the serial line is running at anything except 9600 baud.)
Ie: ‘gdb TARGET-PROG’, or ‘gdb --baud BAUD TARGET-PROG’. After that, the only
new command you need to know about is ‘target remote’. It’s argument is either
a device name (usually a serial device, like ‘/dev/ttyb’), or a HOST:PORT
descriptor. For example:
(gdb) target remote /dev/ttyb
communicates with the server via serial line /dev/ttyb, and:
(gdb) target remote the-target:2345
communicates via a TCP connection to port 2345 on host ‘the-target’, where
you previously started up gdbserver with the same port number. Note that for
TCP connections, you must start up gdbserver prior to using the ‘target remote’
command, otherwise you may get an error that looks something like
‘Connection refused’.
Remote debugging is particularly useful in cases of embedded applications where resources are scarce.
So in such cases the program can run on the target machine and you can debug it from remote host machine.
Below are steps involved in debugging with gdbserver
$ gdbserver localhost:2000 gdb_example -l 20 -b 10
Process gdb_example created; pid = 4674
Listening on port 2000
$ gcc -o gdb_example -g gdb_example.c
$ gdb -q gdb_example
Reading symbols from /home/gdb_example...done.
(gdb)
(gdb) target remote 15.77.28.37:2000
$ gdbserver localhost:2000 gdb_example -l 20 -b 10
Process gdb_example created; pid = 4674
Listening on port 2000
Remote debugging from host 15.77.28.36
Area: 20 * 10 = 200
Child exited with status 0
GDBserver exiting
$ gdb -q gdb_example
Reading symbols from /home/gdb_example...done.
(gdb) target remote 15.77.28.37:2000
Remote debugging using 15.77.28.37:2000
Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/ld-linux.so.2
0x00ab3810 in _start () from /lib/ld-linux.so.2
(gdb) b main
Breakpoint 1 at 0x80484fd: file gdb_example.c, line 18.
(gdb) c
Continuing.
Breakpoint 1, main (argc=5, argv=0xbfff8724) at gdb_example.c:18
18 if (argc != 5) {
(gdb) n
23 while ((c = getopt (argc, argv, "l:b:")) != -1) {
(gdb) n
24 switch( c ) {
(gdb) c
Continuing.
Program exited normally.
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": 10609,
"s": 10577,
"text": "\nUsage (server (target) side):\n"
},
{
"code": null,
"e": 10875,
"s": 10609,
"text": "\nFirst, you need to have a copy of the program you want to debug put onto\nthe target system. The program can be stripped to save space if needed, as\nGDBserver doesn’t care about symbols. All symbol handling is taken care of by\nthe GDB running on the host system.\n"
},
{
"code": null,
"e": 11090,
"s": 10875,
"text": "\nTo use the server, you log on to the target system, and run the ‘gdbserver’\nprogram. You must tell it (a) how to communicate with GDB, (b) the name of\nyour program, and (c) its arguments. The general syntax is:\n"
},
{
"code": null,
"e": 11142,
"s": 11090,
"text": "\n target> gdbserver COMM PROGRAM [ARGS ...]\n"
},
{
"code": null,
"e": 11193,
"s": 11142,
"text": "\nFor example, using a serial port, you might say:\n"
},
{
"code": null,
"e": 11245,
"s": 11193,
"text": "\n target> gdbserver /dev/com1 emacs foo.txt\n"
},
{
"code": null,
"e": 11427,
"s": 11245,
"text": "\nThis tells gdbserver to debug emacs with an argument of foo.txt, and to\ncommunicate with GDB via /dev/com1. Gdbserver now waits patiently for the\nhost GDB to communicate with it.\n"
},
{
"code": null,
"e": 11469,
"s": 11427,
"text": "\nTo use a TCP connection, you could say:\n"
},
{
"code": null,
"e": 11521,
"s": 11469,
"text": "\n target> gdbserver host:2345 emacs foo.txt\n"
},
{
"code": null,
"e": 12176,
"s": 11521,
"text": "\nThis says pretty much the same thing as the last example, except that we are\ngoing to communicate with the host GDB via TCP. The ‘host:2345’ argument means\nthat we are expecting to see a TCP connection from ‘host’ to local TCP port\n2345. (Currently, the ‘host’ part is ignored.) You can choose any number you\nwant for the port number as long as it does not conflict with any existing TCP\nports on the target system. This same port number must be used in the host\nGDBs ‘target remote’ command, which will be described shortly. Note that if\nyou chose a port number that conflicts with another service, gdbserver will\nprint an error message and exit.\n"
},
{
"code": null,
"e": 12306,
"s": 12176,
"text": "\nOn some targets, gdbserver can also attach to running programs.\nThis is accomplished via the --attach argument. The syntax is:\n"
},
{
"code": null,
"e": 12352,
"s": 12306,
"text": "\n target> gdbserver COMM --attach PID\n"
},
{
"code": null,
"e": 12484,
"s": 12352,
"text": "\nPID is the process ID of a currently running process. It isn’t\nnecessary to point gdbserver at a binary for the running process.\n"
},
{
"code": null,
"e": 12505,
"s": 12484,
"text": "\nUsage (host side):\n"
},
{
"code": null,
"e": 13078,
"s": 12505,
"text": "\nYou need an unstripped copy of the target program on your host system, since\nGDB needs to examine it’s symbol tables and such. Start up GDB as you normally\nwould, with the target program as the first argument. (You may need to use the\n--baud option if the serial line is running at anything except 9600 baud.)\nIe: ‘gdb TARGET-PROG’, or ‘gdb --baud BAUD TARGET-PROG’. After that, the only\nnew command you need to know about is ‘target remote’. It’s argument is either\na device name (usually a serial device, like ‘/dev/ttyb’), or a HOST:PORT\ndescriptor. For example:\n"
},
{
"code": null,
"e": 13118,
"s": 13078,
"text": "\n (gdb) target remote /dev/ttyb\n"
},
{
"code": null,
"e": 13181,
"s": 13118,
"text": "\ncommunicates with the server via serial line /dev/ttyb, and:\n"
},
{
"code": null,
"e": 13227,
"s": 13181,
"text": "\n (gdb) target remote the-target:2345\n"
},
{
"code": null,
"e": 13550,
"s": 13227,
"text": "\ncommunicates via a TCP connection to port 2345 on host ‘the-target’, where\nyou previously started up gdbserver with the same port number. Note that for\nTCP connections, you must start up gdbserver prior to using the ‘target remote’\ncommand, otherwise you may get an error that looks something like\n‘Connection refused’.\n"
},
{
"code": null,
"e": 13759,
"s": 13550,
"text": "Remote debugging is particularly useful in cases of embedded applications where resources are scarce. \nSo in such cases the program can run on the target machine and you can debug it from remote host machine."
},
{
"code": null,
"e": 13812,
"s": 13759,
"text": "Below are steps involved in debugging with gdbserver"
},
{
"code": null,
"e": 13927,
"s": 13812,
"text": "$ gdbserver localhost:2000 gdb_example -l 20 -b 10\nProcess gdb_example created; pid = 4674\nListening on port 2000\n"
},
{
"code": null,
"e": 13966,
"s": 13927,
"text": "$ gcc -o gdb_example -g gdb_example.c\n"
},
{
"code": null,
"e": 14041,
"s": 13966,
"text": "$ gdb -q gdb_example\nReading symbols from /home/gdb_example...done.\n(gdb)\n"
},
{
"code": null,
"e": 14079,
"s": 14041,
"text": "(gdb) target remote 15.77.28.37:2000\n"
},
{
"code": null,
"e": 14299,
"s": 14079,
"text": "$ gdbserver localhost:2000 gdb_example -l 20 -b 10\nProcess gdb_example created; pid = 4674\nListening on port 2000\nRemote debugging from host 15.77.28.36\nArea: 20 * 10 = 200\n\nChild exited with status 0\nGDBserver exiting\n"
},
{
"code": null,
"e": 14964,
"s": 14299,
"text": "$ gdb -q gdb_example\nReading symbols from /home/gdb_example...done.\n(gdb) target remote 15.77.28.37:2000\nRemote debugging using 15.77.28.37:2000\nReading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.\nLoaded symbols for /lib/ld-linux.so.2\n0x00ab3810 in _start () from /lib/ld-linux.so.2\n(gdb) b main\nBreakpoint 1 at 0x80484fd: file gdb_example.c, line 18.\n(gdb) c\nContinuing.\n\nBreakpoint 1, main (argc=5, argv=0xbfff8724) at gdb_example.c:18\n18 if (argc != 5) {\n(gdb) n\n23 while ((c = getopt (argc, argv, \"l:b:\")) != -1) {\n(gdb) n\n24 switch( c ) {\n(gdb) c\nContinuing.\n\nProgram exited normally.\n"
},
{
"code": null,
"e": 14999,
"s": 14964,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 15027,
"s": 14999,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 15061,
"s": 15027,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 15078,
"s": 15061,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 15111,
"s": 15078,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 15122,
"s": 15111,
"text": " Pradeep D"
},
{
"code": null,
"e": 15157,
"s": 15122,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 15173,
"s": 15157,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 15206,
"s": 15173,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15218,
"s": 15206,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 15250,
"s": 15218,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15258,
"s": 15250,
"text": " Uplatz"
},
{
"code": null,
"e": 15265,
"s": 15258,
"text": " Print"
},
{
"code": null,
"e": 15276,
"s": 15265,
"text": " Add Notes"
}
] |
Git Staging Environment
|
One of the core functions of Git is the concepts of the Staging Environment, and the Commit.
As you are working, you may be adding, editing and removing files. But
whenever you hit a milestone or finish a part of the work, you should add the
files to a Staging Environment.
Staged files are files that are ready to be
committed to the
repository you are working on. You will learn more about
commit shortly.
For now, we are done working with index.html.
So we can add it to the Staging Environment:
git add index.html
The file should be Staged. Let's check the status::
git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached ..." to unstage)
new file: index.html
Now the file has been added to the Staging Environment.
You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again.
A README.md file that describes the repository (recommended for all
repositories):
A basic external style sheet (bluestyle.css):
And update index.html to include the stylesheet:
Now add all files in the current directory to the Staging Environment:
git add --all
Using --all instead of individual filenames
will stage all changes (new, modified, and deleted) files.
git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached ..." to unstage)
new file: README.md
new file: bluestyle.css
new file: index.html
Now all 3 files are added to the Staging Environment, and we are ready to do
our first commit.
Note: The shorthand command for
git add --all is git add -A
Add index.html to the Stating Environment:
git index.html
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 93,
"s": 0,
"text": "One of the core functions of Git is the concepts of the Staging Environment, and the Commit."
},
{
"code": null,
"e": 276,
"s": 93,
"text": "As you are working, you may be adding, editing and removing files. But \nwhenever you hit a milestone or finish a part of the work, you should add the \nfiles to a Staging Environment."
},
{
"code": null,
"e": 413,
"s": 276,
"text": "Staged files are files that are ready to be \ncommitted to the \nrepository you are working on. You will learn more about \ncommit shortly."
},
{
"code": null,
"e": 505,
"s": 413,
"text": "For now, we are done working with index.html. \nSo we can add it to the Staging Environment:"
},
{
"code": null,
"e": 524,
"s": 505,
"text": "git add index.html"
},
{
"code": null,
"e": 576,
"s": 524,
"text": "The file should be Staged. Let's check the status::"
},
{
"code": null,
"e": 712,
"s": 576,
"text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: index.html"
},
{
"code": null,
"e": 768,
"s": 712,
"text": "Now the file has been added to the Staging Environment."
},
{
"code": null,
"e": 890,
"s": 768,
"text": "You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again."
},
{
"code": null,
"e": 974,
"s": 890,
"text": "A README.md file that describes the repository (recommended for all \nrepositories):"
},
{
"code": null,
"e": 1020,
"s": 974,
"text": "A basic external style sheet (bluestyle.css):"
},
{
"code": null,
"e": 1069,
"s": 1020,
"text": "And update index.html to include the stylesheet:"
},
{
"code": null,
"e": 1140,
"s": 1069,
"text": "Now add all files in the current directory to the Staging Environment:"
},
{
"code": null,
"e": 1154,
"s": 1140,
"text": "git add --all"
},
{
"code": null,
"e": 1258,
"s": 1154,
"text": "Using --all instead of individual filenames \nwill stage all changes (new, modified, and deleted) files."
},
{
"code": null,
"e": 1464,
"s": 1258,
"text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: README.md\n new file: bluestyle.css\n new file: index.html"
},
{
"code": null,
"e": 1560,
"s": 1464,
"text": "Now all 3 files are added to the Staging Environment, and we are ready to do \nour first commit."
},
{
"code": null,
"e": 1623,
"s": 1560,
"text": "Note: The shorthand command for \n git add --all is git add -A"
},
{
"code": null,
"e": 1666,
"s": 1623,
"text": "Add index.html to the Stating Environment:"
},
{
"code": null,
"e": 1683,
"s": 1666,
"text": "git index.html\n"
},
{
"code": null,
"e": 1703,
"s": 1683,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 1736,
"s": 1703,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1778,
"s": 1736,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1885,
"s": 1778,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1904,
"s": 1885,
"text": "help@w3schools.com"
}
] |
Bootstrap btn-toolbar class
|
Set Button Toolbar in Bootstrap using the btn-toolbar class.
You can try to run the following code to implement the btn-toolbar class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="/scripts/jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "btn-toolbar" role = "toolbar">
<div class = "btn-group">
<button type = "button" class = "btn btn-default">MCA</button>
<button type = "button" class = "btn btn-default">BCA</button>
</div>
<div class = "btn-group">
<button type = "button" class = "btn btn-default">MBA</button>
<button type = "button" class = "btn btn-default">MS</button>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "Set Button Toolbar in Bootstrap using the btn-toolbar class."
},
{
"code": null,
"e": 1198,
"s": 1123,
"text": "You can try to run the following code to implement the btn-toolbar class −"
},
{
"code": null,
"e": 1209,
"s": 1198,
"text": " Live Demo"
},
{
"code": null,
"e": 1970,
"s": 1209,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href=\"/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src=\"/scripts/jquery.min.js\"></script>\n <script src=\"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"btn-toolbar\" role = \"toolbar\">\n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">MCA</button>\n <button type = \"button\" class = \"btn btn-default\">BCA</button>\n </div>\n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">MBA</button>\n <button type = \"button\" class = \"btn btn-default\">MS</button>\n </div>\n </div>\n </body>\n</html>"
}
] |
Usage of Break keyword in Java - GeeksforGeeks
|
04 Dec, 2021
Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop, only the inner loop will get terminated. Even it is used with if statement to terminated when a certain condition is met.
The break keyword has special usage inside the switch statement. Every case in the switch statement is followed by a break keyword, such that whenever the program control jumps to the next case, it wouldn’t execute subsequent cases.
Real-life Illustration:
Consider a person climbing stairs. Now the red line here is depicting the stair on which his/her shoe slips and he/she rolls backs to the base. Remember if he/she slips, he/she will always be landing on the base.
Here in computers in programming language there is a keyword called ‘break’ which will abruptly stop the further execution of all the statements following it defined in that scope.
Syntax:
break keyword along with a semicolon
break;
Flow chart of Break statement
Use of Break Keyword is mostly found in loop concepts:
Case 1: Break keyword inside FOR loop
In order to show how to use the break keyword within For loop. Considering when the value of ‘i’ becomes 39, the break keyword plays its role and terminate the for a loop. All values of ‘i’ before 39, are displayed in the result.
Java
// Java Program to show use of break statement// inside the For looppublic class GFG { // Main driver code public static void main(String[] args) { // For loop for iteration for (int i = 3; i <= 50; i += 3) { if (i == 39) { // Using Break keyword to suspend // loop when i become 39 break; } // Printing elements showcasing break usage System.out.print(i + " "); } }}
Output:
3 6 9 12 15 18 21 24 27 30 33 36
Case 2: Break keyword inside WHILE loop
In order to show how to use the break keyword within the While loop. Considering when the value of ‘i’ becomes 15, the break keyword plays its role and terminate the for a loop. All values of ‘i’ greater than 15 till 35, are displayed in the result.
Java
// Java Program to illustrate the use of break statement// inside the While loop // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // While loop for iteration // Creating and initializing variable // outside loop int i = 35; // Condition check while (i >= 10) { if (i == 15) { // Using Break keyword to suspend // loop when i become 15 // Decrementing variable initialized above i--; // Break statement break; } // Printing elements showcasing break System.out.print(i + " "); i--; } }}
Output:
35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16
Case 3: Break keyword inside DO-WHILE loop
In order to show how to use the break keyword within the Do-while loop. Considering when the value of ‘i’ becomes 80, the break keyword plays its role and terminate the for a loop. All values of i” before 80, are displayed in the result.
Java
// Java Program to illustrate the use of break statement// Inside the do-While loop // Importing all generic classesimport java.util.*; // Importing specific class to take// user input from the userimport java.util.Scanner; public class GFG { // Main driver method public static void main(String[] args) { // Using do-While loop // Creating and initializing a variable // over which execution occurs int i = 0; // do loop consisting of executable statements do { if (i == 80) { // Incrementing variable by 5 i += 5; // Using Break keyword to // suspend loop when i become 80 break; } System.out.print(i + " "); // Printing elements to show break usage i += 5; } // Condition check while (i <= 100); }}
Output:
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
Case 4: Break keyword inside the Switch statement
In order to show how to use the break keyword within For loop. The break keyword is used at the bottom of every switch case to terminate each statement sequence and prevent the mixing of switch-case statements.
Java
// Java Program to illustrate the use of break statement// inside the Switch Statement // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Declaring a variable for switch expression int numb = 20; // Switch expression switch (numb) { // Case statements case 10: System.out.println("TEN"); // Break keyword to suspend the switch case // if given condition is fulfilled break; case 20: System.out.println("TWENTY"); break; case 30: System.out.println("THIRTY"); break; // Default case statement default: System.out.println("INFINITE"); } }}
Output:
TWENTY
saurabh1990aror
sooda367
singghakshay
Java-keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23582,
"s": 23554,
"text": "\n04 Dec, 2021"
},
{
"code": null,
"e": 24056,
"s": 23582,
"text": "Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop, only the inner loop will get terminated. Even it is used with if statement to terminated when a certain condition is met."
},
{
"code": null,
"e": 24290,
"s": 24056,
"text": "The break keyword has special usage inside the switch statement. Every case in the switch statement is followed by a break keyword, such that whenever the program control jumps to the next case, it wouldn’t execute subsequent cases. "
},
{
"code": null,
"e": 24314,
"s": 24290,
"text": "Real-life Illustration:"
},
{
"code": null,
"e": 24527,
"s": 24314,
"text": "Consider a person climbing stairs. Now the red line here is depicting the stair on which his/her shoe slips and he/she rolls backs to the base. Remember if he/she slips, he/she will always be landing on the base."
},
{
"code": null,
"e": 24708,
"s": 24527,
"text": "Here in computers in programming language there is a keyword called ‘break’ which will abruptly stop the further execution of all the statements following it defined in that scope."
},
{
"code": null,
"e": 24716,
"s": 24708,
"text": "Syntax:"
},
{
"code": null,
"e": 24753,
"s": 24716,
"text": "break keyword along with a semicolon"
},
{
"code": null,
"e": 24760,
"s": 24753,
"text": "break;"
},
{
"code": null,
"e": 24790,
"s": 24760,
"text": "Flow chart of Break statement"
},
{
"code": null,
"e": 24845,
"s": 24790,
"text": "Use of Break Keyword is mostly found in loop concepts:"
},
{
"code": null,
"e": 24883,
"s": 24845,
"text": "Case 1: Break keyword inside FOR loop"
},
{
"code": null,
"e": 25113,
"s": 24883,
"text": "In order to show how to use the break keyword within For loop. Considering when the value of ‘i’ becomes 39, the break keyword plays its role and terminate the for a loop. All values of ‘i’ before 39, are displayed in the result."
},
{
"code": null,
"e": 25118,
"s": 25113,
"text": "Java"
},
{
"code": "// Java Program to show use of break statement// inside the For looppublic class GFG { // Main driver code public static void main(String[] args) { // For loop for iteration for (int i = 3; i <= 50; i += 3) { if (i == 39) { // Using Break keyword to suspend // loop when i become 39 break; } // Printing elements showcasing break usage System.out.print(i + \" \"); } }}",
"e": 25610,
"s": 25118,
"text": null
},
{
"code": null,
"e": 25618,
"s": 25610,
"text": "Output:"
},
{
"code": null,
"e": 25652,
"s": 25618,
"text": "3 6 9 12 15 18 21 24 27 30 33 36 "
},
{
"code": null,
"e": 25692,
"s": 25652,
"text": "Case 2: Break keyword inside WHILE loop"
},
{
"code": null,
"e": 25942,
"s": 25692,
"text": "In order to show how to use the break keyword within the While loop. Considering when the value of ‘i’ becomes 15, the break keyword plays its role and terminate the for a loop. All values of ‘i’ greater than 15 till 35, are displayed in the result."
},
{
"code": null,
"e": 25947,
"s": 25942,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of break statement// inside the While loop // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // While loop for iteration // Creating and initializing variable // outside loop int i = 35; // Condition check while (i >= 10) { if (i == 15) { // Using Break keyword to suspend // loop when i become 15 // Decrementing variable initialized above i--; // Break statement break; } // Printing elements showcasing break System.out.print(i + \" \"); i--; } }}",
"e": 26732,
"s": 25947,
"text": null
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Output:"
},
{
"code": null,
"e": 26801,
"s": 26740,
"text": "35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 "
},
{
"code": null,
"e": 26844,
"s": 26801,
"text": "Case 3: Break keyword inside DO-WHILE loop"
},
{
"code": null,
"e": 27082,
"s": 26844,
"text": "In order to show how to use the break keyword within the Do-while loop. Considering when the value of ‘i’ becomes 80, the break keyword plays its role and terminate the for a loop. All values of i” before 80, are displayed in the result."
},
{
"code": null,
"e": 27087,
"s": 27082,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of break statement// Inside the do-While loop // Importing all generic classesimport java.util.*; // Importing specific class to take// user input from the userimport java.util.Scanner; public class GFG { // Main driver method public static void main(String[] args) { // Using do-While loop // Creating and initializing a variable // over which execution occurs int i = 0; // do loop consisting of executable statements do { if (i == 80) { // Incrementing variable by 5 i += 5; // Using Break keyword to // suspend loop when i become 80 break; } System.out.print(i + \" \"); // Printing elements to show break usage i += 5; } // Condition check while (i <= 100); }}",
"e": 28037,
"s": 27087,
"text": null
},
{
"code": null,
"e": 28045,
"s": 28037,
"text": "Output:"
},
{
"code": null,
"e": 28106,
"s": 28045,
"text": "0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75"
},
{
"code": null,
"e": 28156,
"s": 28106,
"text": "Case 4: Break keyword inside the Switch statement"
},
{
"code": null,
"e": 28367,
"s": 28156,
"text": "In order to show how to use the break keyword within For loop. The break keyword is used at the bottom of every switch case to terminate each statement sequence and prevent the mixing of switch-case statements."
},
{
"code": null,
"e": 28372,
"s": 28367,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of break statement// inside the Switch Statement // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Declaring a variable for switch expression int numb = 20; // Switch expression switch (numb) { // Case statements case 10: System.out.println(\"TEN\"); // Break keyword to suspend the switch case // if given condition is fulfilled break; case 20: System.out.println(\"TWENTY\"); break; case 30: System.out.println(\"THIRTY\"); break; // Default case statement default: System.out.println(\"INFINITE\"); } }}",
"e": 29197,
"s": 28372,
"text": null
},
{
"code": null,
"e": 29205,
"s": 29197,
"text": "Output:"
},
{
"code": null,
"e": 29212,
"s": 29205,
"text": "TWENTY"
},
{
"code": null,
"e": 29228,
"s": 29212,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29237,
"s": 29228,
"text": "sooda367"
},
{
"code": null,
"e": 29250,
"s": 29237,
"text": "singghakshay"
},
{
"code": null,
"e": 29263,
"s": 29250,
"text": "Java-keyword"
},
{
"code": null,
"e": 29268,
"s": 29263,
"text": "Java"
},
{
"code": null,
"e": 29273,
"s": 29268,
"text": "Java"
},
{
"code": null,
"e": 29371,
"s": 29273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29380,
"s": 29371,
"text": "Comments"
},
{
"code": null,
"e": 29393,
"s": 29380,
"text": "Old Comments"
},
{
"code": null,
"e": 29423,
"s": 29393,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29438,
"s": 29423,
"text": "Stream In Java"
},
{
"code": null,
"e": 29459,
"s": 29438,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29505,
"s": 29459,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29524,
"s": 29505,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29541,
"s": 29524,
"text": "Generics in Java"
},
{
"code": null,
"e": 29584,
"s": 29541,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29600,
"s": 29584,
"text": "Strings in Java"
},
{
"code": null,
"e": 29656,
"s": 29600,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Get object at the top of the Stack in C#
|
To get object at the top of the Stack, the code is as follows −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
stack.Push("C");
stack.Push("D");
stack.Push("E");
stack.Push("F");
stack.Push("G");
stack.Push("H");
stack.Push("I");
stack.Push("J");
Console.WriteLine("Count of elements = "+stack.Count);
Console.WriteLine("Element at the top of stack = " + stack.Peek());
}
}
This will produce the following output −
Count of elements = 10
Element at the top of stack = J
Count of elements = 10
Let us see another example −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
stack.Push(60);
stack.Push(70);
stack.Push(80);
stack.Push(90);
stack.Push(100);
Console.WriteLine("Count of elements = "+stack.Count);
Console.WriteLine("Element at the top of stack = " + stack.Peek());
Console.WriteLine("Element at the top of stack = " + stack.Peek());
}
}
This will produce the following output −
Count of elements = 10
Element at the top of stack = 100
Element at the top of stack = 100
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To get object at the top of the Stack, the code is as follows −"
},
{
"code": null,
"e": 1137,
"s": 1126,
"text": " Live Demo"
},
{
"code": null,
"e": 1657,
"s": 1137,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n Stack<string> stack = new Stack<string>();\n stack.Push(\"A\");\n stack.Push(\"B\");\n stack.Push(\"C\");\n stack.Push(\"D\");\n stack.Push(\"E\");\n stack.Push(\"F\");\n stack.Push(\"G\");\n stack.Push(\"H\");\n stack.Push(\"I\");\n stack.Push(\"J\");\n Console.WriteLine(\"Count of elements = \"+stack.Count);\n Console.WriteLine(\"Element at the top of stack = \" + stack.Peek());\n }\n}"
},
{
"code": null,
"e": 1698,
"s": 1657,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1777,
"s": 1698,
"text": "Count of elements = 10\nElement at the top of stack = J\n\nCount of elements = 10"
},
{
"code": null,
"e": 1806,
"s": 1777,
"text": "Let us see another example −"
},
{
"code": null,
"e": 1817,
"s": 1806,
"text": " Live Demo"
},
{
"code": null,
"e": 2396,
"s": 1817,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n Stack<int> stack = new Stack<int>();\n stack.Push(10);\n stack.Push(20);\n stack.Push(30);\n stack.Push(40);\n stack.Push(50);\n stack.Push(60);\n stack.Push(70);\n stack.Push(80);\n stack.Push(90);\n stack.Push(100);\n Console.WriteLine(\"Count of elements = \"+stack.Count);\n Console.WriteLine(\"Element at the top of stack = \" + stack.Peek());\n Console.WriteLine(\"Element at the top of stack = \" + stack.Peek());\n }\n}"
},
{
"code": null,
"e": 2437,
"s": 2396,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2528,
"s": 2437,
"text": "Count of elements = 10\nElement at the top of stack = 100\nElement at the top of stack = 100"
}
] |
Logstash - Collecting Logs
|
Logs from different servers or data sources are collected using shippers. A shipper is an instance of Logstash installed in the server, which accesses the server logs and sends to specific output location.
It mainly sends the output to the Elasticsearch for storage. Logstash takes input from the following sources −
STDIN
Syslog
Files
TCP/UDP
Microsoft windows Eventlogs
Websocket
Zeromq
Customized extensions
In this example, we are collecting logs of Apache Tomcat 7 Server installed in windows using the file input plugin and sending them to the other log.
Here, Logstash is configured to access the access log of Apache Tomcat 7 installed locally. A regex pattern is used in path setting of the file plugin to get the data from the log file. This contains “access” in its name and it adds an apache type, which helps in differentiating the apache events from the other in a centralized destination source. Finally, the output events will be shown in the output.log.
input {
file {
path => "C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/*access*"
type => "apache"
}
}
output {
file {
path => "C:/tpwork/logstash/bin/log/output.log"
}
}
We can run Logstash by using the following command.
C:\logstash\bin> logstash –f Logstash.conf
Access the Apache Tomcat Server and its web apps (http://localhost:8080) to generate logs. The updated data in the logs are read by Logstash in real time and stashed in output.log as specified in configuration file.
Apache Tomcat generates a new access log file according to date and logs the access events there. In our case, it was localhost_access_log.2016-12-24.txt in the logs directory of Apache Tomcat.
0:0:0:0:0:0:0:1 - - [
25/Dec/2016:18:37:00 +0800] "GET / HTTP/1.1" 200 11418
0:0:0:0:0:0:0:1 - munish [
25/Dec/2016:18:37:02 +0800] "GET /manager/html HTTP/1.1" 200 17472
0:0:0:0:0:0:0:1 - - [
25/Dec/2016:18:37:08 +0800] "GET /docs/ HTTP/1.1" 200 19373
0:0:0:0:0:0:0:1 - - [
25/Dec/2016:18:37:10 +0800] "GET /docs/introduction.html HTTP/1.1" 200 15399
You can see in the output events, a type field is added and the event is present in the message field.
{
"path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
localhost_access_log.2016-12-25.txt",
"@timestamp":"2016-12-25T10:37:00.363Z","@version":"1","host":"Dell-PC",
"message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:00 +0800] \"GET /
HTTP/1.1\" 200 11418\r","type":"apache","tags":[]
}
{
"path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:10.407Z",
"@version":"1","host":"Dell-PC",
"message":"0:0:0:0:0:0:0:1 - munish [25/Dec/2016:18:37:02 +0800] \"GET /
manager/html HTTP/1.1\" 200 17472\r","type":"apache","tags":[]
}
{
"path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:10.407Z",
"@version":"1","host":"Dell-PC",
"message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:08 +0800] \"GET /docs/
HTTP/1.1\" 200 19373\r","type":"apache","tags":[]
}
{
"path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:20.436Z",
"@version":"1","host":"Dell-PC",
"message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:10 +0800] \"GET /docs/
introduction.html HTTP/1.1\" 200 15399\r","type":"apache","tags":[]
}
In this section, we will discuss another example of collecting logs using the STDIN Plugin.
It is a very simple example, where Logstash is reading the events entered by the user in a standard input. In our case, it is the command prompt, which stores the events in the output.log file.
input {
stdin{}
}
output {
file {
path => "C:/tpwork/logstash/bin/log/output.log"
}
}
We can run Logstash by using the following command.
C:\logstash\bin> logstash –f Logstash.conf
Write the following text in the command prompt −
The user entered the following two lines. Logstash separates the events by the delimiter setting and its value by default is ‘\n’. The user can change by changing the value of the delimiter in the file plugin.
Tutorialspoint.com welcomes you
Simply easy learning
The following code block shows the output log data.
{
"@timestamp":"2016-12-25T11:41:16.518Z","@version":"1","host":"Dell-PC",
"message":"tutrialspoint.com welcomes you\r","tags":[]
}
{
"@timestamp":"2016-12-25T11:41:53.396Z","@version":"1","host":"Dell-PC",
"message":"simply easy learning\r","tags":[]
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2261,
"s": 2055,
"text": "Logs from different servers or data sources are collected using shippers. A shipper is an instance of Logstash installed in the server, which accesses the server logs and sends to specific output location."
},
{
"code": null,
"e": 2372,
"s": 2261,
"text": "It mainly sends the output to the Elasticsearch for storage. Logstash takes input from the following sources −"
},
{
"code": null,
"e": 2378,
"s": 2372,
"text": "STDIN"
},
{
"code": null,
"e": 2385,
"s": 2378,
"text": "Syslog"
},
{
"code": null,
"e": 2391,
"s": 2385,
"text": "Files"
},
{
"code": null,
"e": 2399,
"s": 2391,
"text": "TCP/UDP"
},
{
"code": null,
"e": 2427,
"s": 2399,
"text": "Microsoft windows Eventlogs"
},
{
"code": null,
"e": 2437,
"s": 2427,
"text": "Websocket"
},
{
"code": null,
"e": 2444,
"s": 2437,
"text": "Zeromq"
},
{
"code": null,
"e": 2466,
"s": 2444,
"text": "Customized extensions"
},
{
"code": null,
"e": 2616,
"s": 2466,
"text": "In this example, we are collecting logs of Apache Tomcat 7 Server installed in windows using the file input plugin and sending them to the other log."
},
{
"code": null,
"e": 3026,
"s": 2616,
"text": "Here, Logstash is configured to access the access log of Apache Tomcat 7 installed locally. A regex pattern is used in path setting of the file plugin to get the data from the log file. This contains “access” in its name and it adds an apache type, which helps in differentiating the apache events from the other in a centralized destination source. Finally, the output events will be shown in the output.log."
},
{
"code": null,
"e": 3240,
"s": 3026,
"text": "input {\n file {\n path => \"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/*access*\"\n type => \"apache\"\n }\n} \noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\"\n }\n}"
},
{
"code": null,
"e": 3292,
"s": 3240,
"text": "We can run Logstash by using the following command."
},
{
"code": null,
"e": 3337,
"s": 3292,
"text": "C:\\logstash\\bin> logstash –f Logstash.conf\n"
},
{
"code": null,
"e": 3553,
"s": 3337,
"text": "Access the Apache Tomcat Server and its web apps (http://localhost:8080) to generate logs. The updated data in the logs are read by Logstash in real time and stashed in output.log as specified in configuration file."
},
{
"code": null,
"e": 3747,
"s": 3553,
"text": "Apache Tomcat generates a new access log file according to date and logs the access events there. In our case, it was localhost_access_log.2016-12-24.txt in the logs directory of Apache Tomcat."
},
{
"code": null,
"e": 4112,
"s": 3747,
"text": "0:0:0:0:0:0:0:1 - - [\n 25/Dec/2016:18:37:00 +0800] \"GET / HTTP/1.1\" 200 11418\n0:0:0:0:0:0:0:1 - munish [\n 25/Dec/2016:18:37:02 +0800] \"GET /manager/html HTTP/1.1\" 200 17472\n0:0:0:0:0:0:0:1 - - [\n 25/Dec/2016:18:37:08 +0800] \"GET /docs/ HTTP/1.1\" 200 19373\n0:0:0:0:0:0:0:1 - - [\n 25/Dec/2016:18:37:10 +0800] \"GET /docs/introduction.html HTTP/1.1\" 200 15399\n"
},
{
"code": null,
"e": 4215,
"s": 4112,
"text": "You can see in the output events, a type field is added and the event is present in the message field."
},
{
"code": null,
"e": 5529,
"s": 4215,
"text": "{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n localhost_access_log.2016-12-25.txt\",\n \"@timestamp\":\"2016-12-25T10:37:00.363Z\",\"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:00 +0800] \\\"GET /\n HTTP/1.1\\\" 200 11418\\r\",\"type\":\"apache\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n localhost_access_log.2016-12-25.txt\",\"@timestamp\":\"2016-12-25T10:37:10.407Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"0:0:0:0:0:0:0:1 - munish [25/Dec/2016:18:37:02 +0800] \\\"GET /\n manager/html HTTP/1.1\\\" 200 17472\\r\",\"type\":\"apache\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n localhost_access_log.2016-12-25.txt\",\"@timestamp\":\"2016-12-25T10:37:10.407Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:08 +0800] \\\"GET /docs/\n HTTP/1.1\\\" 200 19373\\r\",\"type\":\"apache\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n localhost_access_log.2016-12-25.txt\",\"@timestamp\":\"2016-12-25T10:37:20.436Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:10 +0800] \\\"GET /docs/\n introduction.html HTTP/1.1\\\" 200 15399\\r\",\"type\":\"apache\",\"tags\":[]\n}"
},
{
"code": null,
"e": 5621,
"s": 5529,
"text": "In this section, we will discuss another example of collecting logs using the STDIN Plugin."
},
{
"code": null,
"e": 5815,
"s": 5621,
"text": "It is a very simple example, where Logstash is reading the events entered by the user in a standard input. In our case, it is the command prompt, which stores the events in the output.log file."
},
{
"code": null,
"e": 5916,
"s": 5815,
"text": "input {\n stdin{}\n}\noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\"\n }\n}"
},
{
"code": null,
"e": 5968,
"s": 5916,
"text": "We can run Logstash by using the following command."
},
{
"code": null,
"e": 6013,
"s": 5968,
"text": "C:\\logstash\\bin> logstash –f Logstash.conf\n"
},
{
"code": null,
"e": 6062,
"s": 6013,
"text": "Write the following text in the command prompt −"
},
{
"code": null,
"e": 6272,
"s": 6062,
"text": "The user entered the following two lines. Logstash separates the events by the delimiter setting and its value by default is ‘\\n’. The user can change by changing the value of the delimiter in the file plugin."
},
{
"code": null,
"e": 6326,
"s": 6272,
"text": "Tutorialspoint.com welcomes you\nSimply easy learning\n"
},
{
"code": null,
"e": 6378,
"s": 6326,
"text": "The following code block shows the output log data."
},
{
"code": null,
"e": 6644,
"s": 6378,
"text": "{\n \"@timestamp\":\"2016-12-25T11:41:16.518Z\",\"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"tutrialspoint.com welcomes you\\r\",\"tags\":[]\n}\n{\n \"@timestamp\":\"2016-12-25T11:41:53.396Z\",\"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"simply easy learning\\r\",\"tags\":[]\n}"
},
{
"code": null,
"e": 6651,
"s": 6644,
"text": " Print"
},
{
"code": null,
"e": 6662,
"s": 6651,
"text": " Add Notes"
}
] |
HTML - Comments
|
Comment is a piece of code which is ignored by any web browser. It is a good practice to add comments into your HTML code, especially in complex documents, to indicate sections of a document, and any other notes to anyone looking at the code. Comments help you and others understand your code and increases code readability.
HTML comments are placed in between <!-- ... --> tags. So, any content placed with-in <!-- ... --> tags will be treated as comment and will be completely ignored by the browser.
<!DOCTYPE html>
<html>
<head> <!-- Document Header Starts -->
<title>This is document title</title>
</head> <!-- Document Header Ends -->
<body>
<p>Document content goes here.....</p>
</body>
</html>
This will produce the following result without displaying the content given as a part of comments −
Document content goes here.....
Comments do not nest which means a comment cannot be put inside another comment. Second the double-dash sequence "--" may not appear inside a comment except as part of the closing --> tag. You must also make sure that there are no spaces in the start-of comment string.
Here, the given comment is a valid comment and will be wiped off by the browser.
<!DOCTYPE html>
<html>
<head>
<title>Valid Comment Example</title>
</head>
<body>
<!-- This is valid comment -->
<p>Document content goes here.....</p>
</body>
</html>
This will produce the following result −
Document content goes here.....
But, following line is not a valid comment and will be displayed by the browser. This is because there is a space between the left angle bracket and the exclamation mark.
<!DOCTYPE html>
<html>
<head>
<title>Invalid Comment Example</title>
</head>
<body>
< !-- This is not a valid comment -->
<p>Document content goes here.....</p>
</body>
</html>
This will produce the following result −
Document content goes here.....
So far we have seen single line comments, but HTML supports multi-line comments as well.
You can comment multiple lines by the special beginning tag <!-- and ending tag --> placed before the first line and end of the last line as shown in the given example below.
<!DOCTYPE html>
<html>
<head>
<title>Multiline Comments</title>
</head>
<body>
<!--
This is a multiline comment and it can
span through as many as lines you like.
-->
<p>Document content goes here.....</p>
</body>
</html>
This will produce the following result −
Document content goes here.....
Conditional comments only work in Internet Explorer (IE) on Windows but they are ignored by other browsers. They are supported from Explorer 5 onwards, and you can use them to give conditional instructions to different versions of IE.
<!DOCTYPE html>
<html>
<head>
<title>Conditional Comments</title>
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
</head>
<body>
<p>Document content goes here.....</p>
</body>
</html>
You will come across a situation where you will need to apply a different style sheet based on different versions of Internet Explorer, in such situation conditional comments will be helpful.
There are few browsers that support <comment> tag to comment a part of HTML code.
Note − The <comment> tag deprecated in HTML5. Do not use this element.
<!DOCTYPE html>
<html>
<head>
<title>Using Comment Tag</title>
</head>
<body>
<p>This is <comment>not</comment> Internet Explorer.</p>
</body>
</html>
If you are using IE, then it will produce following result −
This is Internet Explorer.
But if you are not using IE, then it will produce following result −
This is not Internet Explorer.
Though you will learn JavaScript with HTML, in a separate tutorial, but here you must make a note that if you are using Java Script or VB Script in your HTML code then it is recommended to put that script code inside proper HTML comments so that old browsers can work properly.
<!DOCTYPE html>
<html>
<head>
<title>Commenting Script Code</title>
<script>
<!--
document.write("Hello World!")
//-->
</script>
</head>
<body>
<p>Hello , World!</p>
</body>
</html>
This will produce the following result −
Hello , World!
Though you will learn using style sheets with HTML in a separate tutorial, but here you must make a note that if you are using Cascading Style Sheet (CSS) in your HTML code then it is recommended to put that style sheet code inside proper HTML comments so that old browsers can work properly.
<!DOCTYPE html>
<html>
<head>
<title>Commenting Style Sheets</title>
<style>
<!--
.example {
border:1px solid #4a7d49;
}
//-->
</style>
</head>
<body>
<div class = "example">Hello , World!</div>
</body>
</html>
This will produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2699,
"s": 2374,
"text": "Comment is a piece of code which is ignored by any web browser. It is a good practice to add comments into your HTML code, especially in complex documents, to indicate sections of a document, and any other notes to anyone looking at the code. Comments help you and others understand your code and increases code readability."
},
{
"code": null,
"e": 2877,
"s": 2699,
"text": "HTML comments are placed in between <!-- ... --> tags. So, any content placed with-in <!-- ... --> tags will be treated as comment and will be completely ignored by the browser."
},
{
"code": null,
"e": 3107,
"s": 2877,
"text": "<!DOCTYPE html>\n<html>\n\n <head> <!-- Document Header Starts -->\n <title>This is document title</title>\n </head> <!-- Document Header Ends -->\n\t\n <body>\n <p>Document content goes here.....</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3207,
"s": 3107,
"text": "This will produce the following result without displaying the content given as a part of comments −"
},
{
"code": null,
"e": 3239,
"s": 3207,
"text": "Document content goes here....."
},
{
"code": null,
"e": 3509,
"s": 3239,
"text": "Comments do not nest which means a comment cannot be put inside another comment. Second the double-dash sequence \"--\" may not appear inside a comment except as part of the closing --> tag. You must also make sure that there are no spaces in the start-of comment string."
},
{
"code": null,
"e": 3590,
"s": 3509,
"text": "Here, the given comment is a valid comment and will be wiped off by the browser."
},
{
"code": null,
"e": 3795,
"s": 3590,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Valid Comment Example</title>\n </head>\n\t\n <body>\n <!-- This is valid comment -->\n <p>Document content goes here.....</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3836,
"s": 3795,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3868,
"s": 3836,
"text": "Document content goes here....."
},
{
"code": null,
"e": 4039,
"s": 3868,
"text": "But, following line is not a valid comment and will be displayed by the browser. This is because there is a space between the left angle bracket and the exclamation mark."
},
{
"code": null,
"e": 4255,
"s": 4039,
"text": "<!DOCTYPE html>\n<html>\n\n <head> \n <title>Invalid Comment Example</title>\n </head>\n\t\n <body>\n < !-- This is not a valid comment -->\n <p>Document content goes here.....</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4296,
"s": 4255,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4328,
"s": 4296,
"text": "Document content goes here....."
},
{
"code": null,
"e": 4417,
"s": 4328,
"text": "So far we have seen single line comments, but HTML supports multi-line comments as well."
},
{
"code": null,
"e": 4592,
"s": 4417,
"text": "You can comment multiple lines by the special beginning tag <!-- and ending tag --> placed before the first line and end of the last line as shown in the given example below."
},
{
"code": null,
"e": 4884,
"s": 4592,
"text": "<!DOCTYPE html>\n<html>\n\n <head> \n <title>Multiline Comments</title>\n </head> \n\t\n <body>\n <!-- \n This is a multiline comment and it can\n span through as many as lines you like.\n -->\n \n <p>Document content goes here.....</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4925,
"s": 4884,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4957,
"s": 4925,
"text": "Document content goes here....."
},
{
"code": null,
"e": 5192,
"s": 4957,
"text": "Conditional comments only work in Internet Explorer (IE) on Windows but they are ignored by other browsers. They are supported from Explorer 5 onwards, and you can use them to give conditional instructions to different versions of IE."
},
{
"code": null,
"e": 5447,
"s": 5192,
"text": "<!DOCTYPE html>\n<html>\n\n <head> \n <title>Conditional Comments</title>\n\n <!--[if IE 6]>\n Special instructions for IE 6 here\n <![endif]-->\n </head> \n \n <body>\n <p>Document content goes here.....</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 5639,
"s": 5447,
"text": "You will come across a situation where you will need to apply a different style sheet based on different versions of Internet Explorer, in such situation conditional comments will be helpful."
},
{
"code": null,
"e": 5721,
"s": 5639,
"text": "There are few browsers that support <comment> tag to comment a part of HTML code."
},
{
"code": null,
"e": 5792,
"s": 5721,
"text": "Note − The <comment> tag deprecated in HTML5. Do not use this element."
},
{
"code": null,
"e": 5972,
"s": 5792,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Using Comment Tag</title>\n </head>\n\t\n <body>\n <p>This is <comment>not</comment> Internet Explorer.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6033,
"s": 5972,
"text": "If you are using IE, then it will produce following result −"
},
{
"code": null,
"e": 6060,
"s": 6033,
"text": "This is Internet Explorer."
},
{
"code": null,
"e": 6129,
"s": 6060,
"text": "But if you are not using IE, then it will produce following result −"
},
{
"code": null,
"e": 6160,
"s": 6129,
"text": "This is not Internet Explorer."
},
{
"code": null,
"e": 6438,
"s": 6160,
"text": "Though you will learn JavaScript with HTML, in a separate tutorial, but here you must make a note that if you are using Java Script or VB Script in your HTML code then it is recommended to put that script code inside proper HTML comments so that old browsers can work properly."
},
{
"code": null,
"e": 6699,
"s": 6438,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Commenting Script Code</title>\n \n <script>\n <!-- \n document.write(\"Hello World!\")\n //-->\n </script>\n </head>\n\t\n <body>\n <p>Hello , World!</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6740,
"s": 6699,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6755,
"s": 6740,
"text": "Hello , World!"
},
{
"code": null,
"e": 7048,
"s": 6755,
"text": "Though you will learn using style sheets with HTML in a separate tutorial, but here you must make a note that if you are using Cascading Style Sheet (CSS) in your HTML code then it is recommended to put that style sheet code inside proper HTML comments so that old browsers can work properly."
},
{
"code": null,
"e": 7364,
"s": 7048,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Commenting Style Sheets</title>\n \n <style>\n <!--\n .example {\n border:1px solid #4a7d49;\n }\n //-->\n </style>\n </head>\n\t\n <body>\n <div class = \"example\">Hello , World!</div>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 7405,
"s": 7364,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7438,
"s": 7405,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7452,
"s": 7438,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7487,
"s": 7452,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7501,
"s": 7487,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7536,
"s": 7501,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7553,
"s": 7536,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7588,
"s": 7553,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7619,
"s": 7588,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7652,
"s": 7619,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7683,
"s": 7652,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7718,
"s": 7683,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7749,
"s": 7718,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7756,
"s": 7749,
"text": " Print"
},
{
"code": null,
"e": 7767,
"s": 7756,
"text": " Add Notes"
}
] |
Multiple Stack
|
Theory of Computation
A single stack is sometimes not sufficient to store a large amount of data. To overcome this problem, we can use multiple stack.
For this, we have used a single array having more than one stack. The array is divided for multiple stacks.
Suppose there is an array STACK[n] divided into two stack STACK A and STACK B,
where n = 10.
STACK A expands from the left to the right, i.e., from 0th element.
STACK B expands from the right to the left, i.e., from 10th element.
The combined size of both STACK A and STACK B never exceeds 10.
The following program demonstrates Multiple Stack -
#include <stdio.h>
#include <malloc.h>
#define MAX 10
int stack[MAX], topA = -1, topB = MAX;
void push_stackA(int val)
{
if(topA == topB-1)
printf("\n STACK OVERFLOW");
else
{
topA+=1;
stack[topA] = val;
}
}
int pop_stackA()
{
int val;
if(topA == -1)
{
printf("\n STACK UNDERFLOW");
}
else
{
val = stack[topA];
topA--;
}
return val;
}
void display_stackA()
{
int i;
if(topA == -1)
printf("\n Empty STACK A");
else
{
for(i = topA;i >= 0;i--)
printf("\t %d",stack[i]);
}
}
void push_stackB(int val)
{
if(topB-1 == topA)
printf("\n STACK OVERFLOW");
else
{
topB-=1;
stack[topB] = val;
}
}
int pop_stackB()
{
int val;
if(topB == MAX)
{
printf("\n STACK UNDERFLOW");
}
else
{
val = stack[topB];
topB++;
}
}
void display_stackB()
{
int i;
if(topB == MAX)
printf("\n Empty STACK B");
else
{
for(i = topB; i < MAX;i++)
printf("\t %d",stack[i]);
}
}
int main()
{
int option, val;
do
{
printf("\n -----Menu----- ");
printf("\n Enter 1 to PUSH a element into STACK A");
printf("\n Enter 2 to PUSH a element into STACK B");
printf("\n Enter 3 to POP a element from STACK A");
printf("\n Enter 4 to POP a element from STACK B");
printf("\n Enter 5 to display the STACK A");
printf("\n Enter 6 to display the STACK B");
printf("\n Press 7 to exit");
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
printf("\n Enter a value to PUSH on STACK A :");
scanf("%d",&val);
push_stackA(val);
break;
case 2:
printf("\n Enter the value to PUSH on STACK B:");
scanf("%d", &val);
push_stackB(val);
break;
case 3:
printf("\n The value POPPED from STACK A = %d", val);
pop_stackA();
break;
case 4:
printf("\n The value POPPED from STACK B = %d", val);
pop_stackB();
break;
case 5:
printf("\n The STACK A elements are :\n");
display_stackA();
break;
case 6:
printf("\n The STACK B elements are :\n");
display_stackB();
break;
}
}while(option != 7);
return 0;
}
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 1
Enter a value to PUSH on STACK A :10
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 1
Enter a value to PUSH on STACK A :30
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 1
Enter a value to PUSH on STACK A :20
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 5
The STACK A elements are :
20 30 10
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 3
The value POPPED from STACK A = 20
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 5
The STACK A elements are :
30 10
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 2
Enter the value to PUSH on STACK B:23
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 2
Enter the value to PUSH on STACK B:23
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 6
The STACK B elements are :
24 23
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice: 4
The value POPPED from STACK B = 24
-----Menu-----
Enter 1 to PUSH a element into STACK A
Enter 2 to PUSH a element into STACK B
Enter 3 to POP a element from STACK A
Enter 4 to POP a element from STACK B
Enter 5 to display the STACK A
Enter 6 to display the STACK B
Press 7 to exit
Enter your choice:
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 351,
"s": 112,
"text": "A single stack is sometimes not sufficient to store a large amount of data. To overcome this problem, we can use multiple stack. \n For this, we have used a single array having more than one stack. The array is divided for multiple stacks."
},
{
"code": null,
"e": 445,
"s": 351,
"text": "Suppose there is an array STACK[n] divided into two stack STACK A and STACK B,\n where n = 10."
},
{
"code": null,
"e": 513,
"s": 445,
"text": "STACK A expands from the left to the right, i.e., from 0th element."
},
{
"code": null,
"e": 582,
"s": 513,
"text": "STACK B expands from the right to the left, i.e., from 10th element."
},
{
"code": null,
"e": 646,
"s": 582,
"text": "The combined size of both STACK A and STACK B never exceeds 10."
},
{
"code": null,
"e": 698,
"s": 646,
"text": "The following program demonstrates Multiple Stack -"
},
{
"code": null,
"e": 2561,
"s": 698,
"text": "#include <stdio.h>\n#include <malloc.h>\n#define MAX 10\nint stack[MAX], topA = -1, topB = MAX;\nvoid push_stackA(int val)\n{\nif(topA == topB-1)\nprintf(\"\\n STACK OVERFLOW\");\nelse\n{\ntopA+=1;\nstack[topA] = val;\n}\n}\nint pop_stackA()\n{\nint val;\nif(topA == -1)\n{\nprintf(\"\\n STACK UNDERFLOW\");\n}\nelse\n{\nval = stack[topA];\ntopA--;\n}\nreturn val;\n}\nvoid display_stackA()\n{\nint i;\nif(topA == -1)\nprintf(\"\\n Empty STACK A\");\nelse\n{\nfor(i = topA;i >= 0;i--)\nprintf(\"\\t %d\",stack[i]);\n}\n}\nvoid push_stackB(int val)\n{\nif(topB-1 == topA)\nprintf(\"\\n STACK OVERFLOW\");\nelse\n{\ntopB-=1;\nstack[topB] = val;\n}\n}\nint pop_stackB()\n{\nint val;\nif(topB == MAX)\n{\nprintf(\"\\n STACK UNDERFLOW\");\n}\nelse\n{\nval = stack[topB];\ntopB++;\n}\n}\nvoid display_stackB()\n{\nint i;\nif(topB == MAX)\nprintf(\"\\n Empty STACK B\");\nelse\n{\nfor(i = topB; i < MAX;i++)\nprintf(\"\\t %d\",stack[i]);\n}\n}\nint main()\n{\nint option, val;\ndo\n{\nprintf(\"\\n -----Menu----- \");\nprintf(\"\\n Enter 1 to PUSH a element into STACK A\");\nprintf(\"\\n Enter 2 to PUSH a element into STACK B\");\nprintf(\"\\n Enter 3 to POP a element from STACK A\");\nprintf(\"\\n Enter 4 to POP a element from STACK B\");\nprintf(\"\\n Enter 5 to display the STACK A\");\nprintf(\"\\n Enter 6 to display the STACK B\");\nprintf(\"\\n Press 7 to exit\");\nprintf(\"\\n Enter your choice: \");\nscanf(\"%d\",&option);\nswitch(option)\n{\ncase 1:\nprintf(\"\\n Enter a value to PUSH on STACK A :\");\nscanf(\"%d\",&val);\npush_stackA(val);\nbreak;\ncase 2:\nprintf(\"\\n Enter the value to PUSH on STACK B:\");\nscanf(\"%d\", &val);\npush_stackB(val);\nbreak;\ncase 3:\nprintf(\"\\n The value POPPED from STACK A = %d\", val);\npop_stackA();\nbreak;\ncase 4:\nprintf(\"\\n The value POPPED from STACK B = %d\", val);\npop_stackB();\nbreak;\ncase 5:\nprintf(\"\\n The STACK A elements are :\\n\");\ndisplay_stackA();\nbreak;\ncase 6:\nprintf(\"\\n The STACK B elements are :\\n\");\ndisplay_stackB();\nbreak;\n}\n}while(option != 7);\nreturn 0;\n}"
}
] |
Maximum width of a binary tree in C++
|
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum of widths of all levels.
Consider below tree −
10
/ \
7 4
/ \ \
9 2 1
/ \
2 5
1. Width at level 1: 1
2. Width at level 2: 2
3. Width at level 3: 3
4. Width at level 4: 2
For above tree answer is 3.
1. Use level order traversal to find the answer
#include <bits/stdc++.h>
using namespace std;
struct node {
public:
int data;
node* left;
node* right;
};
int getWidth(node* root, int level);
int height(node* node);
node* newNode(int data);
int getMaxWidth(node* root){
int maxWidth = 0;
int width;
int h = height(root);
int i;
for (i = 1; i <= h; ++i) {
width = getWidth(root, i);
if (width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
int getWidth(node* root, int level){
if (root == NULL) {
return 0;
}
if (level == 1) {
return 1;
}
else if (level > 1) {
return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);
}
}
int height(node* node){
if (node == NULL) {
return 0;
}
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight)? (lHeight + 1): (rHeight + 1);
}
node* newNode(int data){
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
int main(){
node *root = newNode(10);
root->left = newNode(7);
root->right = newNode(4);
root->left->left = newNode(9);
root->left->right = newNode(2);
root->right->right = newNode(1);
root->right->right->left = newNode(2);
root->right->right->right = newNode(5);
cout<<"Maximum width = " << getMaxWidth(root) << endl;
return 0;
}
When you compile and execute the above program. It generates the following output −
Maximum width = 3
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum of widths of all levels."
},
{
"code": null,
"e": 1226,
"s": 1204,
"text": "Consider below tree −"
},
{
"code": null,
"e": 1424,
"s": 1226,
"text": " 10\n / \\\n 7 4\n / \\ \\\n 9 2 1\n / \\\n 2 5\n1. Width at level 1: 1\n2. Width at level 2: 2\n3. Width at level 3: 3\n4. Width at level 4: 2\nFor above tree answer is 3."
},
{
"code": null,
"e": 1472,
"s": 1424,
"text": "1. Use level order traversal to find the answer"
},
{
"code": null,
"e": 2881,
"s": 1472,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct node {\n public:\n int data;\n node* left;\n node* right;\n};\nint getWidth(node* root, int level);\nint height(node* node);\nnode* newNode(int data);\nint getMaxWidth(node* root){\n int maxWidth = 0;\n int width;\n int h = height(root);\n int i;\n for (i = 1; i <= h; ++i) {\n width = getWidth(root, i);\n if (width > maxWidth) {\n maxWidth = width;\n }\n }\n return maxWidth;\n}\nint getWidth(node* root, int level){\n if (root == NULL) {\n return 0;\n }\n if (level == 1) {\n return 1;\n }\n else if (level > 1) {\n return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);\n }\n}\nint height(node* node){\n if (node == NULL) {\n return 0;\n }\n int lHeight = height(node->left);\n int rHeight = height(node->right);\n return (lHeight > rHeight)? (lHeight + 1): (rHeight + 1);\n}\nnode* newNode(int data){\n node* Node = new node();\n Node->data = data;\n Node->left = NULL;\n Node->right = NULL;\n return(Node);\n}\nint main(){\n node *root = newNode(10);\n root->left = newNode(7);\n root->right = newNode(4);\n root->left->left = newNode(9);\n root->left->right = newNode(2);\n root->right->right = newNode(1);\n root->right->right->left = newNode(2);\n root->right->right->right = newNode(5);\n cout<<\"Maximum width = \" << getMaxWidth(root) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2965,
"s": 2881,
"text": "When you compile and execute the above program. It generates the following output −"
},
{
"code": null,
"e": 2983,
"s": 2965,
"text": "Maximum width = 3"
}
] |
JavaFX - 2D Shapes Types of Arc
|
In JavaFX, you can draw three kinds of arc’s namely −
Open − An arc which is not closed at all is known as an open arc.
Open − An arc which is not closed at all is known as an open arc.
Chord − A chord is a type of an arc which is closed by straight line.
Chord − A chord is a type of an arc which is closed by straight line.
Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse.
Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse.
You can set the type of the arc using the method setType() by passing any of the following properties − ArcType.OPEN, ArcType.CHORD, ArcType.Round.
To Draw an arc in JavaFX, follow the steps given below.
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class ClassName extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
You can create an arc in JavaFX by instantiating the class named Arc which belongs to a package javafx.scene.shape. You can instantiate this class as shown below.
//Creating an object of the class Arc
Arc arc = new Arc();
Specify the x, y coordinates of the center of the Ellipse (of which this arc is a part of). These coordinates include – radiusX, radiusY, start angle and length of the arc using their respective setter methods as shown in the following code block.
You can also set the type of the arc (round, chord open) by using the setType() method.
//Setting the properties of the arc
arc.setCenterX(300.0f);
arc.setCenterY(150.0f);
arc.setRadiusX(90.0f);
arc.setRadiusY(90.0f);
arc.setStartAngle(40.0f);
arc.setLength(239.0f);
arc.setType(ArcType.ROUND);
You can set the type of the arc using the method setType() as shown in the following code block.
//Setting the type of the arc
arc.setType(ArcType.ROUND);
In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the Arc (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as shown below −
Group root = new Group(arc);
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Launch the JavaFX application by calling the static method launch()of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Following is a program which generates an arc. Save this code in a file with the name ArcExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
public class ArcExample extends Application {
@Override
public void start(Stage stage) {
//Drawing an arc
Arc arc = new Arc();
//Setting the properties of the arc
arc.setCenterX(300.0f);
arc.setCenterY(150.0f);
arc.setRadiusX(90.0f);
arc.setRadiusY(90.0f);
arc.setStartAngle(40.0f);
arc.setLength(239.0f);
//Setting the type of the arc
arc.setType(ArcType.ROUND);
//Creating a Group object
Group root = new Group(arc);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing an Arc");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac ArcExample.java
java ArcExample
On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1954,
"s": 1900,
"text": "In JavaFX, you can draw three kinds of arc’s namely −"
},
{
"code": null,
"e": 2021,
"s": 1954,
"text": "Open − An arc which is not closed at all is known as an open arc. "
},
{
"code": null,
"e": 2088,
"s": 2021,
"text": "Open − An arc which is not closed at all is known as an open arc. "
},
{
"code": null,
"e": 2158,
"s": 2088,
"text": "Chord − A chord is a type of an arc which is closed by straight line."
},
{
"code": null,
"e": 2228,
"s": 2158,
"text": "Chord − A chord is a type of an arc which is closed by straight line."
},
{
"code": null,
"e": 2347,
"s": 2228,
"text": "Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse."
},
{
"code": null,
"e": 2466,
"s": 2347,
"text": "Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse."
},
{
"code": null,
"e": 2614,
"s": 2466,
"text": "You can set the type of the arc using the method setType() by passing any of the following properties − ArcType.OPEN, ArcType.CHORD, ArcType.Round."
},
{
"code": null,
"e": 2670,
"s": 2614,
"text": "To Draw an arc in JavaFX, follow the steps given below."
},
{
"code": null,
"e": 2817,
"s": 2670,
"text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows."
},
{
"code": null,
"e": 2960,
"s": 2817,
"text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n} "
},
{
"code": null,
"e": 3123,
"s": 2960,
"text": "You can create an arc in JavaFX by instantiating the class named Arc which belongs to a package javafx.scene.shape. You can instantiate this class as shown below."
},
{
"code": null,
"e": 3192,
"s": 3123,
"text": "//Creating an object of the class Arc \nArc arc = new Arc();\n"
},
{
"code": null,
"e": 3440,
"s": 3192,
"text": "Specify the x, y coordinates of the center of the Ellipse (of which this arc is a part of). These coordinates include – radiusX, radiusY, start angle and length of the arc using their respective setter methods as shown in the following code block."
},
{
"code": null,
"e": 3528,
"s": 3440,
"text": "You can also set the type of the arc (round, chord open) by using the setType() method."
},
{
"code": null,
"e": 3743,
"s": 3528,
"text": "//Setting the properties of the arc \narc.setCenterX(300.0f); \narc.setCenterY(150.0f); \narc.setRadiusX(90.0f); \narc.setRadiusY(90.0f); \narc.setStartAngle(40.0f); \narc.setLength(239.0f); \narc.setType(ArcType.ROUND);\n"
},
{
"code": null,
"e": 3840,
"s": 3743,
"text": "You can set the type of the arc using the method setType() as shown in the following code block."
},
{
"code": null,
"e": 3900,
"s": 3840,
"text": "//Setting the type of the arc \narc.setType(ArcType.ROUND);\n"
},
{
"code": null,
"e": 4027,
"s": 3900,
"text": "In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene."
},
{
"code": null,
"e": 4206,
"s": 4027,
"text": "Pass the Arc (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as shown below −"
},
{
"code": null,
"e": 4236,
"s": 4206,
"text": "Group root = new Group(arc);\n"
},
{
"code": null,
"e": 4406,
"s": 4236,
"text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) created in the previous step."
},
{
"code": null,
"e": 4575,
"s": 4406,
"text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows."
},
{
"code": null,
"e": 4618,
"s": 4575,
"text": "Scene scene = new Scene(group ,600, 300);\n"
},
{
"code": null,
"e": 4807,
"s": 4618,
"text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class as a parameter."
},
{
"code": null,
"e": 4899,
"s": 4807,
"text": "Using the primaryStage object, set the title of the scene as Sample Application as follows."
},
{
"code": null,
"e": 4945,
"s": 4899,
"text": "primaryStage.setTitle(\"Sample Application\");\n"
},
{
"code": null,
"e": 5121,
"s": 4945,
"text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows."
},
{
"code": null,
"e": 5153,
"s": 5121,
"text": "primaryStage.setScene(scene); \n"
},
{
"code": null,
"e": 5248,
"s": 5153,
"text": "Display the contents of the scene using the method named show() of the Stage class as follows."
},
{
"code": null,
"e": 5270,
"s": 5248,
"text": "primaryStage.show();\n"
},
{
"code": null,
"e": 5396,
"s": 5270,
"text": "Launch the JavaFX application by calling the static method launch()of the Application class from the main method as follows."
},
{
"code": null,
"e": 5465,
"s": 5396,
"text": "public static void main(String args[]){ \n launch(args); \n} "
},
{
"code": null,
"e": 5568,
"s": 5465,
"text": "Following is a program which generates an arc. Save this code in a file with the name ArcExample.java."
},
{
"code": null,
"e": 6733,
"s": 5568,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene;\nimport javafx.stage.Stage; \nimport javafx.scene.shape.Arc; \nimport javafx.scene.shape.ArcType; \n \npublic class ArcExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing an arc \n Arc arc = new Arc(); \n \n //Setting the properties of the arc \n arc.setCenterX(300.0f); \n arc.setCenterY(150.0f); \n arc.setRadiusX(90.0f); \n arc.setRadiusY(90.0f); \n arc.setStartAngle(40.0f); \n arc.setLength(239.0f); \n \n //Setting the type of the arc \n arc.setType(ArcType.ROUND); \n \n //Creating a Group object \n Group root = new Group(arc); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing an Arc\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage\n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 6827,
"s": 6733,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6867,
"s": 6827,
"text": "javac ArcExample.java \njava ArcExample\n"
},
{
"code": null,
"e": 6981,
"s": 6867,
"text": "On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot."
},
{
"code": null,
"e": 7016,
"s": 6981,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7027,
"s": 7016,
"text": " Syed Raza"
},
{
"code": null,
"e": 7063,
"s": 7027,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 7099,
"s": 7063,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 7132,
"s": 7099,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7168,
"s": 7132,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 7175,
"s": 7168,
"text": " Print"
},
{
"code": null,
"e": 7186,
"s": 7175,
"text": " Add Notes"
}
] |
Get repetition of a string in Julia - repeat() Method - GeeksforGeeks
|
26 Mar, 2020
The repeat() is an inbuilt function in julia which is used to return a string which is the repetition of specified string with specified number of times.
Syntax:repeat(String::AbstractString, r::Integer)
Parameters:
String: Specified string or character
r::Integer: Specified number of times
Returns: It returns a string which is the repetition of specified string with specified number of times.
Example 1:
# Julia program to illustrate # the use of String repeat() method # Create a repetition of string "gfg"# with 3 times of repetition.println(repeat("gfg", 3)) # Create a repetition of character "a"# with 4 times of repetition.println(repeat("a", 4)) # Create a repetition of string "Geeks"# with 2 times of repetition.println(repeat("Geeks", 2)) # Create a repetition of string "@#"# with 3 times of repetition.println(repeat("@#", 3))
Output:
gfggfggfg
aaaa
GeeksGeeks
@#@#@#
Example 2:
# Julia program to illustrate # the use of String repeat() method # Create a repetition of string "123"# with 3 times of repetition.println(repeat("123", 3)) # Create a repetition of string "22"# with 4 times of repetition.println(repeat("22", 4)) # Create a repetition of string "03210"# with 2 times of repetitionprintln(repeat("03210", 2))
Output:
123123123
22222222
0321003210
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Searching in Array for a given element in Julia
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Exception handling in Julia
Get number of elements of array in Julia - length() Method
Find maximum element along with its index in Julia - findmax() Method
Working with Date and Time in Julia
Working with Excel Files in Julia
Getting last element of an array in Julia - last() Method
|
[
{
"code": null,
"e": 24153,
"s": 24125,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24307,
"s": 24153,
"text": "The repeat() is an inbuilt function in julia which is used to return a string which is the repetition of specified string with specified number of times."
},
{
"code": null,
"e": 24357,
"s": 24307,
"text": "Syntax:repeat(String::AbstractString, r::Integer)"
},
{
"code": null,
"e": 24369,
"s": 24357,
"text": "Parameters:"
},
{
"code": null,
"e": 24407,
"s": 24369,
"text": "String: Specified string or character"
},
{
"code": null,
"e": 24445,
"s": 24407,
"text": "r::Integer: Specified number of times"
},
{
"code": null,
"e": 24550,
"s": 24445,
"text": "Returns: It returns a string which is the repetition of specified string with specified number of times."
},
{
"code": null,
"e": 24561,
"s": 24550,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of String repeat() method # Create a repetition of string \"gfg\"# with 3 times of repetition.println(repeat(\"gfg\", 3)) # Create a repetition of character \"a\"# with 4 times of repetition.println(repeat(\"a\", 4)) # Create a repetition of string \"Geeks\"# with 2 times of repetition.println(repeat(\"Geeks\", 2)) # Create a repetition of string \"@#\"# with 3 times of repetition.println(repeat(\"@#\", 3))",
"e": 25000,
"s": 24561,
"text": null
},
{
"code": null,
"e": 25008,
"s": 25000,
"text": "Output:"
},
{
"code": null,
"e": 25041,
"s": 25008,
"text": "gfggfggfg\naaaa\nGeeksGeeks\n@#@#@#"
},
{
"code": null,
"e": 25052,
"s": 25041,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of String repeat() method # Create a repetition of string \"123\"# with 3 times of repetition.println(repeat(\"123\", 3)) # Create a repetition of string \"22\"# with 4 times of repetition.println(repeat(\"22\", 4)) # Create a repetition of string \"03210\"# with 2 times of repetitionprintln(repeat(\"03210\", 2))",
"e": 25401,
"s": 25052,
"text": null
},
{
"code": null,
"e": 25409,
"s": 25401,
"text": "Output:"
},
{
"code": null,
"e": 25439,
"s": 25409,
"text": "123123123\n22222222\n0321003210"
},
{
"code": null,
"e": 25445,
"s": 25439,
"text": "Julia"
},
{
"code": null,
"e": 25543,
"s": 25445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25552,
"s": 25543,
"text": "Comments"
},
{
"code": null,
"e": 25565,
"s": 25552,
"text": "Old Comments"
},
{
"code": null,
"e": 25635,
"s": 25565,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 25708,
"s": 25635,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 25756,
"s": 25708,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 25837,
"s": 25756,
"text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods"
},
{
"code": null,
"e": 25865,
"s": 25837,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 25924,
"s": 25865,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 25994,
"s": 25924,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 26030,
"s": 25994,
"text": "Working with Date and Time in Julia"
},
{
"code": null,
"e": 26064,
"s": 26030,
"text": "Working with Excel Files in Julia"
}
] |
How to change header background color of a table in Java
|
To change header background color, at first get the header background −
JTableHeader tableHeader = table.getTableHeader();
Now, set the background color using set Background() −
tableHeader.setBackground(Color.black);
Above, we have used the Color class to set the color.
The following is an example to change the header background color of a JTable −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class SwingDemo {
public static void main(String[] argv) throws Exception {
Integer[][] marks = {
{ 70, 66, 76, 89, 67, 98 },
{ 67, 89, 64, 78, 59, 78 },
{ 68, 87, 71, 65, 87, 86 },
{ 80, 56, 89, 98, 59, 56 },
{ 75, 95, 90, 73, 57, 79 },
{ 69, 49, 56, 78, 76, 77 }
};
String col[] = { "S1", "S2", "S3", "S4", "S5", "S6"};
JTable table = new JTable(marks, col);
Font font = new Font("Verdana", Font.PLAIN, 12);
table.setFont(font);
table.setRowHeight(30);
table.setBackground(Color.blue);
table.setForeground(Color.white);
JTableHeader tableHeader = table.getTableHeader();
tableHeader.setBackground(Color.black);
tableHeader.setForeground(Color.white);
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
}
The output is as follows. Here, we have changed the header background color to BLACK −
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To change header background color, at first get the header background −"
},
{
"code": null,
"e": 1185,
"s": 1134,
"text": "JTableHeader tableHeader = table.getTableHeader();"
},
{
"code": null,
"e": 1240,
"s": 1185,
"text": "Now, set the background color using set Background() −"
},
{
"code": null,
"e": 1280,
"s": 1240,
"text": "tableHeader.setBackground(Color.black);"
},
{
"code": null,
"e": 1334,
"s": 1280,
"text": "Above, we have used the Color class to set the color."
},
{
"code": null,
"e": 1414,
"s": 1334,
"text": "The following is an example to change the header background color of a JTable −"
},
{
"code": null,
"e": 2529,
"s": 1414,
"text": "package my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.JTableHeader;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n Integer[][] marks = {\n { 70, 66, 76, 89, 67, 98 },\n { 67, 89, 64, 78, 59, 78 },\n { 68, 87, 71, 65, 87, 86 },\n { 80, 56, 89, 98, 59, 56 },\n { 75, 95, 90, 73, 57, 79 },\n { 69, 49, 56, 78, 76, 77 }\n };\n String col[] = { \"S1\", \"S2\", \"S3\", \"S4\", \"S5\", \"S6\"};\n JTable table = new JTable(marks, col);\n Font font = new Font(\"Verdana\", Font.PLAIN, 12);\n table.setFont(font);\n table.setRowHeight(30);\n table.setBackground(Color.blue);\n table.setForeground(Color.white);\n JTableHeader tableHeader = table.getTableHeader();\n tableHeader.setBackground(Color.black);\n tableHeader.setForeground(Color.white);\n JFrame frame = new JFrame();\n frame.setSize(600, 400);\n frame.add(new JScrollPane(table));\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2616,
"s": 2529,
"text": "The output is as follows. Here, we have changed the header background color to BLACK −"
}
] |
Turtle graphics using Python
|
Turtle is a Python library to draw graphics. After we import Turtle we can give commands like forward, backward, right, left etc. This commands will draw different shapes when we. When We combine Search commands we can create many nice graphics in the below example we will see some simple scenarios and then some Complex ones where nice graphics is created.
forward(10) It moves the turtle (arrow) forward by 10 pixels.
forward(10) It moves the turtle (arrow) forward by 10 pixels.
backward(5) It moves the turtle (arrow) backward by 5 pixels
backward(5) It moves the turtle (arrow) backward by 5 pixels
right(35) It moves the turtle (arrow) clockwise by an angle of 35 degrees.
right(35) It moves the turtle (arrow) clockwise by an angle of 35 degrees.
left(55) It moves the turtle (arrow) counter-clockwise by an angle of 55 degrees
left(55) It moves the turtle (arrow) counter-clockwise by an angle of 55 degrees
goto(x,y) It moves the turtle (arrow) to the position x, y
goto(x,y) It moves the turtle (arrow) to the position x, y
dot() It creates a dot in the current position.
dot() It creates a dot in the current position.
shape(‘circle’) It draws a circle shape.
shape(‘circle’) It draws a circle shape.
Let’s see some drawings using some simple commands.
In the below program we draw a start. We choose appropriate steps to move the cursor forward and then right continuously to get this result.
import turtle
star = turtle.Turtle()
for i in range(100):
star.forward(100)
star.right(144)
turtle.done()
Running the above code gives us the following result
We follow a similar approach where the turtle moves in all four directions to create the English alphabet E.
import turtle
t=turtle.Turtle()
t.penup()
t.setpos(-20,40)
t.pendown()
t.pensize(10)
t.pencolor("pink")
t.forward(100)
t.backward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
t.backward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
turtle.done()
Running the above code gives us the following result
In the next example we see the drawing of multiple squares all starting from a common point. We sue the usual simple commands to go forward, backward and then turn 90 degrees.
import turtle
mult_square=turtle.Turtle()
def Multiple_Squares(length, colour):
mult_square.pencolor(colour)
mult_square.pensize(2)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.setheading(360)
for i in range(60,120,15):
Multiple_Squares(i,"blue")
turtle.done
Running the above code gives us the following result
This is a very interesting example where we use turtle to create a spiral structure. The final shape is a hexagon and there are various colours used in producing the sides of the hexagon.
import turtle
colors = [ "pink","yellow","blue","green","white","red"]
sketch = turtle.Pen()
turtle.bgcolor("black")
for i in range(200):
sketch.pencolor(colors[i % 6])
sketch.width(i/100 + 1)
sketch.forward(i)
sketch.left(59)
Running the above code gives us the following result
|
[
{
"code": null,
"e": 1421,
"s": 1062,
"text": "Turtle is a Python library to draw graphics. After we import Turtle we can give commands like forward, backward, right, left etc. This commands will draw different shapes when we. When We combine Search commands we can create many nice graphics in the below example we will see some simple scenarios and then some Complex ones where nice graphics is created."
},
{
"code": null,
"e": 1484,
"s": 1421,
"text": "forward(10) It moves the turtle (arrow) forward by 10 pixels."
},
{
"code": null,
"e": 1547,
"s": 1484,
"text": "forward(10) It moves the turtle (arrow) forward by 10 pixels."
},
{
"code": null,
"e": 1609,
"s": 1547,
"text": "backward(5) It moves the turtle (arrow) backward by 5 pixels"
},
{
"code": null,
"e": 1671,
"s": 1609,
"text": "backward(5) It moves the turtle (arrow) backward by 5 pixels"
},
{
"code": null,
"e": 1748,
"s": 1671,
"text": " right(35) It moves the turtle (arrow) clockwise by an angle of 35 degrees."
},
{
"code": null,
"e": 1825,
"s": 1748,
"text": " right(35) It moves the turtle (arrow) clockwise by an angle of 35 degrees."
},
{
"code": null,
"e": 1907,
"s": 1825,
"text": "left(55) It moves the turtle (arrow) counter-clockwise by an angle of 55 degrees"
},
{
"code": null,
"e": 1989,
"s": 1907,
"text": "left(55) It moves the turtle (arrow) counter-clockwise by an angle of 55 degrees"
},
{
"code": null,
"e": 2050,
"s": 1989,
"text": " goto(x,y) It moves the turtle (arrow) to the position x, y"
},
{
"code": null,
"e": 2111,
"s": 2050,
"text": " goto(x,y) It moves the turtle (arrow) to the position x, y"
},
{
"code": null,
"e": 2160,
"s": 2111,
"text": " dot() It creates a dot in the current position."
},
{
"code": null,
"e": 2209,
"s": 2160,
"text": " dot() It creates a dot in the current position."
},
{
"code": null,
"e": 2251,
"s": 2209,
"text": " shape(‘circle’) It draws a circle shape."
},
{
"code": null,
"e": 2293,
"s": 2251,
"text": " shape(‘circle’) It draws a circle shape."
},
{
"code": null,
"e": 2345,
"s": 2293,
"text": "Let’s see some drawings using some simple commands."
},
{
"code": null,
"e": 2486,
"s": 2345,
"text": "In the below program we draw a start. We choose appropriate steps to move the cursor forward and then right continuously to get this result."
},
{
"code": null,
"e": 2601,
"s": 2486,
"text": "import turtle\nstar = turtle.Turtle()\nfor i in range(100):\n star.forward(100)\n star.right(144)\n turtle.done()"
},
{
"code": null,
"e": 2654,
"s": 2601,
"text": "Running the above code gives us the following result"
},
{
"code": null,
"e": 2763,
"s": 2654,
"text": "We follow a similar approach where the turtle moves in all four directions to create the English alphabet E."
},
{
"code": null,
"e": 3034,
"s": 2763,
"text": "import turtle\nt=turtle.Turtle()\nt.penup()\nt.setpos(-20,40)\nt.pendown()\nt.pensize(10)\nt.pencolor(\"pink\")\nt.forward(100)\nt.backward(100)\nt.right(90)\nt.forward(100)\nt.left(90)\nt.forward(100)\nt.backward(100)\nt.right(90)\nt.forward(100)\nt.left(90)\nt.forward(100)\nturtle.done()"
},
{
"code": null,
"e": 3087,
"s": 3034,
"text": "Running the above code gives us the following result"
},
{
"code": null,
"e": 3263,
"s": 3087,
"text": "In the next example we see the drawing of multiple squares all starting from a common point. We sue the usual simple commands to go forward, backward and then turn 90 degrees."
},
{
"code": null,
"e": 3695,
"s": 3263,
"text": "import turtle\nmult_square=turtle.Turtle()\ndef Multiple_Squares(length, colour):\nmult_square.pencolor(colour)\nmult_square.pensize(2)\nmult_square.forward(length)\nmult_square.right(90)\nmult_square.forward(length)\nmult_square.right(90)\nmult_square.forward(length)\nmult_square.right(90)\nmult_square.forward(length)\nmult_square.right(90)\nmult_square.setheading(360)\nfor i in range(60,120,15):\n Multiple_Squares(i,\"blue\")\n turtle.done"
},
{
"code": null,
"e": 3748,
"s": 3695,
"text": "Running the above code gives us the following result"
},
{
"code": null,
"e": 3936,
"s": 3748,
"text": "This is a very interesting example where we use turtle to create a spiral structure. The final shape is a hexagon and there are various colours used in producing the sides of the hexagon."
},
{
"code": null,
"e": 4175,
"s": 3936,
"text": "import turtle\ncolors = [ \"pink\",\"yellow\",\"blue\",\"green\",\"white\",\"red\"]\nsketch = turtle.Pen()\nturtle.bgcolor(\"black\")\nfor i in range(200):\n sketch.pencolor(colors[i % 6])\n sketch.width(i/100 + 1)\n sketch.forward(i)\n sketch.left(59)"
},
{
"code": null,
"e": 4228,
"s": 4175,
"text": "Running the above code gives us the following result"
}
] |
Draw a line using OpenCV in C++ - GeeksforGeeks
|
27 Jan, 2021
In this article, we will discuss how to draw a line using OpenCV in C++. The idea is to use the line() function from OpenCV C++ library.
Syntax:
line(img, pt1, pt2, color, thickness, lineType, shift)
Parameters:
img: This is the image file.
start: Start point of the line segment. The first point out of two ends of a line segment. It is a tuple of two coordinates (x-coordinate, y-coordinate)).
end: Endpoint of the line segment. The second point out of two ends of a line segment. It is a tuple of two coordinates (x-coordinate, y-coordinate)).
color: Color of the line to be drawn. It is a tuple representing 3 colors (B, G, R) i.e.. (Blue, Green, Red).
thickness: Thickness of the line drawn.
lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Antialiased lines formed by using the Gaussian filter.
LINE_4: Line was drawn using 4 connected Bresenham algorithm.
LINE_8: Line drawn using 8 connected Bresenham algorithm.
LINE_AA: It draws Antialiased lines formed by using the Gaussian filter.
nshift: It is the Number of fractional bits in the point coordinates.
Return Value: It returns an image.
Program 1:
Below is the program shows how to draw all types of lines over a self-formed background image:
C++
// C++ program for the above approach#include <iostream>#include <opencv2/core/core.hpp> // Library to include for// drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Create a blank image of size // (500 x 500) with black // background (B, G, R) : (0, 0, 0) Mat image(500, 500, CV_8UC3, Scalar(0, 0, 0)); // Check if the image is created // successfully if (!image.data) { cout << "Could not open or find" << " the image"; return 0; } Point p1(0, 0), p2(100, 0); Point p3(200, 0), p4(500, 500); int thickness = 2; // Line drawn using 8 connected // Bresenham algorithm line(image, p1, p4, Scalar(255, 0, 0), thickness, LINE_8); // Line drawn using 4 connected // Bresenham algorithm line(image, p2, p4, Scalar(0, 255, 0), thickness, LINE_4); // Antialiased line line(image, p3, p4, Scalar(0, 0, 255), thickness, LINE_AA); // Show our image inside window imshow("Output", image); waitKey(0); return 0;}
Output:
Program 2:
Below is the program to shows how to draw a line over a loaded image:
C++
// C++ program for the above approach#include <iostream>#include <opencv2/core/core.hpp> // Library to include for// drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Driver codeint main(int argc, char** argv){ // Path of the image file Mat image = imread( "C:/Users/harsh/Downloads/geeks.png", IMREAD_COLOR); // Check if the image is loaded // successfully if (!image.data) { std::cout << "Could not open or " "find the image"; return 0; } Point p1(0, 0), p2(250, 250); int thickness = 2; // Line drawn using 8 connected // Bresenham algorithm line(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside window imshow("Output", image); waitKey(0); return 0;}
Output:
OpenCV
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 24235,
"s": 24098,
"text": "In this article, we will discuss how to draw a line using OpenCV in C++. The idea is to use the line() function from OpenCV C++ library."
},
{
"code": null,
"e": 24243,
"s": 24235,
"text": "Syntax:"
},
{
"code": null,
"e": 24298,
"s": 24243,
"text": "line(img, pt1, pt2, color, thickness, lineType, shift)"
},
{
"code": null,
"e": 24310,
"s": 24298,
"text": "Parameters:"
},
{
"code": null,
"e": 24339,
"s": 24310,
"text": "img: This is the image file."
},
{
"code": null,
"e": 24494,
"s": 24339,
"text": "start: Start point of the line segment. The first point out of two ends of a line segment. It is a tuple of two coordinates (x-coordinate, y-coordinate))."
},
{
"code": null,
"e": 24645,
"s": 24494,
"text": "end: Endpoint of the line segment. The second point out of two ends of a line segment. It is a tuple of two coordinates (x-coordinate, y-coordinate))."
},
{
"code": null,
"e": 24755,
"s": 24645,
"text": "color: Color of the line to be drawn. It is a tuple representing 3 colors (B, G, R) i.e.. (Blue, Green, Red)."
},
{
"code": null,
"e": 24795,
"s": 24755,
"text": "thickness: Thickness of the line drawn."
},
{
"code": null,
"e": 25040,
"s": 24795,
"text": "lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Antialiased lines formed by using the Gaussian filter."
},
{
"code": null,
"e": 25102,
"s": 25040,
"text": "LINE_4: Line was drawn using 4 connected Bresenham algorithm."
},
{
"code": null,
"e": 25160,
"s": 25102,
"text": "LINE_8: Line drawn using 8 connected Bresenham algorithm."
},
{
"code": null,
"e": 25233,
"s": 25160,
"text": "LINE_AA: It draws Antialiased lines formed by using the Gaussian filter."
},
{
"code": null,
"e": 25303,
"s": 25233,
"text": "nshift: It is the Number of fractional bits in the point coordinates."
},
{
"code": null,
"e": 25338,
"s": 25303,
"text": "Return Value: It returns an image."
},
{
"code": null,
"e": 25349,
"s": 25338,
"text": "Program 1:"
},
{
"code": null,
"e": 25444,
"s": 25349,
"text": "Below is the program shows how to draw all types of lines over a self-formed background image:"
},
{
"code": null,
"e": 25448,
"s": 25444,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <opencv2/core/core.hpp> // Library to include for// drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Create a blank image of size // (500 x 500) with black // background (B, G, R) : (0, 0, 0) Mat image(500, 500, CV_8UC3, Scalar(0, 0, 0)); // Check if the image is created // successfully if (!image.data) { cout << \"Could not open or find\" << \" the image\"; return 0; } Point p1(0, 0), p2(100, 0); Point p3(200, 0), p4(500, 500); int thickness = 2; // Line drawn using 8 connected // Bresenham algorithm line(image, p1, p4, Scalar(255, 0, 0), thickness, LINE_8); // Line drawn using 4 connected // Bresenham algorithm line(image, p2, p4, Scalar(0, 255, 0), thickness, LINE_4); // Antialiased line line(image, p3, p4, Scalar(0, 0, 255), thickness, LINE_AA); // Show our image inside window imshow(\"Output\", image); waitKey(0); return 0;}",
"e": 26622,
"s": 25448,
"text": null
},
{
"code": null,
"e": 26630,
"s": 26622,
"text": "Output:"
},
{
"code": null,
"e": 26641,
"s": 26630,
"text": "Program 2:"
},
{
"code": null,
"e": 26711,
"s": 26641,
"text": "Below is the program to shows how to draw a line over a loaded image:"
},
{
"code": null,
"e": 26715,
"s": 26711,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <opencv2/core/core.hpp> // Library to include for// drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Driver codeint main(int argc, char** argv){ // Path of the image file Mat image = imread( \"C:/Users/harsh/Downloads/geeks.png\", IMREAD_COLOR); // Check if the image is loaded // successfully if (!image.data) { std::cout << \"Could not open or \" \"find the image\"; return 0; } Point p1(0, 0), p2(250, 250); int thickness = 2; // Line drawn using 8 connected // Bresenham algorithm line(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside window imshow(\"Output\", image); waitKey(0); return 0;}",
"e": 27587,
"s": 26715,
"text": null
},
{
"code": null,
"e": 27595,
"s": 27587,
"text": "Output:"
},
{
"code": null,
"e": 27602,
"s": 27595,
"text": "OpenCV"
},
{
"code": null,
"e": 27606,
"s": 27602,
"text": "C++"
},
{
"code": null,
"e": 27619,
"s": 27606,
"text": "C++ Programs"
},
{
"code": null,
"e": 27623,
"s": 27619,
"text": "CPP"
},
{
"code": null,
"e": 27721,
"s": 27623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27749,
"s": 27721,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27769,
"s": 27749,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27802,
"s": 27769,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27826,
"s": 27802,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27847,
"s": 27826,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27882,
"s": 27847,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27908,
"s": 27882,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27967,
"s": 27908,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 28011,
"s": 27967,
"text": "Program to print ASCII Value of a character"
}
] |
Functional Programming in Python - GeeksforGeeks
|
11 Oct, 2021
Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve“. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables.
Any Functional programming language is expected to follow these concepts.
Pure Functions: These functions have two main properties. First, they always produce the same output for the same arguments irrespective of anything else. Secondly, they have no side-effects i.e. they do modify any argument or global variables or output something.
Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion.
Functions are First-Class and can be Higher-Order: First-class functions are treated as first-class variable. The first-class variables can be passed to functions as a parameter, can be returned from functions or stored in data structures.
Variables are Immutable: In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables.
Python too supports Functional Programming paradigms without the support of any special features or libraries.
As Discussed above, pure functions have two properties.
It always produces the same output for the same arguments. For example, 3+7 will always be 10 no matter what.
It does not change or modifies the input variable.
The second property is also known as immutability. The only result of the Pure Function is the value it returns. They are deterministic. Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change.
Example:
# Python program to demonstrate# pure functions # A pure function that does Not# changes the input list and # returns the new Listdef pure_func(List): New_List = [] for i in List: New_List.append(i**2) return New_List # Driver's codeOriginal_List = [1, 2, 3, 4]Modified_List = pure_func(Original_List) print("Original List:", Original_List)print("Modified List:", Modified_List)
Output:
Original List: [1, 2, 3, 4]
Modified List: [1, 4, 9, 16]
During functional programming, there is no concept of for loop or while loop, instead recursion is used. Recursion is a process in which a function calls itself directly or indirectly. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. A question may arise what is base case? The base case can be considered as a condition that tells the compiler or interpreter to exit from the function.
Note: For more information, refer Recursion
Example: Let’s consider a program that will find the sum of all the elements of a list without using any for loop.
# Python program to demonstrate# recursion # Recursive Function to find# sum of a listdef Sum(L, i, n, count): # Base case if n <= i: return count count += L[i] # Going into the recursion count = Sum(L, i + 1, n, count) return count # Driver's codeL = [1, 2, 3, 4, 5]count = 0n = len(L)print(Sum(L, 0, n, count))
Output:
15
First-class objects are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, ...
# Python program to demonstrate# higher order functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func("Hi, I am created by a function passed as an argument.") print(greeting) greet(shout) greet(whisper)
Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, I am created by a function passed as an argument.
Note: For more information, refer to First Class functions in Python.
Built-in Higher-order functions
To make the processing of iterable objects like lists and iterator much easier, Python has implemented some commonly used Higher-Order Functions. These functions return an iterator that is space-efficient. Some of the built-in higher-order functions are:
Map(): map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)Syntax: map(fun, iter)Parameters:fun: It is a function to which map passes each element of given iterable.iter: It is a iterable which is to be mapped.Return Type: Returns an iterator of map class.Example:# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers) # Does not Print the valueprint(results) # For Printing valuefor result in results: print(result, end = " ")Output:<map object at 0x7fae3004b630>
2 4 6 8
Note: For more information, refer to Python map() function
Syntax: map(fun, iter)
Parameters:fun: It is a function to which map passes each element of given iterable.iter: It is a iterable which is to be mapped.
Return Type: Returns an iterator of map class.
Example:
# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers) # Does not Print the valueprint(results) # For Printing valuefor result in results: print(result, end = " ")
Output:
<map object at 0x7fae3004b630>
2 4 6 8
Note: For more information, refer to Python map() function
filter(): The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.Syntax: filter(function, sequence)Parameters:function: a function that tests if each element of a sequence true or not.sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.Return Type: returns an iterator that is already filtered.Example:# Python program to demonstrate working # of the filter. # function that filters vowels def fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequence sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter function filtered = filter(fun, sequence) print('The filtered letters are:') for s in filtered: print(s) Output:The filtered letters are:
e
e
Note: For more information, refer to filter() in Python
Syntax: filter(function, sequence)
Parameters:function: a function that tests if each element of a sequence true or not.sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.
Return Type: returns an iterator that is already filtered.
Example:
# Python program to demonstrate working # of the filter. # function that filters vowels def fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequence sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter function filtered = filter(fun, sequence) print('The filtered letters are:') for s in filtered: print(s)
Output:
The filtered letters are:
e
e
Note: For more information, refer to filter() in Python
Lambda functions: In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.Syntax:lambda arguments: expression
1) This function can have any number of arguments but only one expression, which is evaluated and returned.2) One is free to use lambda functions wherever function objects are required.3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.4) It has various uses in particular fields of programming besides other types of expressions in functions.Example:# Python code to demonstrate# lambda cube = lambda x: x * x*x print(cube(7)) L = [1, 3, 2, 4, 5, 6]is_even = [x for x in L if x % 2 == 0] print(is_even) Output:343
[2, 4, 6]
Note: For more information, refer to Python lambda.
Syntax:
lambda arguments: expression
1) This function can have any number of arguments but only one expression, which is evaluated and returned.2) One is free to use lambda functions wherever function objects are required.3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.4) It has various uses in particular fields of programming besides other types of expressions in functions.
Example:
# Python code to demonstrate# lambda cube = lambda x: x * x*x print(cube(7)) L = [1, 3, 2, 4, 5, 6]is_even = [x for x in L if x % 2 == 0] print(is_even)
Output:
343
[2, 4, 6]
Note: For more information, refer to Python lambda.
Immutability is a functional programming paradigm can be used for debugging as it will throw an error where the variable is being changed not where the value is changed. Python too supports some immutable data types like string, tuple, numeric, etc.
Example:
# Python program to demonstrate # immutable data types # String data typesimmutable = "GeeksforGeeks" # changing the values will# raise an errorimmutable[1] = 'K'
Output:
Traceback (most recent call last):
File "/home/ee8bf8d8f560b97c7ec0ef080a077879.py", line 10, in
immutable[1] = 'K'
TypeError: 'str' object does not support item assignment
Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.
Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.
Akanksha_Rai
pujasingg43
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41161,
"s": 41133,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 41584,
"s": 41161,
"text": "Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve“. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables."
},
{
"code": null,
"e": 41658,
"s": 41584,
"text": "Any Functional programming language is expected to follow these concepts."
},
{
"code": null,
"e": 41923,
"s": 41658,
"text": "Pure Functions: These functions have two main properties. First, they always produce the same output for the same arguments irrespective of anything else. Secondly, they have no side-effects i.e. they do modify any argument or global variables or output something."
},
{
"code": null,
"e": 42062,
"s": 41923,
"text": "Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion."
},
{
"code": null,
"e": 42302,
"s": 42062,
"text": "Functions are First-Class and can be Higher-Order: First-class functions are treated as first-class variable. The first-class variables can be passed to functions as a parameter, can be returned from functions or stored in data structures."
},
{
"code": null,
"e": 42480,
"s": 42302,
"text": "Variables are Immutable: In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables."
},
{
"code": null,
"e": 42591,
"s": 42480,
"text": "Python too supports Functional Programming paradigms without the support of any special features or libraries."
},
{
"code": null,
"e": 42647,
"s": 42591,
"text": "As Discussed above, pure functions have two properties."
},
{
"code": null,
"e": 42757,
"s": 42647,
"text": "It always produces the same output for the same arguments. For example, 3+7 will always be 10 no matter what."
},
{
"code": null,
"e": 42808,
"s": 42757,
"text": "It does not change or modifies the input variable."
},
{
"code": null,
"e": 43395,
"s": 42808,
"text": "The second property is also known as immutability. The only result of the Pure Function is the value it returns. They are deterministic. Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change."
},
{
"code": null,
"e": 43404,
"s": 43395,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# pure functions # A pure function that does Not# changes the input list and # returns the new Listdef pure_func(List): New_List = [] for i in List: New_List.append(i**2) return New_List # Driver's codeOriginal_List = [1, 2, 3, 4]Modified_List = pure_func(Original_List) print(\"Original List:\", Original_List)print(\"Modified List:\", Modified_List)",
"e": 43830,
"s": 43404,
"text": null
},
{
"code": null,
"e": 43838,
"s": 43830,
"text": "Output:"
},
{
"code": null,
"e": 43896,
"s": 43838,
"text": "Original List: [1, 2, 3, 4]\nModified List: [1, 4, 9, 16]\n"
},
{
"code": null,
"e": 44384,
"s": 43896,
"text": "During functional programming, there is no concept of for loop or while loop, instead recursion is used. Recursion is a process in which a function calls itself directly or indirectly. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. A question may arise what is base case? The base case can be considered as a condition that tells the compiler or interpreter to exit from the function."
},
{
"code": null,
"e": 44428,
"s": 44384,
"text": "Note: For more information, refer Recursion"
},
{
"code": null,
"e": 44543,
"s": 44428,
"text": "Example: Let’s consider a program that will find the sum of all the elements of a list without using any for loop."
},
{
"code": "# Python program to demonstrate# recursion # Recursive Function to find# sum of a listdef Sum(L, i, n, count): # Base case if n <= i: return count count += L[i] # Going into the recursion count = Sum(L, i + 1, n, count) return count # Driver's codeL = [1, 2, 3, 4, 5]count = 0n = len(L)print(Sum(L, 0, n, count))",
"e": 44913,
"s": 44543,
"text": null
},
{
"code": null,
"e": 44921,
"s": 44913,
"text": "Output:"
},
{
"code": null,
"e": 44925,
"s": 44921,
"text": "15\n"
},
{
"code": null,
"e": 45181,
"s": 44925,
"text": "First-class objects are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects."
},
{
"code": null,
"e": 45218,
"s": 45181,
"text": "Properties of first class functions:"
},
{
"code": null,
"e": 45264,
"s": 45218,
"text": "A function is an instance of the Object type."
},
{
"code": null,
"e": 45306,
"s": 45264,
"text": "You can store the function in a variable."
},
{
"code": null,
"e": 45368,
"s": 45306,
"text": "You can pass the function as a parameter to another function."
},
{
"code": null,
"e": 45413,
"s": 45368,
"text": "You can return the function from a function."
},
{
"code": null,
"e": 45483,
"s": 45413,
"text": "You can store them in data structures such as hash tables, lists, ..."
},
{
"code": "# Python program to demonstrate# higher order functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func(\"Hi, I am created by a function passed as an argument.\") print(greeting) greet(shout) greet(whisper) ",
"e": 45823,
"s": 45483,
"text": null
},
{
"code": null,
"e": 45831,
"s": 45823,
"text": "Output:"
},
{
"code": null,
"e": 45940,
"s": 45831,
"text": "HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.\nhi, I am created by a function passed as an argument.\n"
},
{
"code": null,
"e": 46010,
"s": 45940,
"text": "Note: For more information, refer to First Class functions in Python."
},
{
"code": null,
"e": 46042,
"s": 46010,
"text": "Built-in Higher-order functions"
},
{
"code": null,
"e": 46297,
"s": 46042,
"text": "To make the processing of iterable objects like lists and iterator much easier, Python has implemented some commonly used Higher-Order Functions. These functions return an iterator that is space-efficient. Some of the built-in higher-order functions are:"
},
{
"code": null,
"e": 47064,
"s": 46297,
"text": "Map(): map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)Syntax: map(fun, iter)Parameters:fun: It is a function to which map passes each element of given iterable.iter: It is a iterable which is to be mapped.Return Type: Returns an iterator of map class.Example:# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers) # Does not Print the valueprint(results) # For Printing valuefor result in results: print(result, end = \" \")Output:<map object at 0x7fae3004b630>\n2 4 6 8 \nNote: For more information, refer to Python map() function"
},
{
"code": null,
"e": 47087,
"s": 47064,
"text": "Syntax: map(fun, iter)"
},
{
"code": null,
"e": 47217,
"s": 47087,
"text": "Parameters:fun: It is a function to which map passes each element of given iterable.iter: It is a iterable which is to be mapped."
},
{
"code": null,
"e": 47264,
"s": 47217,
"text": "Return Type: Returns an iterator of map class."
},
{
"code": null,
"e": 47273,
"s": 47264,
"text": "Example:"
},
{
"code": "# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers) # Does not Print the valueprint(results) # For Printing valuefor result in results: print(result, end = \" \")",
"e": 47593,
"s": 47273,
"text": null
},
{
"code": null,
"e": 47601,
"s": 47593,
"text": "Output:"
},
{
"code": null,
"e": 47642,
"s": 47601,
"text": "<map object at 0x7fae3004b630>\n2 4 6 8 \n"
},
{
"code": null,
"e": 47701,
"s": 47642,
"text": "Note: For more information, refer to Python map() function"
},
{
"code": null,
"e": 48678,
"s": 47701,
"text": "filter(): The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.Syntax: filter(function, sequence)Parameters:function: a function that tests if each element of a sequence true or not.sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.Return Type: returns an iterator that is already filtered.Example:# Python program to demonstrate working # of the filter. # function that filters vowels def fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequence sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter function filtered = filter(fun, sequence) print('The filtered letters are:') for s in filtered: print(s) Output:The filtered letters are:\ne\ne\nNote: For more information, refer to filter() in Python"
},
{
"code": null,
"e": 48713,
"s": 48678,
"text": "Syntax: filter(function, sequence)"
},
{
"code": null,
"e": 48908,
"s": 48713,
"text": "Parameters:function: a function that tests if each element of a sequence true or not.sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators."
},
{
"code": null,
"e": 48967,
"s": 48908,
"text": "Return Type: returns an iterator that is already filtered."
},
{
"code": null,
"e": 48976,
"s": 48967,
"text": "Example:"
},
{
"code": "# Python program to demonstrate working # of the filter. # function that filters vowels def fun(variable): letters = ['a', 'e', 'i', 'o', 'u'] if (variable in letters): return True else: return False # sequence sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] # using filter function filtered = filter(fun, sequence) print('The filtered letters are:') for s in filtered: print(s) ",
"e": 49424,
"s": 48976,
"text": null
},
{
"code": null,
"e": 49432,
"s": 49424,
"text": "Output:"
},
{
"code": null,
"e": 49463,
"s": 49432,
"text": "The filtered letters are:\ne\ne\n"
},
{
"code": null,
"e": 49519,
"s": 49463,
"text": "Note: For more information, refer to filter() in Python"
},
{
"code": null,
"e": 50433,
"s": 49519,
"text": "Lambda functions: In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.Syntax:lambda arguments: expression\n1) This function can have any number of arguments but only one expression, which is evaluated and returned.2) One is free to use lambda functions wherever function objects are required.3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.4) It has various uses in particular fields of programming besides other types of expressions in functions.Example:# Python code to demonstrate# lambda cube = lambda x: x * x*x print(cube(7)) L = [1, 3, 2, 4, 5, 6]is_even = [x for x in L if x % 2 == 0] print(is_even) Output:343\n[2, 4, 6]\nNote: For more information, refer to Python lambda."
},
{
"code": null,
"e": 50441,
"s": 50433,
"text": "Syntax:"
},
{
"code": null,
"e": 50471,
"s": 50441,
"text": "lambda arguments: expression\n"
},
{
"code": null,
"e": 50876,
"s": 50471,
"text": "1) This function can have any number of arguments but only one expression, which is evaluated and returned.2) One is free to use lambda functions wherever function objects are required.3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.4) It has various uses in particular fields of programming besides other types of expressions in functions."
},
{
"code": null,
"e": 50885,
"s": 50876,
"text": "Example:"
},
{
"code": "# Python code to demonstrate# lambda cube = lambda x: x * x*x print(cube(7)) L = [1, 3, 2, 4, 5, 6]is_even = [x for x in L if x % 2 == 0] print(is_even) ",
"e": 51054,
"s": 50885,
"text": null
},
{
"code": null,
"e": 51062,
"s": 51054,
"text": "Output:"
},
{
"code": null,
"e": 51077,
"s": 51062,
"text": "343\n[2, 4, 6]\n"
},
{
"code": null,
"e": 51129,
"s": 51077,
"text": "Note: For more information, refer to Python lambda."
},
{
"code": null,
"e": 51379,
"s": 51129,
"text": "Immutability is a functional programming paradigm can be used for debugging as it will throw an error where the variable is being changed not where the value is changed. Python too supports some immutable data types like string, tuple, numeric, etc."
},
{
"code": null,
"e": 51388,
"s": 51379,
"text": "Example:"
},
{
"code": "# Python program to demonstrate # immutable data types # String data typesimmutable = \"GeeksforGeeks\" # changing the values will# raise an errorimmutable[1] = 'K'",
"e": 51557,
"s": 51388,
"text": null
},
{
"code": null,
"e": 51565,
"s": 51557,
"text": "Output:"
},
{
"code": null,
"e": 51746,
"s": 51565,
"text": "Traceback (most recent call last):\n File \"/home/ee8bf8d8f560b97c7ec0ef080a077879.py\", line 10, in \n immutable[1] = 'K'\nTypeError: 'str' object does not support item assignment\n"
},
{
"code": null,
"e": 52010,
"s": 51746,
"text": "Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone."
},
{
"code": null,
"e": 52288,
"s": 52010,
"text": "Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone."
},
{
"code": null,
"e": 52301,
"s": 52288,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 52313,
"s": 52301,
"text": "pujasingg43"
},
{
"code": null,
"e": 52330,
"s": 52313,
"text": "Python-Functions"
},
{
"code": null,
"e": 52337,
"s": 52330,
"text": "Python"
},
{
"code": null,
"e": 52435,
"s": 52337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52444,
"s": 52435,
"text": "Comments"
},
{
"code": null,
"e": 52457,
"s": 52444,
"text": "Old Comments"
},
{
"code": null,
"e": 52485,
"s": 52457,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 52535,
"s": 52485,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 52557,
"s": 52535,
"text": "Python map() function"
},
{
"code": null,
"e": 52601,
"s": 52557,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 52636,
"s": 52601,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 52658,
"s": 52636,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 52690,
"s": 52658,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 52720,
"s": 52690,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 52762,
"s": 52720,
"text": "Different ways to create Pandas Dataframe"
}
] |
How can I add a new column which counts the number of rows as serial number in MySQL?
|
To add a new column that counts the number of rows as serial number, you can use the global variable in select statement.
Let us create a table. The query to create a table is as follows:
mysql> create table addColumnToCountAsSerialNumber
-> (
-> Id int,
-> Name varchar(20),
-> Age int,
-> Salary int
-> );
Query OK, 0 rows affected (0.80 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into addColumnToCountAsSerialNumber values(10,'John',23,8576);
Query OK, 1 row affected (0.10 sec)
mysql> insert into addColumnToCountAsSerialNumber values(12,'Carol',21,4686);
Query OK, 1 row affected (0.14 sec)
mysql> insert into addColumnToCountAsSerialNumber values(9,'Mike',22,38585);
Query OK, 1 row affected (0.11 sec)
mysql> insert into addColumnToCountAsSerialNumber values(15,'Sam',25,38586);
Query OK, 1 row affected (0.16 sec)
mysql> insert into addColumnToCountAsSerialNumber values(20,'Bob',26,43544);
Query OK, 1 row affected (0.17 sec)
mysql> insert into addColumnToCountAsSerialNumber values(39,'Larry',29,485886);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from addColumnToCountAsSerialNumber ;
The following is the output:
+------+-------+------+--------+
| Id | Name | Age | Salary |
+------+-------+------+--------+
| 10 | John | 23 | 8576 |
| 12 | Carol | 21 | 4686 |
| 9 | Mike | 22 | 38585 |
| 15 | Sam | 25 | 38586 |
| 20 | Bob | 26 | 43544 |
| 39 | Larry | 29 | 485886 |
+------+-------+------+--------+
6 rows in set (0.00 sec)
The following is the query to count each row as a serial number:
mysql> select @globalVar:=@globalVar+1 RowCount,tblColumns.*
-> from (select @globalVar:=0) initializeGlobalVariable,addColumnToCountAsSerialNumber tblColumns;
The following is the output displaying the count in a new column “RowCount”:
+----------+------+-------+------+--------+
| RowCount | Id | Name | Age | Salary |
+----------+------+-------+------+--------+
| 1 | 10 | John | 23 | 8576 |
| 2 | 12 | Carol | 21 | 4686 |
| 3 | 9 | Mike | 22 | 38585 |
| 4 | 15 | Sam | 25 | 38586 |
| 5 | 20 | Bob | 26 | 43544 |
| 6 | 39 | Larry | 29 | 485886 |
+----------+------+-------+------+--------+
6 rows in set (0.06 sec)
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "To add a new column that counts the number of rows as serial number, you can use the global variable in select statement."
},
{
"code": null,
"e": 1250,
"s": 1184,
"text": "Let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1425,
"s": 1250,
"text": "mysql> create table addColumnToCountAsSerialNumber\n -> (\n -> Id int,\n -> Name varchar(20),\n -> Age int,\n -> Salary int\n -> );\nQuery OK, 0 rows affected (0.80 sec)"
},
{
"code": null,
"e": 1505,
"s": 1425,
"text": "Insert some records in the table using insert command. The query is as follows:"
},
{
"code": null,
"e": 2187,
"s": 1505,
"text": "mysql> insert into addColumnToCountAsSerialNumber values(10,'John',23,8576);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into addColumnToCountAsSerialNumber values(12,'Carol',21,4686);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into addColumnToCountAsSerialNumber values(9,'Mike',22,38585);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into addColumnToCountAsSerialNumber values(15,'Sam',25,38586);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into addColumnToCountAsSerialNumber values(20,'Bob',26,43544);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into addColumnToCountAsSerialNumber values(39,'Larry',29,485886);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2271,
"s": 2187,
"text": "Display all records from the table using select statement. The query is as follows:"
},
{
"code": null,
"e": 2324,
"s": 2271,
"text": "mysql> select *from addColumnToCountAsSerialNumber ;"
},
{
"code": null,
"e": 2353,
"s": 2324,
"text": "The following is the output:"
},
{
"code": null,
"e": 2708,
"s": 2353,
"text": "+------+-------+------+--------+\n| Id | Name | Age | Salary |\n+------+-------+------+--------+\n| 10 | John | 23 | 8576 |\n| 12 | Carol | 21 | 4686 |\n| 9 | Mike | 22 | 38585 |\n| 15 | Sam | 25 | 38586 |\n| 20 | Bob | 26 | 43544 |\n| 39 | Larry | 29 | 485886 |\n+------+-------+------+--------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2773,
"s": 2708,
"text": "The following is the query to count each row as a serial number:"
},
{
"code": null,
"e": 2936,
"s": 2773,
"text": "mysql> select @globalVar:=@globalVar+1 RowCount,tblColumns.*\n -> from (select @globalVar:=0) initializeGlobalVariable,addColumnToCountAsSerialNumber tblColumns;"
},
{
"code": null,
"e": 3013,
"s": 2936,
"text": "The following is the output displaying the count in a new column “RowCount”:"
},
{
"code": null,
"e": 3478,
"s": 3013,
"text": "+----------+------+-------+------+--------+\n| RowCount | Id | Name | Age | Salary |\n+----------+------+-------+------+--------+\n| 1 | 10 | John | 23 | 8576 |\n| 2 | 12 | Carol | 21 | 4686 |\n| 3 | 9 | Mike | 22 | 38585 |\n| 4 | 15 | Sam | 25 | 38586 |\n| 5 | 20 | Bob | 26 | 43544 |\n| 6 | 39 | Larry | 29 | 485886 |\n+----------+------+-------+------+--------+\n6 rows in set (0.06 sec)"
}
] |
How to implementing start Foreground for a service?
|
Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy
This example demonstrate about How to implementing start Foreground for a service.
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"?>
<android.support.constraint.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">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken text view, when user click on text view, it will start startForeground().
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isMyServiceRunning(service.class)) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this, service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this, service.class));
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –
package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class service extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show();
String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
return START_STICKY;
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}
In the above code we have used notification channel and notification builder as shown below –
String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
To start and stop foreground use the following code –
startForeground(1337, notification);
stopForeground(true);
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<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>
<service android:name = ".service"/>
</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 –
In the above result is an initial screen, Click on Text view, it will start Notification service as shown below –In the above result, service is startd now click on text view, it will stop notification service as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy"
},
{
"code": null,
"e": 1328,
"s": 1245,
"text": "This example demonstrate about How to implementing start Foreground for a service."
},
{
"code": null,
"e": 1457,
"s": 1328,
"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": 1522,
"s": 1457,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2363,
"s": 1522,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\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/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2470,
"s": 2363,
"text": "In the above code, we have taken text view, when user click on text view, it will start startForeground()."
},
{
"code": null,
"e": 2527,
"s": 2470,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3958,
"s": 2527,
"text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isMyServiceRunning(service.class)) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this, service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this, service.class));\n }\n }\n });\n }\n private boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n}"
},
{
"code": null,
"e": 4152,
"s": 3958,
"text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –"
},
{
"code": null,
"e": 6421,
"s": 4152,
"text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.media.MediaPlayer;\nimport android.os.Build;\nimport android.os.IBinder;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.NotificationCompat;\nimport android.widget.Toast;\npublic class service extends Service {\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public void onCreate() {\n super.onCreate();\n }\n @TargetApi(Build.VERSION_CODES.O)\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Notification Service started by user.\", Toast.LENGTH_LONG).show();\n String NOTIFICATION_CHANNEL_ID = \"com.example.andy.myapplication\";\n String channelName = \"My Background Service\";\n NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);\n chan.setLightColor(Color.BLUE);\n chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);\n NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n assert manager != null;\n manager.createNotificationChannel(chan);\n Intent notificationIntent = new Intent(this, MainActivity.class);\n PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);\n Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)\n .setSmallIcon(R.mipmap.ic_launcher)\n .setContentTitle(\"My Awesome App\")\n .setContentIntent(pendingIntent).build();\n startForeground(1337, notification);\n return START_STICKY;\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n public void onDestroy() {\n super.onDestroy();\n stopForeground(true);\n Toast.makeText(this, \"Notification Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}"
},
{
"code": null,
"e": 6515,
"s": 6421,
"text": "In the above code we have used notification channel and notification builder as shown below –"
},
{
"code": null,
"e": 7404,
"s": 6515,
"text": "String NOTIFICATION_CHANNEL_ID = \"com.example.andy.myapplication\";\nString channelName = \"My Background Service\";\nNotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);\nchan.setLightColor(Color.BLUE);\nchan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);\nNotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\nassert manager != null;\nmanager.createNotificationChannel(chan);\nIntent notificationIntent = new Intent(this, MainActivity.class);\nPendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);\nNotification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)\n.setSmallIcon(R.mipmap.ic_launcher)\n.setContentTitle(\"My Awesome App\")\n.setContentIntent(pendingIntent).build();\nstartForeground(1337, notification);"
},
{
"code": null,
"e": 7458,
"s": 7404,
"text": "To start and stop foreground use the following code –"
},
{
"code": null,
"e": 7517,
"s": 7458,
"text": "startForeground(1337, notification);\nstopForeground(true);"
},
{
"code": null,
"e": 7565,
"s": 7517,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 8323,
"s": 7565,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\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 <service android:name = \".service\"/>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8670,
"s": 8323,
"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": 8897,
"s": 8670,
"text": "In the above result is an initial screen, Click on Text view, it will start Notification service as shown below –In the above result, service is startd now click on text view, it will stop notification service as shown below -"
},
{
"code": null,
"e": 8937,
"s": 8897,
"text": "Click here to download the project code"
}
] |
Latin Square in Python
|
The Latin square is a matrix that has a special pattern. Let's see different examples to examine the pattern.
1 2
2 1
1 2 3
3 1 2
2 3 1
1 2 3 4
4 1 2 3
3 4 1 2
2 3 4 1
The Latin square that you get will be of different size as you notice in the above examples. But, if you carefully observe the above matrices' pattern, you will find out that the last number of the previous row comes as the first element of the next row.
That's the pattern hidden in Latin square. We have to write the program that generates the above matrix for the input n.
Initialise the n with any number you like.
Initialise a number with the value n + 1 call it as first_half_end.
Write a loop that iterates from 1 to n both inclusive.Assign the value of first_half_end to a variable called first_half_start.Write a loop until first_half_start reaches to the value n.Print the iterating variable i.e.., first_half_start.Write a loop that iterates from 1 to first_half_end.Print the iterating variable.Decrement the value of first_half_end by 1.Move the next row.
Assign the value of first_half_end to a variable called first_half_start.
Write a loop until first_half_start reaches to the value n.Print the iterating variable i.e.., first_half_start.
Print the iterating variable i.e.., first_half_start.
Write a loop that iterates from 1 to first_half_end.Print the iterating variable.
Print the iterating variable.
Decrement the value of first_half_end by 1.
Move the next row.
Following is the implementation of the above algorithm in Python
def generateLatinSquare(n):
first_half_end = n + 1
for i in range(1, n + 1):
first_half_start = first_half_end
while (first_half_start <= n):
print(first_half_start, end=" ")
first_half_start += 1
for second_half_start in range(1, first_half_end):
print(second_half_start, end=" ")
first_half_end -= 1
print()
print()
if __name__ == "__main__":
generateLatinSquare(2)
generateLatinSquare(3)
generateLatinSquare(4)
If you run the above code, then you will get the following result.
1 2
2 1
1 2 3
3 1 2
2 3 1
1 2 3 4
4 1 2 3
3 4 1 2
2 3 4 1
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "The Latin square is a matrix that has a special pattern. Let's see different examples to examine the pattern."
},
{
"code": null,
"e": 1234,
"s": 1172,
"text": "1 2\n2 1\n\n1 2 3\n3 1 2\n2 3 1\n\n1 2 3 4\n4 1 2 3\n3 4 1 2\n2 3 4 1\n\n"
},
{
"code": null,
"e": 1489,
"s": 1234,
"text": "The Latin square that you get will be of different size as you notice in the above examples. But, if you carefully observe the above matrices' pattern, you will find out that the last number of the previous row comes as the first element of the next row."
},
{
"code": null,
"e": 1610,
"s": 1489,
"text": "That's the pattern hidden in Latin square. We have to write the program that generates the above matrix for the input n."
},
{
"code": null,
"e": 1653,
"s": 1610,
"text": "Initialise the n with any number you like."
},
{
"code": null,
"e": 1721,
"s": 1653,
"text": "Initialise a number with the value n + 1 call it as first_half_end."
},
{
"code": null,
"e": 2103,
"s": 1721,
"text": "Write a loop that iterates from 1 to n both inclusive.Assign the value of first_half_end to a variable called first_half_start.Write a loop until first_half_start reaches to the value n.Print the iterating variable i.e.., first_half_start.Write a loop that iterates from 1 to first_half_end.Print the iterating variable.Decrement the value of first_half_end by 1.Move the next row."
},
{
"code": null,
"e": 2177,
"s": 2103,
"text": "Assign the value of first_half_end to a variable called first_half_start."
},
{
"code": null,
"e": 2290,
"s": 2177,
"text": "Write a loop until first_half_start reaches to the value n.Print the iterating variable i.e.., first_half_start."
},
{
"code": null,
"e": 2344,
"s": 2290,
"text": "Print the iterating variable i.e.., first_half_start."
},
{
"code": null,
"e": 2426,
"s": 2344,
"text": "Write a loop that iterates from 1 to first_half_end.Print the iterating variable."
},
{
"code": null,
"e": 2456,
"s": 2426,
"text": "Print the iterating variable."
},
{
"code": null,
"e": 2500,
"s": 2456,
"text": "Decrement the value of first_half_end by 1."
},
{
"code": null,
"e": 2519,
"s": 2500,
"text": "Move the next row."
},
{
"code": null,
"e": 2584,
"s": 2519,
"text": "Following is the implementation of the above algorithm in Python"
},
{
"code": null,
"e": 3076,
"s": 2584,
"text": "def generateLatinSquare(n):\n first_half_end = n + 1\n\n for i in range(1, n + 1):\n first_half_start = first_half_end\n while (first_half_start <= n):\n print(first_half_start, end=\" \")\n first_half_start += 1\n\n for second_half_start in range(1, first_half_end):\n print(second_half_start, end=\" \")\n first_half_end -= 1\n print()\n print()\n\nif __name__ == \"__main__\":\n generateLatinSquare(2)\n generateLatinSquare(3)\n generateLatinSquare(4)"
},
{
"code": null,
"e": 3143,
"s": 3076,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3203,
"s": 3143,
"text": "1 2\n2 1\n\n1 2 3\n3 1 2\n2 3 1\n\n1 2 3 4\n4 1 2 3\n3 4 1 2\n2 3 4 1"
}
] |
Python | Convert location coordinates to tuple - GeeksforGeeks
|
29 Apr, 2022
Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let’s discuss certain ways in which this task can be performed.
Method #1 :
Using tuple() + float() + split() + map() The combination of above functions can be used to perform this task. In this, we first split the two parts of coordinates into a list, apply float function to each of them using float() and map() and lastly it is converted to tuple using tuple().
Python3
# Python3 code to demonstrate working of# Convert location coordinates to tuple# Using tuple() + float() + split() + map() # Initializing stringtest_str = "44.6463, -49.583" # printing original stringprint("The original string is : " + str(test_str)) # Convert location coordinates to tuple# Using tuple() + float() + split() + map()res = tuple(map(float, test_str.split(', '))) # printing resultprint("The coordinates after conversion to tuple are : " + str(res))
The original string is : 44.6463, -49.583
The coordinates after conversion to tuple are : (44.6463, -49.583)
Method #2 :
Using eval() This is the one-liner and recommended method to perform this particular task. In this, the eval(), internally detects the string and converts to floating point number separated as tuple elements.
Python3
# Python3 code to demonstrate working of# Convert location coordinates to tuple# Using eval() # Initializing stringtest_str = "44.6463, -49.583" # printing original stringprint("The original string is : " + str(test_str)) # Convert location coordinates to tuple# Using eval()res = eval(test_str) # printing resultprint("The coordinates after conversion to tuple are : " + str(res))
The original string is : 44.6463, -49.583
The coordinates after conversion to tuple are : (44.6463, -49.583)
rkbhola5
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 24659,
"s": 24390,
"text": "Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let’s discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 24672,
"s": 24659,
"text": "Method #1 : "
},
{
"code": null,
"e": 24962,
"s": 24672,
"text": "Using tuple() + float() + split() + map() The combination of above functions can be used to perform this task. In this, we first split the two parts of coordinates into a list, apply float function to each of them using float() and map() and lastly it is converted to tuple using tuple(). "
},
{
"code": null,
"e": 24970,
"s": 24962,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert location coordinates to tuple# Using tuple() + float() + split() + map() # Initializing stringtest_str = \"44.6463, -49.583\" # printing original stringprint(\"The original string is : \" + str(test_str)) # Convert location coordinates to tuple# Using tuple() + float() + split() + map()res = tuple(map(float, test_str.split(', '))) # printing resultprint(\"The coordinates after conversion to tuple are : \" + str(res))",
"e": 25435,
"s": 24970,
"text": null
},
{
"code": null,
"e": 25544,
"s": 25435,
"text": "The original string is : 44.6463, -49.583\nThe coordinates after conversion to tuple are : (44.6463, -49.583)"
},
{
"code": null,
"e": 25559,
"s": 25544,
"text": " Method #2 : "
},
{
"code": null,
"e": 25769,
"s": 25559,
"text": "Using eval() This is the one-liner and recommended method to perform this particular task. In this, the eval(), internally detects the string and converts to floating point number separated as tuple elements. "
},
{
"code": null,
"e": 25777,
"s": 25769,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert location coordinates to tuple# Using eval() # Initializing stringtest_str = \"44.6463, -49.583\" # printing original stringprint(\"The original string is : \" + str(test_str)) # Convert location coordinates to tuple# Using eval()res = eval(test_str) # printing resultprint(\"The coordinates after conversion to tuple are : \" + str(res))",
"e": 26159,
"s": 25777,
"text": null
},
{
"code": null,
"e": 26268,
"s": 26159,
"text": "The original string is : 44.6463, -49.583\nThe coordinates after conversion to tuple are : (44.6463, -49.583)"
},
{
"code": null,
"e": 26277,
"s": 26268,
"text": "rkbhola5"
},
{
"code": null,
"e": 26299,
"s": 26277,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 26306,
"s": 26299,
"text": "Python"
},
{
"code": null,
"e": 26322,
"s": 26306,
"text": "Python Programs"
},
{
"code": null,
"e": 26420,
"s": 26322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26452,
"s": 26420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26494,
"s": 26452,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26536,
"s": 26494,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26592,
"s": 26536,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26614,
"s": 26592,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26636,
"s": 26614,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26675,
"s": 26636,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26721,
"s": 26675,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26759,
"s": 26721,
"text": "Python | Convert a list to dictionary"
}
] |
Functional Programming in R with purrr | by Thomas Mock | Towards Data Science
|
When you first started in R you likely were writing simple code.
print("Hello world!")5 * 6x <- c(1, 2, 3, 4, 5)
This is great, you are learning about strings, math, and vectors in R!
Then you get started with some basic analyses. You want to see if you can find the mean of some numbers.
employee <- c('John Doe','Peter Gynn','Jolie Hope')salary <- c(21000, 23400, 26800)startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))# form dataframe and take mean of salary columnemploy_data <- data.frame(employee, salary, startdate)mean(employ_data$salary)# output[1] 23733.33
Eventually you hopefully get exposed to the tidyverse, and you find how this “ opinionated collection of R packages designed for data science” makes data analysis in R easier and more readable!
mtcars %>% group_by(cyl) %>% summarize(mean(mpg))# A tibble: 3 x 2 cyl `mean(mpg)` <dbl> <dbl>1 4.00 26.72 6.00 19.73 8.00 15.1
Everything is going great! You’ve likely replaced Excel at this point, and potentially SPSS or some other statistical software suite! But then you run into a problem where you need to use a function repeatedly.
You could use something like the following code to calculate one-way ANOVAs for some dependent variables and a set independent variable:
aov_mpg <- aov(mpg ~ factor(cyl), data = mtcars)summary(aov_mpg)aov_disp <- aov(disp ~ factor(cyll), data = mtcars)summary(aov_disp)aov_hp <- aov(hp ~ factor(cyl), data = mrcars)summry(aov_hpp)aov_wt <- aov(wt ~ factor(cyl), datas = mtcars)summary(aov_wt)
But you copy-pasted code 3x, and oops you made some minor misspelling mistakes which throws an error! (The above code leads to errors!)
Also, what if you realized that you wanted to actually run these ANOVAs for number of gears instead of number of cylinders? You would have to go back and change the factor(cyl) call to factor(gear) 4x! This is not very efficient, and you’re more likely to end up with mistakes as you have to type everything multiple times!
How about another example.
Let’s calculate the R-squared values for the linear relationship between Weight and Miles per Gallon, according to the number of Cylinders.
I have written code below that does this for 4 cylinder cars from the mtcars dataset. This is a worst case scenario, you know some dplyr code (dplyr::filter), but are not comfortable with the pipe. That’s fine, you accomplish your goal but a lot of coding! You would have to duplicate this code for 6 cylinder and 8 cylinder cars, for even more code...
# create df for 4 cylinder carscyl_4 <- filter(mtcars, cyl == 4)# create a linear model on 4 cyl carslm_4 <- lm(mpg ~ wt, data = cyl_4)# get the summlm_4_summary <- summary(lm_4)# get the r.squared valuelm_4_r_squared <- lm_4_summary["r.squared"]# check the valuelm_4cyl_r_squared# output$r.squared[1] 0.5086326
Alternatively, you could do the same thing with the pipe. A lot less typing, but to do this for all 3 subsets means we have to copy paste multiple times, so if you end up wanting to do this as a linear model of mpg ~ disp in addition to mpg ~ wt, you would have to duplicate the code 3 more times and change it 3 more times. This may not seem like a big deal, but eventually is a huge deal once you start to scale up the code (say 10+ times or 100+ times, etc).
lm_4cyl_rsquared <- mtcars %>% filter(cyl == 4) %>% lm(mpg ~ wt, data = .) %>% summary() %>% .$"r.squared"# output[1] 0.5086326
To solve this issue of minimizing repetition with further replication, we can dive straight into purrr! To read more about purrr Hadley Wickham recommends the iteration chapter from “R for Data Science” or alternatively you can look at the purrr documentation. Lastly, Jenny Bryan has a great purrr tutorial here. You can load purrr by itself, but it is also loaded as part of the tidyverse library.
purrr allows you to map functions to data. Appropriately the basic function in purrr is called map()! The map functions transform their input by applying a function to each element and returning a vector the same length as the input.
The base arguments for map() are:.x — A list or atomic vector (logical, integer, double/numeric, and character).f — A function, formula, or atomic vector
Basically map() takes a function (.f) and applies it to data (.x).
Going back to our example of grabbing the R-squared from a linear model, we use the following code with purrr.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl("r.squared")# output4 6 8 0.5086326 0.4645102 0.4229655
This generates an output from all 3 of our linear models according to number of cylinders in 5 lines of code! This is the beauty of purrr, efficient scaling of functions!
Let’s break down our linear model R-squared code.
We take the mtcars dataset, split it into data subsets according to the number of cylinders, apply a linear model of mpg by wt to each subset of data, apply a summary function and then pull out the r.squared value. However, while purrr is readable, we need to cover a few quirks of using it.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl("r.squared")# output4 6 8 0.5086326 0.4645102 0.4229655
For our code here you may have noticed we have a “.” placed twice within the code. This is a placeholder for the data, we can see this below. The “.” indicate the left-hand side data, or in this case mtcars. Our split call splits the mtcars dataframe into 3 dataframes, each stored within a list. This may seem odd, but it allows map to cycle through our 3 dataframes and replicate the lm() function on each of them individually.
# pipedmtcars %>% split(.$cyl)# base Rsplit(mtcars, mtcars$cyl)# outputList of 3 $ 4:'data.frame': 11 obs. of 11 variables: ..$ mpg : num [1:11] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26... ..$ cyl : num [1:11] 4 4 4 4 4 4 4 4 4 4 ... ..$ disp: num [1:11] 108 146.7 140.8 78.7 75.7 ... ..$ hp : num [1:11] 93 62 95 66 52 65 97 66 91 113 ... ..$ drat: num [1:11] 3.85 3.69 3.92 4.08 4.93 4.22 3.7 4.08 ... ..$ wt : num [1:11] 2.32 3.19 3.15 2.2 1.61 ... ..$ qsec: num [1:11] 18.6 20 22.9 19.5 18.5 ... ..$ vs : num [1:11] 1 1 1 1 1 1 1 1 0 1 ... ..$ am : num [1:11] 1 0 0 1 1 1 0 1 1 1 ... ..$ gear: num [1:11] 4 4 4 4 4 4 3 4 5 5 ... ..$ carb: num [1:11] 1 2 2 1 2 1 1 1 2 2 ... $ 6:'data.frame': 7 obs. of 11 variables: ..$ mpg : num [1:7] 21 21 21.4 18.1 19.2 17.8 19.7 ..$ cyl : num [1:7] 6 6 6 6 6 6 6 ..$ disp: num [1:7] 160 160 258 225 168 ... ..$ hp : num [1:7] 110 110 110 105 123 123 175 ..$ drat: num [1:7] 3.9 3.9 3.08 2.76 3.92 3.92 3.62 ..$ wt : num [1:7] 2.62 2.88 3.21 3.46 3.44 ... ..$ qsec: num [1:7] 16.5 17 19.4 20.2 18.3 ... ..$ vs : num [1:7] 0 0 1 1 1 1 0 ..$ am : num [1:7] 1 1 0 0 0 0 1 ..$ gear: num [1:7] 4 4 3 3 4 4 5 ..$ carb: num [1:7] 4 4 1 1 4 4 6 $ 8:'data.frame': 14 obs. of 11 variables: ..$ mpg : num [1:14] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7... ..$ cyl : num [1:14] 8 8 8 8 8 8 8 8 8 8 ... ..$ disp: num [1:14] 360 360 276 276 276 ... ..$ hp : num [1:14] 175 245 180 180 180 205 215 230 150 150 ... ..$ drat: num [1:14] 3.15 3.21 3.07 3.07 3.07 2.93 3 3.23 2.76... ..$ wt : num [1:14] 3.44 3.57 4.07 3.73 3.78 ... ..$ qsec: num [1:14] 17 15.8 17.4 17.6 18 ... ..$ vs : num [1:14] 0 0 0 0 0 0 0 0 0 0 ... ..$ am : num [1:14] 0 0 0 0 0 0 0 0 0 0 ... ..$ gear: num [1:14] 3 3 3 3 3 3 3 3 3 3 ... ..$ carb: num [1:14] 2 4 3 3 3 4 4 4 2 2 ...
Similarily, the “.” in or first map call is a placeholder for data, but in this case it will cycle through our list of 3 dataframes generated by the previous pipe. You can see that we get a list of 3 lm() outputs, we need to map a summary call to each of these to get access to R-squared.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .))# output$`4`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 39.571 -5.647$`6`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 28.41 -2.78$`8`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 23.868 -2.192
We next map our summary function to each of the list items to get cleaner outputs with R-squared values. We now have the rest of our statistical output, including p values and R-squared.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary)# output$`4`Call:lm(formula = mpg ~ wt, data = .)Residuals: Min 1Q Median 3Q Max -4.1513 -1.9795 -0.6272 1.9299 5.2523Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 39.571 4.347 9.104 7.77e-06 ***wt -5.647 1.850 -3.052 0.0137 * ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 3.332 on 9 degrees of freedomMultiple R-squared: 0.5086, Adjusted R-squared: 0.454 F-statistic: 9.316 on 1 and 9 DF, p-value: 0.01374$`6`Call:lm(formula = mpg ~ wt, data = .)Residuals: Mazda RX4 Mazda RX4 Wag Hornet 4 Drive Valiant Merc 280 -0.1250 0.5840 1.9292 -0.6897 0.3547 Merc 280C Ferrari Dino -1.0453 -1.0080Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 28.409 4.184 6.789 0.00105 **wt -2.780 1.335 -2.083 0.09176 . ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 1.165 on 5 degrees of freedomMultiple R-squared: 0.4645, Adjusted R-squared: 0.3574 F-statistic: 4.337 on 1 and 5 DF, p-value: 0.09176$`8`Call:lm(formula = mpg ~ wt, data = .)Residuals: Min 1Q Median 3Q Max -2.1491 -1.4664 -0.8458 1.5711 3.7619Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 23.8680 3.0055 7.942 4.05e-06 ***wt -2.1924 0.7392 -2.966 0.0118 * ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 2.024 on 12 degrees of freedomMultiple R-squared: 0.423, Adjusted R-squared: 0.3749 F-statistic: 8.796 on 1 and 12 DF, p-value: 0.01179
Our last map is a bit different. You can see we use map_dbl this time. This indicates we want our output to be a dbl or numeric outcome. We get nice named numbers!
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl("r.squared")# output 4 6 8 0.5086326 0.4645102 0.4229655
If we had not indicated map_dbl, but instead used map we would get a list of the same outcome.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map("r.squared")# output$`4`[1] 0.5086326$`6`[1] 0.4645102$`8`[1] 0.4229655
You could also use map_dfr which binds the outputs into rows of a dataframe.
mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dfr("r.squared")# output# A tibble: 1 x 3 `4` `6` `8` <dbl> <dbl> <dbl>1 0.509 0.465 0.423
There are limitless applications of purrr and other functions within purrr that greatly empower your functional programming in R. I hope that this guide motivates you to add purrr to your toolbox and explore this useful tidyverse package!
As a brief teaser to some more applications of purrr, I’ll leave you with this example. I mentioned calculating ANOVAs across multiple variables at the beginning. Break down this example on your own and see what you think! (You can copy paste this code into R, but need to load the tidyverse and broom packages first).
mtcars %>% mutate(cyl = factor(cyl), am = factor(am)) %>% select(mpg, disp, hp) %>% map(~ aov(.x ~ cyl * am, data = mtcars)) %>% map_dfr(~ broom::tidy(.), .id = 'source') %>% mutate(p.value = round(p.value, 5))
In closing, I’d like to thank several #r4ds slack community members for their help in my personal understanding of purrr: Frank Farach, Michael Kuehn, and Kent Johnson.
If you are interested in joining this community led by Jesse Maegan check out her post here and May the Force be with you!
|
[
{
"code": null,
"e": 237,
"s": 172,
"text": "When you first started in R you likely were writing simple code."
},
{
"code": null,
"e": 285,
"s": 237,
"text": "print(\"Hello world!\")5 * 6x <- c(1, 2, 3, 4, 5)"
},
{
"code": null,
"e": 356,
"s": 285,
"text": "This is great, you are learning about strings, math, and vectors in R!"
},
{
"code": null,
"e": 461,
"s": 356,
"text": "Then you get started with some basic analyses. You want to see if you can find the mean of some numbers."
},
{
"code": null,
"e": 750,
"s": 461,
"text": "employee <- c('John Doe','Peter Gynn','Jolie Hope')salary <- c(21000, 23400, 26800)startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))# form dataframe and take mean of salary columnemploy_data <- data.frame(employee, salary, startdate)mean(employ_data$salary)# output[1] 23733.33"
},
{
"code": null,
"e": 944,
"s": 750,
"text": "Eventually you hopefully get exposed to the tidyverse, and you find how this “ opinionated collection of R packages designed for data science” makes data analysis in R easier and more readable!"
},
{
"code": null,
"e": 1110,
"s": 944,
"text": "mtcars %>% group_by(cyl) %>% summarize(mean(mpg))# A tibble: 3 x 2 cyl `mean(mpg)` <dbl> <dbl>1 4.00 26.72 6.00 19.73 8.00 15.1"
},
{
"code": null,
"e": 1321,
"s": 1110,
"text": "Everything is going great! You’ve likely replaced Excel at this point, and potentially SPSS or some other statistical software suite! But then you run into a problem where you need to use a function repeatedly."
},
{
"code": null,
"e": 1458,
"s": 1321,
"text": "You could use something like the following code to calculate one-way ANOVAs for some dependent variables and a set independent variable:"
},
{
"code": null,
"e": 1714,
"s": 1458,
"text": "aov_mpg <- aov(mpg ~ factor(cyl), data = mtcars)summary(aov_mpg)aov_disp <- aov(disp ~ factor(cyll), data = mtcars)summary(aov_disp)aov_hp <- aov(hp ~ factor(cyl), data = mrcars)summry(aov_hpp)aov_wt <- aov(wt ~ factor(cyl), datas = mtcars)summary(aov_wt)"
},
{
"code": null,
"e": 1850,
"s": 1714,
"text": "But you copy-pasted code 3x, and oops you made some minor misspelling mistakes which throws an error! (The above code leads to errors!)"
},
{
"code": null,
"e": 2174,
"s": 1850,
"text": "Also, what if you realized that you wanted to actually run these ANOVAs for number of gears instead of number of cylinders? You would have to go back and change the factor(cyl) call to factor(gear) 4x! This is not very efficient, and you’re more likely to end up with mistakes as you have to type everything multiple times!"
},
{
"code": null,
"e": 2201,
"s": 2174,
"text": "How about another example."
},
{
"code": null,
"e": 2341,
"s": 2201,
"text": "Let’s calculate the R-squared values for the linear relationship between Weight and Miles per Gallon, according to the number of Cylinders."
},
{
"code": null,
"e": 2694,
"s": 2341,
"text": "I have written code below that does this for 4 cylinder cars from the mtcars dataset. This is a worst case scenario, you know some dplyr code (dplyr::filter), but are not comfortable with the pipe. That’s fine, you accomplish your goal but a lot of coding! You would have to duplicate this code for 6 cylinder and 8 cylinder cars, for even more code..."
},
{
"code": null,
"e": 3006,
"s": 2694,
"text": "# create df for 4 cylinder carscyl_4 <- filter(mtcars, cyl == 4)# create a linear model on 4 cyl carslm_4 <- lm(mpg ~ wt, data = cyl_4)# get the summlm_4_summary <- summary(lm_4)# get the r.squared valuelm_4_r_squared <- lm_4_summary[\"r.squared\"]# check the valuelm_4cyl_r_squared# output$r.squared[1] 0.5086326"
},
{
"code": null,
"e": 3468,
"s": 3006,
"text": "Alternatively, you could do the same thing with the pipe. A lot less typing, but to do this for all 3 subsets means we have to copy paste multiple times, so if you end up wanting to do this as a linear model of mpg ~ disp in addition to mpg ~ wt, you would have to duplicate the code 3 more times and change it 3 more times. This may not seem like a big deal, but eventually is a huge deal once you start to scale up the code (say 10+ times or 100+ times, etc)."
},
{
"code": null,
"e": 3603,
"s": 3468,
"text": "lm_4cyl_rsquared <- mtcars %>% filter(cyl == 4) %>% lm(mpg ~ wt, data = .) %>% summary() %>% .$\"r.squared\"# output[1] 0.5086326"
},
{
"code": null,
"e": 4003,
"s": 3603,
"text": "To solve this issue of minimizing repetition with further replication, we can dive straight into purrr! To read more about purrr Hadley Wickham recommends the iteration chapter from “R for Data Science” or alternatively you can look at the purrr documentation. Lastly, Jenny Bryan has a great purrr tutorial here. You can load purrr by itself, but it is also loaded as part of the tidyverse library."
},
{
"code": null,
"e": 4237,
"s": 4003,
"text": "purrr allows you to map functions to data. Appropriately the basic function in purrr is called map()! The map functions transform their input by applying a function to each element and returning a vector the same length as the input."
},
{
"code": null,
"e": 4391,
"s": 4237,
"text": "The base arguments for map() are:.x — A list or atomic vector (logical, integer, double/numeric, and character).f — A function, formula, or atomic vector"
},
{
"code": null,
"e": 4458,
"s": 4391,
"text": "Basically map() takes a function (.f) and applies it to data (.x)."
},
{
"code": null,
"e": 4569,
"s": 4458,
"text": "Going back to our example of grabbing the R-squared from a linear model, we use the following code with purrr."
},
{
"code": null,
"e": 4732,
"s": 4569,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl(\"r.squared\")# output4 6 8 0.5086326 0.4645102 0.4229655"
},
{
"code": null,
"e": 4903,
"s": 4732,
"text": "This generates an output from all 3 of our linear models according to number of cylinders in 5 lines of code! This is the beauty of purrr, efficient scaling of functions!"
},
{
"code": null,
"e": 4953,
"s": 4903,
"text": "Let’s break down our linear model R-squared code."
},
{
"code": null,
"e": 5245,
"s": 4953,
"text": "We take the mtcars dataset, split it into data subsets according to the number of cylinders, apply a linear model of mpg by wt to each subset of data, apply a summary function and then pull out the r.squared value. However, while purrr is readable, we need to cover a few quirks of using it."
},
{
"code": null,
"e": 5408,
"s": 5245,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl(\"r.squared\")# output4 6 8 0.5086326 0.4645102 0.4229655"
},
{
"code": null,
"e": 5838,
"s": 5408,
"text": "For our code here you may have noticed we have a “.” placed twice within the code. This is a placeholder for the data, we can see this below. The “.” indicate the left-hand side data, or in this case mtcars. Our split call splits the mtcars dataframe into 3 dataframes, each stored within a list. This may seem odd, but it allows map to cycle through our 3 dataframes and replicate the lm() function on each of them individually."
},
{
"code": null,
"e": 7668,
"s": 5838,
"text": "# pipedmtcars %>% split(.$cyl)# base Rsplit(mtcars, mtcars$cyl)# outputList of 3 $ 4:'data.frame': 11 obs. of 11 variables: ..$ mpg : num [1:11] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26... ..$ cyl : num [1:11] 4 4 4 4 4 4 4 4 4 4 ... ..$ disp: num [1:11] 108 146.7 140.8 78.7 75.7 ... ..$ hp : num [1:11] 93 62 95 66 52 65 97 66 91 113 ... ..$ drat: num [1:11] 3.85 3.69 3.92 4.08 4.93 4.22 3.7 4.08 ... ..$ wt : num [1:11] 2.32 3.19 3.15 2.2 1.61 ... ..$ qsec: num [1:11] 18.6 20 22.9 19.5 18.5 ... ..$ vs : num [1:11] 1 1 1 1 1 1 1 1 0 1 ... ..$ am : num [1:11] 1 0 0 1 1 1 0 1 1 1 ... ..$ gear: num [1:11] 4 4 4 4 4 4 3 4 5 5 ... ..$ carb: num [1:11] 1 2 2 1 2 1 1 1 2 2 ... $ 6:'data.frame': 7 obs. of 11 variables: ..$ mpg : num [1:7] 21 21 21.4 18.1 19.2 17.8 19.7 ..$ cyl : num [1:7] 6 6 6 6 6 6 6 ..$ disp: num [1:7] 160 160 258 225 168 ... ..$ hp : num [1:7] 110 110 110 105 123 123 175 ..$ drat: num [1:7] 3.9 3.9 3.08 2.76 3.92 3.92 3.62 ..$ wt : num [1:7] 2.62 2.88 3.21 3.46 3.44 ... ..$ qsec: num [1:7] 16.5 17 19.4 20.2 18.3 ... ..$ vs : num [1:7] 0 0 1 1 1 1 0 ..$ am : num [1:7] 1 1 0 0 0 0 1 ..$ gear: num [1:7] 4 4 3 3 4 4 5 ..$ carb: num [1:7] 4 4 1 1 4 4 6 $ 8:'data.frame': 14 obs. of 11 variables: ..$ mpg : num [1:14] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7... ..$ cyl : num [1:14] 8 8 8 8 8 8 8 8 8 8 ... ..$ disp: num [1:14] 360 360 276 276 276 ... ..$ hp : num [1:14] 175 245 180 180 180 205 215 230 150 150 ... ..$ drat: num [1:14] 3.15 3.21 3.07 3.07 3.07 2.93 3 3.23 2.76... ..$ wt : num [1:14] 3.44 3.57 4.07 3.73 3.78 ... ..$ qsec: num [1:14] 17 15.8 17.4 17.6 18 ... ..$ vs : num [1:14] 0 0 0 0 0 0 0 0 0 0 ... ..$ am : num [1:14] 0 0 0 0 0 0 0 0 0 0 ... ..$ gear: num [1:14] 3 3 3 3 3 3 3 3 3 3 ... ..$ carb: num [1:14] 2 4 3 3 3 4 4 4 2 2 ..."
},
{
"code": null,
"e": 7957,
"s": 7668,
"text": "Similarily, the “.” in or first map call is a placeholder for data, but in this case it will cycle through our list of 3 dataframes generated by the previous pipe. You can see that we get a list of 3 lm() outputs, we need to map a summary call to each of these to get access to R-squared."
},
{
"code": null,
"e": 8337,
"s": 7957,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .))# output$`4`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 39.571 -5.647$`6`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 28.41 -2.78$`8`Call:lm(formula = mpg ~ wt, data = .)Coefficients:(Intercept) wt 23.868 -2.192"
},
{
"code": null,
"e": 8524,
"s": 8337,
"text": "We next map our summary function to each of the list items to get cleaner outputs with R-squared values. We now have the rest of our statistical output, including p values and R-squared."
},
{
"code": null,
"e": 10315,
"s": 8524,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary)# output$`4`Call:lm(formula = mpg ~ wt, data = .)Residuals: Min 1Q Median 3Q Max -4.1513 -1.9795 -0.6272 1.9299 5.2523Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 39.571 4.347 9.104 7.77e-06 ***wt -5.647 1.850 -3.052 0.0137 * ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 3.332 on 9 degrees of freedomMultiple R-squared: 0.5086, Adjusted R-squared: 0.454 F-statistic: 9.316 on 1 and 9 DF, p-value: 0.01374$`6`Call:lm(formula = mpg ~ wt, data = .)Residuals: Mazda RX4 Mazda RX4 Wag Hornet 4 Drive Valiant Merc 280 -0.1250 0.5840 1.9292 -0.6897 0.3547 Merc 280C Ferrari Dino -1.0453 -1.0080Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 28.409 4.184 6.789 0.00105 **wt -2.780 1.335 -2.083 0.09176 . ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 1.165 on 5 degrees of freedomMultiple R-squared: 0.4645, Adjusted R-squared: 0.3574 F-statistic: 4.337 on 1 and 5 DF, p-value: 0.09176$`8`Call:lm(formula = mpg ~ wt, data = .)Residuals: Min 1Q Median 3Q Max -2.1491 -1.4664 -0.8458 1.5711 3.7619Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 23.8680 3.0055 7.942 4.05e-06 ***wt -2.1924 0.7392 -2.966 0.0118 * ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 2.024 on 12 degrees of freedomMultiple R-squared: 0.423, Adjusted R-squared: 0.3749 F-statistic: 8.796 on 1 and 12 DF, p-value: 0.01179"
},
{
"code": null,
"e": 10479,
"s": 10315,
"text": "Our last map is a bit different. You can see we use map_dbl this time. This indicates we want our output to be a dbl or numeric outcome. We get nice named numbers!"
},
{
"code": null,
"e": 10650,
"s": 10479,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl(\"r.squared\")# output 4 6 8 0.5086326 0.4645102 0.4229655"
},
{
"code": null,
"e": 10745,
"s": 10650,
"text": "If we had not indicated map_dbl, but instead used map we would get a list of the same outcome."
},
{
"code": null,
"e": 10905,
"s": 10745,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map(\"r.squared\")# output$`4`[1] 0.5086326$`6`[1] 0.4645102$`8`[1] 0.4229655"
},
{
"code": null,
"e": 10982,
"s": 10905,
"text": "You could also use map_dfr which binds the outputs into rows of a dataframe."
},
{
"code": null,
"e": 11169,
"s": 10982,
"text": "mtcars %>% split(.$cyl) %>% map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dfr(\"r.squared\")# output# A tibble: 1 x 3 `4` `6` `8` <dbl> <dbl> <dbl>1 0.509 0.465 0.423"
},
{
"code": null,
"e": 11408,
"s": 11169,
"text": "There are limitless applications of purrr and other functions within purrr that greatly empower your functional programming in R. I hope that this guide motivates you to add purrr to your toolbox and explore this useful tidyverse package!"
},
{
"code": null,
"e": 11727,
"s": 11408,
"text": "As a brief teaser to some more applications of purrr, I’ll leave you with this example. I mentioned calculating ANOVAs across multiple variables at the beginning. Break down this example on your own and see what you think! (You can copy paste this code into R, but need to load the tidyverse and broom packages first)."
},
{
"code": null,
"e": 11951,
"s": 11727,
"text": "mtcars %>% mutate(cyl = factor(cyl), am = factor(am)) %>% select(mpg, disp, hp) %>% map(~ aov(.x ~ cyl * am, data = mtcars)) %>% map_dfr(~ broom::tidy(.), .id = 'source') %>% mutate(p.value = round(p.value, 5))"
},
{
"code": null,
"e": 12120,
"s": 11951,
"text": "In closing, I’d like to thank several #r4ds slack community members for their help in my personal understanding of purrr: Frank Farach, Michael Kuehn, and Kent Johnson."
}
] |
Matplotlib Linear Regression Animation in Jupyter Notebook | by B. Chen | Towards Data Science
|
When fitting values to a line using Linear Regression, it can be very helpful to illustrate how the line fits the data as more data are added. In this article, you’ll learn how to create a Matplotlib animation, this article extends the topic from the previous article “animating a simple sine wave in Jupyter Notebook” to fit values to a line using Linear Regression.
Matplotlib is one of the most popular plotting libraries for exploratory data analysis. Plotting a static graph should work well in most cases, but when you are running simulations or doing time-series data analysis, basic plots may not always be enough. You may want to show an animation that helps you understand how the state changes over time. In this article, you’ll learn how to create a Matplotlib animation for fitting values to a line using Linear Regression. This article is structured as follows:
Gathering and preparing dataInteractive Plot in Jupyter NotebookEmbedded HTML5 video in Jupyter Notebook
Gathering and preparing data
Interactive Plot in Jupyter Notebook
Embedded HTML5 video in Jupyter Notebook
Please check out the Notebook for source code. More tutorials are available from Github Repo.
For demonstration, we will be using the cars dataset. The dataset includes the names of the cars, mpg, cylinders, displacement, etc. (8 variables) for 406 different cars [1]. We will be loading the data from Vega Datasets. Let’s import some libraries and load data to get started:
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LinearRegressionfrom vega_datasets import data%matplotlib inline%config InlineBackend.figure_format = 'svg'df = data.cars()df.head()
For this tutorial, we will be plotting Horsepower vs. Miles_per_Gallon. Let’s drop rows with NaN and transform the data into proper format:
# Drop rows with NaNdf.dropna(subset=['Horsepower', 'Miles_per_Gallon'], inplace=True)# Transform datax = df['Horsepower'].to_numpy().reshape(-1, 1)y = df['Miles_per_Gallon'].to_numpy().reshape(-1, 1)
Let’s do a simple scatter plot to show Horsepower vs. Miles_per_Gallon:
plt.scatter(x, y, c='g', label='Horsepower vs. Miles_per_Gallon')plt.legend()plt.show()
In order to create an interactive plot in Jupyter Notebook, you first need to enable interactive plot as follows:
# Enable interactive plot%matplotlib notebook
After that, we import the required libraries. Especially FuncAnimation class for creating animation and LinearRegression for creating a Linear Regression model.
import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom sklearn.linear_model import LinearRegression
Next, we need to create the initial state of the animation figure. Both x_data and y_data are initialized to []. We call subplots() without any arguments to create a Figure fig and a single Axes ax. We set the x range to (30, 250) and y range to (5, 50) to avoid them to be constantly changing. ax.plot() is called twice to create a scatter plot and a line plot. We also call LinearRegression() to create a Linear Regression model reg.
x_data = []y_data = []fig, ax = plt.subplots() ax.set_xlim(30, 250)ax.set_ylim(5, 50)scatter, = ax.plot([], [], 'go', label='Horsepower vs. Miles_per_Gallon')line, = ax.plot([], [], 'r', label='Linear Regression')ax.legend()reg = LinearRegression()
We then create a function animate() that’s going to be called by the FuncAnimation(). The function takes one argument frame_num — the current frame number. What we want to do here is to change data for our scatter plot and linear regression plot according to the frame number. Notice that reg.fit() is called to fit values as more data is added.
def animate(frame_num): # Adding data x_data.append(x[frame_num]) y_data.append(y[frame_num]) # Convert data to numpy array x_train = np.array(x_data).reshape(-1, 1) y_train = np.array(y_data).reshape(-1, 1) # Fit values to a linear regression reg.fit(x_train, y_train) # update data for scatter plot scatter.set_data((x_data, y_data)) # Predict value and update data for line plot line.set_data((list(range(250)), reg.predict(np.array([entry for entry in range(250)]).reshape(-1, 1))))
Finally, we create our animation object by calling FuncAnimation with 4 arguments
The first argument fig is the reference to the figure we created
The second argument animate is the function we created to call at each frame to update the plot
The third argument frames=len(x), it defines the number of frames for “one round of animation” and we have set it to the number of training data.
Finally, the interval=20 argument sets the delay (in milliseconds) between frames. 20 is equivalent to 50FPS (1000ms / 20 = 50 FPS). If the number is too large you wait a really long time, if the number is too small, it would be faster than your eyes could see. In general, we need FPS greater than 16 for smooth animation (Human eyes can only receive 10–12 frames [2]).
anim = FuncAnimation(fig, animate, frames=len(x), interval=20)plt.show()
Please check out Notebook for source code
In the previous example, we have created a nice animation with linear regression. However, the plot is animating only when the code is running. Of course, we could take a screen capture, but that’s not efficient when you want to share your Jupyter Notebook online.
What we can do is convert the animation into an HTML5 video and embed it in Jupyter Notebook. We will be using FFmpeg for conversion. If you don’t have it, you first need to follow the instruction to download FFmpeg and unzip it.
After that, we import the required libraries and set 'ffmpeg_path' to the path to your local ffmpeg executable:
import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom IPython import display# Turn off matplotlib plot in Notebookplt.ioff()# Pass the ffmpeg pathplt.rcParams['animation.ffmpeg_path'] = '/path_to_your/ffmpeg'
Creating animation is the same as the previous example.
x_data = []y_data = []fig, ax = plt.subplots()ax.set_xlim(30, 250)ax.set_ylim(5, 50)scatter, = ax.plot([], [], 'go', label='Horsepower vs. Miles_per_Gallon')line, = ax.plot([], [], 'r', label='Linear Regression')ax.legend()reg = LinearRegression()def animate(frame_num): # Adding data x_data.append(x[frame_num]) y_data.append(y[frame_num]) # Convert data to numpy array x_train = np.array(x_data).reshape(-1, 1) y_train = np.array(y_data).reshape(-1, 1) reg.fit(x_train, y_train) # update data for scatter plot scatter.set_data((x_data, y_data)) # Predict value and update data for line plot line.set_data((list(range(250)), reg.predict(np.array([entry for entry in range(250)]).reshape(-1, 1))))anim = FuncAnimation(fig, animate, frames=len(x), interval=20)
But instead of plt.show() to plot it, we are calling anim.to_html5_video() method to convert the animation result into an HTML5 video. We then need to get the HTML code that does the embedding for this video and that is done by calling IPython display.HTML(video). Finally, we call display.display(html) to embed the HTML code in Jupyter Notebook.
video = anim.to_html5_video()html = display.HTML(video)display.display(html)plt.close() # avoid plotting a spare static plot
Please check out Notebook for source code
In this article, we have learned 2 approaches to create a Matplotlib Linear Regression animation in Jupyter Notebook. Creating an animation plot can help you running simulations and doing time-series data analysis.
I hope this article will help you to save time in learning Matplotlib. I recommend you to check out the documentation for more options & settings and to know about other things you can do.
Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
Matplotlib animations in Jupyter Notebook
Python Interactive Data Visualization with Altair
Interactive Data Visualization for exploring Coronavirus Spreads
10 tricks for converting numbers and strings to Datetime in Pandas
All Pandas json_normalize() you should know for flattening JSON
Using Pandas method chaining to improve code readability
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
More tutorials can be found on my Github
[1] Dataset — cars http://lib.stat.cmu.edu/datasets/
|
[
{
"code": null,
"e": 540,
"s": 172,
"text": "When fitting values to a line using Linear Regression, it can be very helpful to illustrate how the line fits the data as more data are added. In this article, you’ll learn how to create a Matplotlib animation, this article extends the topic from the previous article “animating a simple sine wave in Jupyter Notebook” to fit values to a line using Linear Regression."
},
{
"code": null,
"e": 1048,
"s": 540,
"text": "Matplotlib is one of the most popular plotting libraries for exploratory data analysis. Plotting a static graph should work well in most cases, but when you are running simulations or doing time-series data analysis, basic plots may not always be enough. You may want to show an animation that helps you understand how the state changes over time. In this article, you’ll learn how to create a Matplotlib animation for fitting values to a line using Linear Regression. This article is structured as follows:"
},
{
"code": null,
"e": 1153,
"s": 1048,
"text": "Gathering and preparing dataInteractive Plot in Jupyter NotebookEmbedded HTML5 video in Jupyter Notebook"
},
{
"code": null,
"e": 1182,
"s": 1153,
"text": "Gathering and preparing data"
},
{
"code": null,
"e": 1219,
"s": 1182,
"text": "Interactive Plot in Jupyter Notebook"
},
{
"code": null,
"e": 1260,
"s": 1219,
"text": "Embedded HTML5 video in Jupyter Notebook"
},
{
"code": null,
"e": 1354,
"s": 1260,
"text": "Please check out the Notebook for source code. More tutorials are available from Github Repo."
},
{
"code": null,
"e": 1635,
"s": 1354,
"text": "For demonstration, we will be using the cars dataset. The dataset includes the names of the cars, mpg, cylinders, displacement, etc. (8 variables) for 406 different cars [1]. We will be loading the data from Vega Datasets. Let’s import some libraries and load data to get started:"
},
{
"code": null,
"e": 1850,
"s": 1635,
"text": "import matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LinearRegressionfrom vega_datasets import data%matplotlib inline%config InlineBackend.figure_format = 'svg'df = data.cars()df.head()"
},
{
"code": null,
"e": 1990,
"s": 1850,
"text": "For this tutorial, we will be plotting Horsepower vs. Miles_per_Gallon. Let’s drop rows with NaN and transform the data into proper format:"
},
{
"code": null,
"e": 2191,
"s": 1990,
"text": "# Drop rows with NaNdf.dropna(subset=['Horsepower', 'Miles_per_Gallon'], inplace=True)# Transform datax = df['Horsepower'].to_numpy().reshape(-1, 1)y = df['Miles_per_Gallon'].to_numpy().reshape(-1, 1)"
},
{
"code": null,
"e": 2263,
"s": 2191,
"text": "Let’s do a simple scatter plot to show Horsepower vs. Miles_per_Gallon:"
},
{
"code": null,
"e": 2351,
"s": 2263,
"text": "plt.scatter(x, y, c='g', label='Horsepower vs. Miles_per_Gallon')plt.legend()plt.show()"
},
{
"code": null,
"e": 2465,
"s": 2351,
"text": "In order to create an interactive plot in Jupyter Notebook, you first need to enable interactive plot as follows:"
},
{
"code": null,
"e": 2511,
"s": 2465,
"text": "# Enable interactive plot%matplotlib notebook"
},
{
"code": null,
"e": 2672,
"s": 2511,
"text": "After that, we import the required libraries. Especially FuncAnimation class for creating animation and LinearRegression for creating a Linear Regression model."
},
{
"code": null,
"e": 2799,
"s": 2672,
"text": "import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom sklearn.linear_model import LinearRegression"
},
{
"code": null,
"e": 3235,
"s": 2799,
"text": "Next, we need to create the initial state of the animation figure. Both x_data and y_data are initialized to []. We call subplots() without any arguments to create a Figure fig and a single Axes ax. We set the x range to (30, 250) and y range to (5, 50) to avoid them to be constantly changing. ax.plot() is called twice to create a scatter plot and a line plot. We also call LinearRegression() to create a Linear Regression model reg."
},
{
"code": null,
"e": 3484,
"s": 3235,
"text": "x_data = []y_data = []fig, ax = plt.subplots() ax.set_xlim(30, 250)ax.set_ylim(5, 50)scatter, = ax.plot([], [], 'go', label='Horsepower vs. Miles_per_Gallon')line, = ax.plot([], [], 'r', label='Linear Regression')ax.legend()reg = LinearRegression()"
},
{
"code": null,
"e": 3830,
"s": 3484,
"text": "We then create a function animate() that’s going to be called by the FuncAnimation(). The function takes one argument frame_num — the current frame number. What we want to do here is to change data for our scatter plot and linear regression plot according to the frame number. Notice that reg.fit() is called to fit values as more data is added."
},
{
"code": null,
"e": 4353,
"s": 3830,
"text": "def animate(frame_num): # Adding data x_data.append(x[frame_num]) y_data.append(y[frame_num]) # Convert data to numpy array x_train = np.array(x_data).reshape(-1, 1) y_train = np.array(y_data).reshape(-1, 1) # Fit values to a linear regression reg.fit(x_train, y_train) # update data for scatter plot scatter.set_data((x_data, y_data)) # Predict value and update data for line plot line.set_data((list(range(250)), reg.predict(np.array([entry for entry in range(250)]).reshape(-1, 1))))"
},
{
"code": null,
"e": 4435,
"s": 4353,
"text": "Finally, we create our animation object by calling FuncAnimation with 4 arguments"
},
{
"code": null,
"e": 4500,
"s": 4435,
"text": "The first argument fig is the reference to the figure we created"
},
{
"code": null,
"e": 4596,
"s": 4500,
"text": "The second argument animate is the function we created to call at each frame to update the plot"
},
{
"code": null,
"e": 4742,
"s": 4596,
"text": "The third argument frames=len(x), it defines the number of frames for “one round of animation” and we have set it to the number of training data."
},
{
"code": null,
"e": 5113,
"s": 4742,
"text": "Finally, the interval=20 argument sets the delay (in milliseconds) between frames. 20 is equivalent to 50FPS (1000ms / 20 = 50 FPS). If the number is too large you wait a really long time, if the number is too small, it would be faster than your eyes could see. In general, we need FPS greater than 16 for smooth animation (Human eyes can only receive 10–12 frames [2])."
},
{
"code": null,
"e": 5186,
"s": 5113,
"text": "anim = FuncAnimation(fig, animate, frames=len(x), interval=20)plt.show()"
},
{
"code": null,
"e": 5228,
"s": 5186,
"text": "Please check out Notebook for source code"
},
{
"code": null,
"e": 5493,
"s": 5228,
"text": "In the previous example, we have created a nice animation with linear regression. However, the plot is animating only when the code is running. Of course, we could take a screen capture, but that’s not efficient when you want to share your Jupyter Notebook online."
},
{
"code": null,
"e": 5723,
"s": 5493,
"text": "What we can do is convert the animation into an HTML5 video and embed it in Jupyter Notebook. We will be using FFmpeg for conversion. If you don’t have it, you first need to follow the instruction to download FFmpeg and unzip it."
},
{
"code": null,
"e": 5835,
"s": 5723,
"text": "After that, we import the required libraries and set 'ffmpeg_path' to the path to your local ffmpeg executable:"
},
{
"code": null,
"e": 6072,
"s": 5835,
"text": "import matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom IPython import display# Turn off matplotlib plot in Notebookplt.ioff()# Pass the ffmpeg pathplt.rcParams['animation.ffmpeg_path'] = '/path_to_your/ffmpeg'"
},
{
"code": null,
"e": 6128,
"s": 6072,
"text": "Creating animation is the same as the previous example."
},
{
"code": null,
"e": 6925,
"s": 6128,
"text": "x_data = []y_data = []fig, ax = plt.subplots()ax.set_xlim(30, 250)ax.set_ylim(5, 50)scatter, = ax.plot([], [], 'go', label='Horsepower vs. Miles_per_Gallon')line, = ax.plot([], [], 'r', label='Linear Regression')ax.legend()reg = LinearRegression()def animate(frame_num): # Adding data x_data.append(x[frame_num]) y_data.append(y[frame_num]) # Convert data to numpy array x_train = np.array(x_data).reshape(-1, 1) y_train = np.array(y_data).reshape(-1, 1) reg.fit(x_train, y_train) # update data for scatter plot scatter.set_data((x_data, y_data)) # Predict value and update data for line plot line.set_data((list(range(250)), reg.predict(np.array([entry for entry in range(250)]).reshape(-1, 1))))anim = FuncAnimation(fig, animate, frames=len(x), interval=20)"
},
{
"code": null,
"e": 7273,
"s": 6925,
"text": "But instead of plt.show() to plot it, we are calling anim.to_html5_video() method to convert the animation result into an HTML5 video. We then need to get the HTML code that does the embedding for this video and that is done by calling IPython display.HTML(video). Finally, we call display.display(html) to embed the HTML code in Jupyter Notebook."
},
{
"code": null,
"e": 7412,
"s": 7273,
"text": "video = anim.to_html5_video()html = display.HTML(video)display.display(html)plt.close() # avoid plotting a spare static plot"
},
{
"code": null,
"e": 7454,
"s": 7412,
"text": "Please check out Notebook for source code"
},
{
"code": null,
"e": 7669,
"s": 7454,
"text": "In this article, we have learned 2 approaches to create a Matplotlib Linear Regression animation in Jupyter Notebook. Creating an animation plot can help you running simulations and doing time-series data analysis."
},
{
"code": null,
"e": 7858,
"s": 7669,
"text": "I hope this article will help you to save time in learning Matplotlib. I recommend you to check out the documentation for more options & settings and to know about other things you can do."
},
{
"code": null,
"e": 8010,
"s": 7858,
"text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 8052,
"s": 8010,
"text": "Matplotlib animations in Jupyter Notebook"
},
{
"code": null,
"e": 8102,
"s": 8052,
"text": "Python Interactive Data Visualization with Altair"
},
{
"code": null,
"e": 8167,
"s": 8102,
"text": "Interactive Data Visualization for exploring Coronavirus Spreads"
},
{
"code": null,
"e": 8234,
"s": 8167,
"text": "10 tricks for converting numbers and strings to Datetime in Pandas"
},
{
"code": null,
"e": 8298,
"s": 8234,
"text": "All Pandas json_normalize() you should know for flattening JSON"
},
{
"code": null,
"e": 8355,
"s": 8298,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 8399,
"s": 8355,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 8456,
"s": 8399,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 8497,
"s": 8456,
"text": "More tutorials can be found on my Github"
}
] |
Python - Convert Integer Matrix to String Matrix - GeeksforGeeks
|
30 Dec, 2020
Given a Matrix with integer values, convert each element to String.
Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’], [’19’, ‘4’, ‘6’]]Explanation : All elements of Matrix converted to Strings.
Input : test_list = [[4, 5, 7], [10, 8, 3]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’]]Explanation : All elements of Matrix converted to Strings.
Method #1 : Using str() + list comprehension
The combination of above methods can be used to solve this problem. In this, we perform conversion using str() and list comprehension is used to iterate for all the elements.
Python3
# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + list comprehension # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]] # printing original listprint("The original list : " + str(test_list)) # using str() to convert each element to string res = [[str(ele) for ele in sub] for sub in test_list] # printing result print("The data type converted Matrix : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]
Method #2 : Using str() + map()
The combination of above functions can also be used to solve this problem. In this, we use map() to extend the string conversion to all row elements.
Python3
# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + map() # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]] # printing original listprint("The original list : " + str(test_list)) # using map() to extend all elements as string res = [list(map(str, sub)) for sub in test_list] # printing result print("The data type converted Matrix : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]
Python list-programs
Python matrix-program
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Convert set into a list
Python | Get dictionary keys as a list
Ways to filter Pandas DataFrame by column values
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24623,
"s": 24595,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 24691,
"s": 24623,
"text": "Given a Matrix with integer values, convert each element to String."
},
{
"code": null,
"e": 24867,
"s": 24691,
"text": "Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’], [’19’, ‘4’, ‘6’]]Explanation : All elements of Matrix converted to Strings."
},
{
"code": null,
"e": 25013,
"s": 24867,
"text": "Input : test_list = [[4, 5, 7], [10, 8, 3]]Output : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’]]Explanation : All elements of Matrix converted to Strings."
},
{
"code": null,
"e": 25058,
"s": 25013,
"text": "Method #1 : Using str() + list comprehension"
},
{
"code": null,
"e": 25233,
"s": 25058,
"text": "The combination of above methods can be used to solve this problem. In this, we perform conversion using str() and list comprehension is used to iterate for all the elements."
},
{
"code": null,
"e": 25241,
"s": 25233,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + list comprehension # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]] # printing original listprint(\"The original list : \" + str(test_list)) # using str() to convert each element to string res = [[str(ele) for ele in sub] for sub in test_list] # printing result print(\"The data type converted Matrix : \" + str(res))",
"e": 25686,
"s": 25241,
"text": null
},
{
"code": null,
"e": 25858,
"s": 25686,
"text": "The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]\nThe data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]\n"
},
{
"code": null,
"e": 25890,
"s": 25858,
"text": "Method #2 : Using str() + map()"
},
{
"code": null,
"e": 26040,
"s": 25890,
"text": "The combination of above functions can also be used to solve this problem. In this, we use map() to extend the string conversion to all row elements."
},
{
"code": null,
"e": 26048,
"s": 26040,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Convert Integer Matrix to String Matrix# Using str() + map() # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]] # printing original listprint(\"The original list : \" + str(test_list)) # using map() to extend all elements as string res = [list(map(str, sub)) for sub in test_list] # printing result print(\"The data type converted Matrix : \" + str(res))",
"e": 26474,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26646,
"s": 26474,
"text": "The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]\nThe data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]\n"
},
{
"code": null,
"e": 26667,
"s": 26646,
"text": "Python list-programs"
},
{
"code": null,
"e": 26689,
"s": 26667,
"text": "Python matrix-program"
},
{
"code": null,
"e": 26712,
"s": 26689,
"text": "Python string-programs"
},
{
"code": null,
"e": 26719,
"s": 26712,
"text": "Python"
},
{
"code": null,
"e": 26735,
"s": 26719,
"text": "Python Programs"
},
{
"code": null,
"e": 26833,
"s": 26735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26842,
"s": 26833,
"text": "Comments"
},
{
"code": null,
"e": 26855,
"s": 26842,
"text": "Old Comments"
},
{
"code": null,
"e": 26888,
"s": 26855,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26927,
"s": 26888,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26976,
"s": 26927,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27013,
"s": 26976,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27056,
"s": 27013,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27099,
"s": 27056,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27121,
"s": 27099,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27160,
"s": 27121,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27206,
"s": 27160,
"text": "Python | Split string into list of characters"
}
] |
miscellaneous topics in C++ - GeeksQuiz
|
29 Jul, 2020
// Objects of test can only be created using new
class Test
{
private:
~Test() {}
friend void destructTest(Test* );
};
// Only this function can destruct objects of Test
void destructTest(Test* ptr)
{
delete ptr;
}
int main()
{
// create an object
Test *ptr = new Test;
// destruct the object
destructTest (ptr);
return 0;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Read Text File Into List in Python?
Python Data Structures and Algorithms
How to Change Axis Scales in R Plots?
|
[
{
"code": null,
"e": 27610,
"s": 27582,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 27972,
"s": 27610,
"text": "// Objects of test can only be created using new\nclass Test\n{\nprivate:\n ~Test() {}\nfriend void destructTest(Test* );\n};\n \n// Only this function can destruct objects of Test\nvoid destructTest(Test* ptr)\n{\n delete ptr;\n}\n \nint main()\n{\n // create an object\n Test *ptr = new Test;\n \n // destruct the object\n destructTest (ptr);\n \n return 0;\n}\n"
},
{
"code": null,
"e": 28070,
"s": 27972,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28123,
"s": 28070,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 28184,
"s": 28123,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28222,
"s": 28184,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 28284,
"s": 28222,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28325,
"s": 28284,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28368,
"s": 28325,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 28404,
"s": 28368,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 28447,
"s": 28404,
"text": "How to Read Text File Into List in Python?"
},
{
"code": null,
"e": 28485,
"s": 28447,
"text": "Python Data Structures and Algorithms"
}
] |
Rexx - pos String
|
This method returns the position of one string within another.
pos(substr,string1)
string1 − The source string.
string1 − The source string.
substr − the sub string to search for in the main string.
substr − the sub string to search for in the main string.
This method returns the position of one string within another.
/* Main program */
a = "Hello World"
say pos("Hello",a)
When we run the above program, we will get the following result.
1
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2402,
"s": 2339,
"text": "This method returns the position of one string within another."
},
{
"code": null,
"e": 2423,
"s": 2402,
"text": "pos(substr,string1)\n"
},
{
"code": null,
"e": 2452,
"s": 2423,
"text": "string1 − The source string."
},
{
"code": null,
"e": 2481,
"s": 2452,
"text": "string1 − The source string."
},
{
"code": null,
"e": 2539,
"s": 2481,
"text": "substr − the sub string to search for in the main string."
},
{
"code": null,
"e": 2597,
"s": 2539,
"text": "substr − the sub string to search for in the main string."
},
{
"code": null,
"e": 2660,
"s": 2597,
"text": "This method returns the position of one string within another."
},
{
"code": null,
"e": 2720,
"s": 2660,
"text": "/* Main program */ \na = \"Hello World\" \nsay pos(\"Hello\",a) "
},
{
"code": null,
"e": 2785,
"s": 2720,
"text": "When we run the above program, we will get the following result."
},
{
"code": null,
"e": 2789,
"s": 2785,
"text": "1 \n"
},
{
"code": null,
"e": 2796,
"s": 2789,
"text": " Print"
},
{
"code": null,
"e": 2807,
"s": 2796,
"text": " Add Notes"
}
] |
Image Processing with Python — Blurring and Sharpening for Beginners | by Tonichi Edeza | Towards Data Science
|
In this article we shall discuss how to apply blurring and sharpening kernels onto images. These basic kernels form the backbone of a lot of more advanced kernel application. In my previous article I discussed the edge detection kernel, but I realized that I only stuck to greyscale images.
To act as a helpful guide, I shall discuss how we can go about applying these kernels onto colored images while still retaining the core image.
Let’s get started!
As always let us begin by importing the required Python Libraries.
import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imshow, imreadfrom skimage.color import rgb2yuv, rgb2hsv, rgb2gray, yuv2rgb, hsv2rgbfrom scipy.signal import convolve2d
For the purposes of this article, we shall use the below image.
dog = imread('fire_dog.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog);
Now the kernels we shall apply to the image are the Gaussian Blur Kernel and the Sharpen Kernel. You can see how we define their matrixes below.
# Sharpensharpen = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])# Gaussian Blurgaussian = (1 / 16.0) * np.array([[1., 2., 1.], [2., 4., 2.], [1., 2., 1.]])fig, ax = plt.subplots(1,2, figsize = (17,10))ax[0].imshow(sharpen, cmap='gray')ax[0].set_title(f'Sharpen', fontsize = 18) ax[1].imshow(gaussian, cmap='gray')ax[1].set_title(f'Gaussian Blur', fontsize = 18) [axi.set_axis_off() for axi in ax.ravel()];
But how do we actually apply these kernels to our image? Well, let us first try by directly convolving them. I have defined the below function to allow us to the kernels iteratively. Note how we set the boundary to fill and fillvalue to 0, this is important to ensure that the output will be a 0 padded matrix of the same size as the original matrix.
def multi_convolver(image, kernel, iterations): for i in range(iterations): image = convolve2d(image, kernel, 'same', boundary = 'fill', fillvalue = 0) return imagemulti_convolver(dog, gaussian, 2)
Oh no, it seems that we have come across a value error. Why is this the case? Remember that when we convolve a matrix with another matrix, the matrices should be of the same dimensions. This means that we cannot apply a 2D convolution to our 3D (because of the color channels) matrix. To solve this we must first convert the image to a greyscale.
dog_grey = rgb2gray(dog)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog_grey);
Now if we run the function, we should get the desired effect.
convolved_image = multi_convolver(dog_grey, gaussian, 2)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(convolved_image);
Wonderful! We can now see that the image has been clearly blurred. The below code will show us what happens to the image if we continue to run the gaussian blur convolution to the image.
def convolution_plotter(image, kernel): iterations = [1,10,20,30] f_size = 20 fig, ax = plt.subplots(1,4, figsize = (15,7)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Iteration : {iterations[n]}', fontsize = f_size) ax.imshow(multi_convolver(image, kernel, iterations[n]), cmap='gray') ax.set_axis_off() fig.tight_layout() convolution_plotter(dog_grey, gaussian)
Great! We can clearly see the continued blurring of the image due to the application of our kernel.
But what if you needed to blur the image and retain the color? Let us first try to apply the convolutions per color channel.
def convolver_rgb(image, kernel, iterations = 1): convolved_image_r = multi_convolver(image[:,:,0], kernel, iterations) convolved_image_g = multi_convolver(image[:,:,1], kernel, iterations) convolved_image_b = multi_convolver(image[:,:,2], kernel, iterations) reformed_image = np.dstack((np.rint(abs(convolved_image_r)), np.rint(abs(convolved_image_g)), np.rint(abs(convolved_image_b)))) / 255 fig, ax = plt.subplots(1,3, figsize = (17,10)) ax[0].imshow(abs(convolved_image_r), cmap='Reds') ax[0].set_title(f'Red', fontsize = 15) ax[1].imshow(abs(convolved_image_g), cmap='Greens') ax[1].set_title(f'Green', fontsize = 15) ax[2].imshow(abs(convolved_image_b), cmap='Blues') ax[2].set_title(f'Blue', fontsize = 15) [axi.set_axis_off() for axi in ax.ravel()] return np.array(reformed_image).astype(np.uint8)convolved_rgb_gauss = convolver_rgb(dog, gaussian, 2)
The function actually returns to us the reformed image, we just have to plug it into the show function.
plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(convolved_rgb_gauss);
Great! It seems that the function worked well. As a fun exercise let us see what happens when we convolve the image 10 times.
So this solve our issue right? Well, not really. To see the issue this function has, let us try to sharpen the image.
convolved_rgb_sharpen = convolver_rgb(dog, sharpen, 1)
Looks good so far, let us see what the reformed image looks like.
The image has been reformed, but we now see that there are some slight distortions. Why is this the case?
Remember that the RGB color space implicitly mixes the luminescence of the pixels with the colors. This means that it is practically impossible to apply convolutions to the lighting of an image without changing the colors. So how do we handle this issue?
One way to go around this problem is by changing the color space the image. Instead of using the RGB color space, we can make use of the Y’UV color space. We do this because the lighting channel in the Y’UV space is actually separated from the colors (this is the Y component).
For the purposes of this article we shall edit the function to first convert the image into a Y’UV color space and then do the required convolutions.
def convolver_rgb(image, kernel, iterations = 1): img_yuv = rgb2yuv(image) img_yuv[:,:,0] = multi_convolver(img_yuv[:,:,0], kernel, iterations) final_image = yuv2rgb(img_yuv) fig, ax = plt.subplots(1,2, figsize = (17,10)) ax[0].imshow(image) ax[0].set_title(f'Original', fontsize = 20) ax[1].imshow(final_image); ax[1].set_title(f'YUV Adjusted, Iterations = {iterations}', fontsize = 20) [axi.set_axis_off() for axi in ax.ravel()] fig.tight_layout() return final_imagefinal_image = convolver_rgb(dog, sharpen, iterations = 1)
We can see that our function now returns an image that is noticeably sharper with none of the color distortions. There are many other ways to tackle this issue with Y’UV conversion being only one of them. Remember that the V component of the HSV color space represents almost the same thing. However, the way that the luma component of Y’UV space and the value component of the HSV space are slightly different. Let us see what are the consequences of using one over the other.
def convolver_comparison(image, kernel, iterations = 1): img_yuv = rgb2yuv(image) img_yuv[:,:,0] = multi_convolver(img_yuv[:,:,0], kernel, iterations) final_image_yuv = yuv2rgb(img_yuv) img_hsv = rgb2hsv(image) img_hsv[:,:,2] = multi_convolver(img_hsv[:,:,2], kernel, iterations) final_image_hsv = hsv2rgb(img_hsv) convolved_image_r = multi_convolver(image[:,:,0], kernel, iterations) convolved_image_g = multi_convolver(image[:,:,1], kernel, iterations) convolved_image_b = multi_convolver(image[:,:,2], kernel, iterations) final_image_rgb = np.dstack((np.rint(abs(convolved_image_r)), np.rint(abs(convolved_image_g)), np.rint(abs(convolved_image_b)))) / 255 fig, ax = plt.subplots(2,2, figsize = (17,17)) ax[0][0].imshow(image) ax[0][0].set_title(f'Original', fontsize = 30) ax[0][1].imshow(final_image_rgb); ax[0][1].set_title(f'RGB Adjusted, Iterations = {iterations}', fontsize = 30) fig.tight_layout() ax[1][0].imshow(final_image_yuv) ax[1][0].set_title(f'YUV Adjusted, Iterations = {iterations}', fontsize = 30) ax[1][1].imshow(final_image_hsv) ax[1][1].set_title(f'HSV Adjusted, Iterations = {iterations}', fontsize = 30) [axi.set_axis_off() for axi in ax.ravel()] fig.tight_layout()convolver_comparison(dog, sharpen, iterations = 1)
We see that there is some slight improvement of the HSV and Y’UV over the original RGB method. For better illustration we can up the amount of iterations from 1 to 2.
At 2 iterations the distortions become far more apparent. But it is also very clear that the HSV and Y’UV adjusted image are fairing much better than the original RGB adjusted image. These properties should be kept in mind when deciding the best way to apply convolutional kernels onto an image.
In Conclusion
To summarize, we’ve learned how to conduct blurring and sharpening convolutions to an image. Such techniques are vital for any data scientist working in the field of image processing and computer vision. Very importantly, we learned that simply applying convolutions to the individual RGB channels may not be the best way to go. When working with images, one should always be aware that there are plenty of different kinds of color spaces to work with. Hopefully you found this article helpful and can apply it in your own work.
|
[
{
"code": null,
"e": 337,
"s": 46,
"text": "In this article we shall discuss how to apply blurring and sharpening kernels onto images. These basic kernels form the backbone of a lot of more advanced kernel application. In my previous article I discussed the edge detection kernel, but I realized that I only stuck to greyscale images."
},
{
"code": null,
"e": 481,
"s": 337,
"text": "To act as a helpful guide, I shall discuss how we can go about applying these kernels onto colored images while still retaining the core image."
},
{
"code": null,
"e": 500,
"s": 481,
"text": "Let’s get started!"
},
{
"code": null,
"e": 567,
"s": 500,
"text": "As always let us begin by importing the required Python Libraries."
},
{
"code": null,
"e": 759,
"s": 567,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imshow, imreadfrom skimage.color import rgb2yuv, rgb2hsv, rgb2gray, yuv2rgb, hsv2rgbfrom scipy.signal import convolve2d"
},
{
"code": null,
"e": 823,
"s": 759,
"text": "For the purposes of this article, we shall use the below image."
},
{
"code": null,
"e": 908,
"s": 823,
"text": "dog = imread('fire_dog.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog);"
},
{
"code": null,
"e": 1053,
"s": 908,
"text": "Now the kernels we shall apply to the image are the Gaussian Blur Kernel and the Sharpen Kernel. You can see how we define their matrixes below."
},
{
"code": null,
"e": 1571,
"s": 1053,
"text": "# Sharpensharpen = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])# Gaussian Blurgaussian = (1 / 16.0) * np.array([[1., 2., 1.], [2., 4., 2.], [1., 2., 1.]])fig, ax = plt.subplots(1,2, figsize = (17,10))ax[0].imshow(sharpen, cmap='gray')ax[0].set_title(f'Sharpen', fontsize = 18) ax[1].imshow(gaussian, cmap='gray')ax[1].set_title(f'Gaussian Blur', fontsize = 18) [axi.set_axis_off() for axi in ax.ravel()];"
},
{
"code": null,
"e": 1922,
"s": 1571,
"text": "But how do we actually apply these kernels to our image? Well, let us first try by directly convolving them. I have defined the below function to allow us to the kernels iteratively. Note how we set the boundary to fill and fillvalue to 0, this is important to ensure that the output will be a 0 padded matrix of the same size as the original matrix."
},
{
"code": null,
"e": 2159,
"s": 1922,
"text": "def multi_convolver(image, kernel, iterations): for i in range(iterations): image = convolve2d(image, kernel, 'same', boundary = 'fill', fillvalue = 0) return imagemulti_convolver(dog, gaussian, 2)"
},
{
"code": null,
"e": 2506,
"s": 2159,
"text": "Oh no, it seems that we have come across a value error. Why is this the case? Remember that when we convolve a matrix with another matrix, the matrices should be of the same dimensions. This means that we cannot apply a 2D convolution to our 3D (because of the color channels) matrix. To solve this we must first convert the image to a greyscale."
},
{
"code": null,
"e": 2592,
"s": 2506,
"text": "dog_grey = rgb2gray(dog)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog_grey);"
},
{
"code": null,
"e": 2654,
"s": 2592,
"text": "Now if we run the function, we should get the desired effect."
},
{
"code": null,
"e": 2779,
"s": 2654,
"text": "convolved_image = multi_convolver(dog_grey, gaussian, 2)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(convolved_image);"
},
{
"code": null,
"e": 2966,
"s": 2779,
"text": "Wonderful! We can now see that the image has been clearly blurred. The below code will show us what happens to the image if we continue to run the gaussian blur convolution to the image."
},
{
"code": null,
"e": 3420,
"s": 2966,
"text": "def convolution_plotter(image, kernel): iterations = [1,10,20,30] f_size = 20 fig, ax = plt.subplots(1,4, figsize = (15,7)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Iteration : {iterations[n]}', fontsize = f_size) ax.imshow(multi_convolver(image, kernel, iterations[n]), cmap='gray') ax.set_axis_off() fig.tight_layout() convolution_plotter(dog_grey, gaussian)"
},
{
"code": null,
"e": 3520,
"s": 3420,
"text": "Great! We can clearly see the continued blurring of the image due to the application of our kernel."
},
{
"code": null,
"e": 3645,
"s": 3520,
"text": "But what if you needed to blur the image and retain the color? Let us first try to apply the convolutions per color channel."
},
{
"code": null,
"e": 4839,
"s": 3645,
"text": "def convolver_rgb(image, kernel, iterations = 1): convolved_image_r = multi_convolver(image[:,:,0], kernel, iterations) convolved_image_g = multi_convolver(image[:,:,1], kernel, iterations) convolved_image_b = multi_convolver(image[:,:,2], kernel, iterations) reformed_image = np.dstack((np.rint(abs(convolved_image_r)), np.rint(abs(convolved_image_g)), np.rint(abs(convolved_image_b)))) / 255 fig, ax = plt.subplots(1,3, figsize = (17,10)) ax[0].imshow(abs(convolved_image_r), cmap='Reds') ax[0].set_title(f'Red', fontsize = 15) ax[1].imshow(abs(convolved_image_g), cmap='Greens') ax[1].set_title(f'Green', fontsize = 15) ax[2].imshow(abs(convolved_image_b), cmap='Blues') ax[2].set_title(f'Blue', fontsize = 15) [axi.set_axis_off() for axi in ax.ravel()] return np.array(reformed_image).astype(np.uint8)convolved_rgb_gauss = convolver_rgb(dog, gaussian, 2)"
},
{
"code": null,
"e": 4943,
"s": 4839,
"text": "The function actually returns to us the reformed image, we just have to plug it into the show function."
},
{
"code": null,
"e": 5016,
"s": 4943,
"text": "plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(convolved_rgb_gauss);"
},
{
"code": null,
"e": 5142,
"s": 5016,
"text": "Great! It seems that the function worked well. As a fun exercise let us see what happens when we convolve the image 10 times."
},
{
"code": null,
"e": 5260,
"s": 5142,
"text": "So this solve our issue right? Well, not really. To see the issue this function has, let us try to sharpen the image."
},
{
"code": null,
"e": 5315,
"s": 5260,
"text": "convolved_rgb_sharpen = convolver_rgb(dog, sharpen, 1)"
},
{
"code": null,
"e": 5381,
"s": 5315,
"text": "Looks good so far, let us see what the reformed image looks like."
},
{
"code": null,
"e": 5487,
"s": 5381,
"text": "The image has been reformed, but we now see that there are some slight distortions. Why is this the case?"
},
{
"code": null,
"e": 5742,
"s": 5487,
"text": "Remember that the RGB color space implicitly mixes the luminescence of the pixels with the colors. This means that it is practically impossible to apply convolutions to the lighting of an image without changing the colors. So how do we handle this issue?"
},
{
"code": null,
"e": 6020,
"s": 5742,
"text": "One way to go around this problem is by changing the color space the image. Instead of using the RGB color space, we can make use of the Y’UV color space. We do this because the lighting channel in the Y’UV space is actually separated from the colors (this is the Y component)."
},
{
"code": null,
"e": 6170,
"s": 6020,
"text": "For the purposes of this article we shall edit the function to first convert the image into a Y’UV color space and then do the required convolutions."
},
{
"code": null,
"e": 6840,
"s": 6170,
"text": "def convolver_rgb(image, kernel, iterations = 1): img_yuv = rgb2yuv(image) img_yuv[:,:,0] = multi_convolver(img_yuv[:,:,0], kernel, iterations) final_image = yuv2rgb(img_yuv) fig, ax = plt.subplots(1,2, figsize = (17,10)) ax[0].imshow(image) ax[0].set_title(f'Original', fontsize = 20) ax[1].imshow(final_image); ax[1].set_title(f'YUV Adjusted, Iterations = {iterations}', fontsize = 20) [axi.set_axis_off() for axi in ax.ravel()] fig.tight_layout() return final_imagefinal_image = convolver_rgb(dog, sharpen, iterations = 1)"
},
{
"code": null,
"e": 7318,
"s": 6840,
"text": "We can see that our function now returns an image that is noticeably sharper with none of the color distortions. There are many other ways to tackle this issue with Y’UV conversion being only one of them. Remember that the V component of the HSV color space represents almost the same thing. However, the way that the luma component of Y’UV space and the value component of the HSV space are slightly different. Let us see what are the consequences of using one over the other."
},
{
"code": null,
"e": 8994,
"s": 7318,
"text": "def convolver_comparison(image, kernel, iterations = 1): img_yuv = rgb2yuv(image) img_yuv[:,:,0] = multi_convolver(img_yuv[:,:,0], kernel, iterations) final_image_yuv = yuv2rgb(img_yuv) img_hsv = rgb2hsv(image) img_hsv[:,:,2] = multi_convolver(img_hsv[:,:,2], kernel, iterations) final_image_hsv = hsv2rgb(img_hsv) convolved_image_r = multi_convolver(image[:,:,0], kernel, iterations) convolved_image_g = multi_convolver(image[:,:,1], kernel, iterations) convolved_image_b = multi_convolver(image[:,:,2], kernel, iterations) final_image_rgb = np.dstack((np.rint(abs(convolved_image_r)), np.rint(abs(convolved_image_g)), np.rint(abs(convolved_image_b)))) / 255 fig, ax = plt.subplots(2,2, figsize = (17,17)) ax[0][0].imshow(image) ax[0][0].set_title(f'Original', fontsize = 30) ax[0][1].imshow(final_image_rgb); ax[0][1].set_title(f'RGB Adjusted, Iterations = {iterations}', fontsize = 30) fig.tight_layout() ax[1][0].imshow(final_image_yuv) ax[1][0].set_title(f'YUV Adjusted, Iterations = {iterations}', fontsize = 30) ax[1][1].imshow(final_image_hsv) ax[1][1].set_title(f'HSV Adjusted, Iterations = {iterations}', fontsize = 30) [axi.set_axis_off() for axi in ax.ravel()] fig.tight_layout()convolver_comparison(dog, sharpen, iterations = 1)"
},
{
"code": null,
"e": 9161,
"s": 8994,
"text": "We see that there is some slight improvement of the HSV and Y’UV over the original RGB method. For better illustration we can up the amount of iterations from 1 to 2."
},
{
"code": null,
"e": 9457,
"s": 9161,
"text": "At 2 iterations the distortions become far more apparent. But it is also very clear that the HSV and Y’UV adjusted image are fairing much better than the original RGB adjusted image. These properties should be kept in mind when deciding the best way to apply convolutional kernels onto an image."
},
{
"code": null,
"e": 9471,
"s": 9457,
"text": "In Conclusion"
}
] |
Plotly - Legends
|
By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True.
layout = go.Layoyt(showlegend = True)
Default labels of legends are trace object names. To set legend label explicitly set name property of trace.
In following example, two scatter traces with name property are plotted.
import numpy as np
import math #needed for definition of pi
xpoints = np.arange(0, math.pi*2, 0.05)
y1 = np.sin(xpoints)
y2 = np.cos(xpoints)
trace0 = go.Scatter(
x = xpoints,
y = y1,
name='Sine'
)
trace1 = go.Scatter(
x = xpoints,
y = y2,
name = 'cos'
)
data = [trace0, trace1]
layout = go.Layout(title = "Sine and cos", xaxis = {'title':'angle'}, yaxis = {'title':'value'})
fig = go.Figure(data = data, layout = layout)
iplot(fig)
The plot appears as below −
12 Lectures
53 mins
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2559,
"s": 2360,
"text": "By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True."
},
{
"code": null,
"e": 2598,
"s": 2559,
"text": "layout = go.Layoyt(showlegend = True)\n"
},
{
"code": null,
"e": 2707,
"s": 2598,
"text": "Default labels of legends are trace object names. To set legend label explicitly set name property of trace."
},
{
"code": null,
"e": 2780,
"s": 2707,
"text": "In following example, two scatter traces with name property are plotted."
},
{
"code": null,
"e": 3232,
"s": 2780,
"text": "import numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\ny1 = np.sin(xpoints)\ny2 = np.cos(xpoints)\ntrace0 = go.Scatter(\n x = xpoints,\n y = y1,\n name='Sine'\n)\ntrace1 = go.Scatter(\n x = xpoints,\n y = y2,\n name = 'cos'\n)\ndata = [trace0, trace1]\nlayout = go.Layout(title = \"Sine and cos\", xaxis = {'title':'angle'}, yaxis = {'title':'value'})\nfig = go.Figure(data = data, layout = layout)\niplot(fig)"
},
{
"code": null,
"e": 3260,
"s": 3232,
"text": "The plot appears as below −"
},
{
"code": null,
"e": 3292,
"s": 3260,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 3312,
"s": 3292,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3319,
"s": 3312,
"text": " Print"
},
{
"code": null,
"e": 3330,
"s": 3319,
"text": " Add Notes"
}
] |
Subgraph filtering in Neo4j Graph Data Science library | by Tomaz Bratanic | Towards Data Science
|
It has been a while since I wrote a post about new features in the Neo4j Graph Data Science library (GDS). For those of you that never heard of the GDS library, it features more than 50 graph algorithms ranging from community detection to node embedding algorithms and more. In this blog post, I will present Subgraph filtering, one of the library’s newer features. To quickly recap how the GDS library works, let’s look at the following image:
Neo4j Graph Data Science library uses the Graph Loader component to project an in-memory graph. The in-memory project graph is separate from the stored graph in the Neo4j database. The GDS library then uses the in-memory graph projection, optimized for topology and property lookup operations, to execute graph algorithms. You can use either Native or Cypher projections to project an in-memory graph. In addition, subgraph filtering allows you to create a new projected in-memory graph based on an existing projected graph. For example, you could project a graph, identify the weakly connected components within that network, and then use subgraph filtering to create a new projected graph that consists only of the largest component in the network. This allows you a smoother graph data science workflow, where you don’t have to store intermediate results back to the database and then use Graph Loader to project a new in-memory graph.
In this blog post, we will be using the Harry Potter network dataset I have created in one of my previous blog posts. It consists of interactions between characters in the Harry Potter and the Philosopher’s Stone book.
The graph schema is relatively simple. It consists of characters and their interactions. We know the name of the characters and when they first appeared in the book (firstSeen). The INTERACTS relationship holds the information about how many times two characters have interacted (weight) and when they first interacted (firstSeen). If you want to follow along with exercises in this post, I would suggest you use Neo4j Sandbox and select a blank project.
Neo4j Sandbox provides a free cloud-instance of Neo4j database and comes with both APOC and GDS libraries pre-installed. However, if you want a local setup of Neo4j database, I have another blog post where I described how to get started with Neo4j Desktop.
To import the HP interaction network, you need to execute the following two Cypher queries.
Import characters:
LOAD CSV WITH HEADERS FROM "https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/HP/character_first_seen.csv" as rowMERGE (c:Character{name:row.name})SET c.firstSeen = toInteger(row.value)
Import interactions:
LOAD CSV WITH HEADERS FROM "https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/HP/HP_rels.csv" as rowMATCH (s:Character{name:row.source})MATCH (t:Character{name:row.target})MERGE (s)-[i:INTERACTS]->(t)SET i.weight = toInteger(row.weight), i.firstSeen = toInteger(row.first_seen)
Once you have imported the dataset, you can inspect a sample subgraph with the following query:
MATCH p=(:Character)-[:INTERACTS]->(:Character)RETURN p LIMIT 25
You should see a similar visualization in Neo4j Browser:
As mention, the goal of this blog post is to demonstrate the power of subgraph filtering. We will not delve into specific algorithms and how they work. We will begin by projecting an in-memory graph with Native projections.
CALL gds.graph.create('interactions', 'Character', {INTERACTS : {orientation:'UNDIRECTED'}}, {nodeProperties:['firstSeen'], relationshipProperties: ['firstSeen', 'weight']})
We have projected an in-memory graph under the “interactions” name. The projected graph includes all Character nodes and their firstSeen properties. We have also defined that we want to project the INTERACTS relationships as undirected and include both firstSeen and weight properties.
Now that we have the projected named graph, we can go ahead and execute any of the graph algorithms on it. Here, I have chosen to run the Weakly Connected Components algorithm (WCC). The WCC algorithm is used to identify disconnected parts of your network that are also known as components.
CALL gds.wcc.stats('interactions')YIELD componentCount, componentDistribution
Result
You can use the stats mode of the algorithm when you are only interested in the high-level overview of the results and have no wish to store the results back to Neo4j or to the projected graph. We can observe that there are four components in our network, the largest having 110 members. Now, we will begin with subgraph filtering. The syntax for the subgraph filtering procedure is as follows:
CALL gds.beta.graph.subgraph( graphName: String, -> name of the new projected graph fromGraphName: String, -> name of the existing projected graph nodeFilter: String, -> predicate used to filter nodes relationshipFilter: String -> predicate used to filter relationships)
You can use the nodeFilter parameter to filter nodes based on node properties or labels. Similarly, you can use relationshipFilter parameter to filter relationships based on their properties and types. There is only a single node label and relationships type in our HP network, so we will only focus on filtering by properties.
We will begin by using the subgraph filtering to create a new projected in-memory graph that holds only relationships that have the weight property greater than 1.
CALL gds.beta.graph.create.subgraph( 'wgt1', // name of the new projected graph 'interactions', // name of the existing projected graph '*', // node predicate filter 'r.weight > 1' // relationship predicate filter)
The wildcard operator * is used to define that we don’t want to apply any filtering. In this case, we have only filtered relationships, but kept all the nodes. The predicate syntax is similar to Cypher query. The relationship entity is always identified by r and the node entity is identified with variable n .
We can go ahead and run the WCC algorithm on the new in-memory graph that we created with the subgraph filtering. It is available under the wgt1name, for a lack of better name nomenclature.
CALL gds.wcc.mutate('wgt1', {mutateProperty:'wcc'})YIELD componentCount, componentDistribution
Result
The filtered projected graph has 43 components. This is reasonable as we ignored all the relationships that have the weight property equal or smaller to one, but left all the nodes. We have used the mutate mode of the algorithm to write the results back to the projected in-memory graph.
Let’s say we now want to run Eigenvector centrality only on the largest component of the graph. First, we need to identify the ID of the largest component. The results of the WCC algorithm are stored in the projected in-memory graph, so we need to use the gds.graph.streamNodeProperties procedure to access the WCC results and identify the largest component.
CALL gds.graph.streamNodeProperties('wgt1', ['wcc']) YIELD propertyValueRETURN propertyValue as component, count(*) as componentSizeORDER BY componentSize DESC LIMIT 5
Results
As we saw before, the largest component has 78 members and its id is 0. We can use the subgraph filtering feature to create a new projected in-memory graph that contains only the nodes in the largest component.
CALL gds.beta.graph.create.subgraph( 'largest_community', 'wgt1', 'n.wcc = 0', '*')
Now, we can go ahead and accomplish our task by running the Eigenvector centrality on the largest component only.
CALL gds.eigenvector.stream('largest_community')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name as character, scoreORDER BY score DESCLIMIT 5
Result
In the Harry Potter universe, there is a good chance that Harry Potter will always come out on top. We have already done two subgraph filtering steps, so you might get confused about what version of network is projected now. The GDS library offers a gds.graph.exportfeature that allows you to export a projected graph as a separate database instance within the same Neo4j server.
CALL gds.graph.export('largest_community', { dbName: 'lc1' });
Before you can access the new database instance in Neo4j Browser, you need to run the following command:
CREATE DATABASE lc1;
Now you can select the lc1database in the database dropdown menu and inspect its content.
I don’t know why, but the Sandbox instance doesn’t work well with the graph export, while the local Desktop version works just fine. At the moment, you can’t export string properties to a separate database. However, I’ve heard through the grapevine that string properties in a projected in-memory graph are to be supported soon.
In the last example, I will show how you can combine multiple node and relationship predicates using the AND or OR logical operators. First we will run the degree centrality on the interactions network and store the results to the projected graph using the mutate mode.
CALL gds.degree.mutate('interactions', {mutateProperty:'degree'})
Now we can go ahead and filter the subgraph by using multiple node and relationship predicates:
CALL gds.beta.graph.create.subgraph( 'first_half', // new projected graph 'interactions', // existing projected graph 'n.firstSeen < 35583 AND n.degree > 2', // node predicates 'r.weight > 5' // relationship predicates)
In the node predicate, we have selected nodes with a degree value greater than two and the first seen property smaller than 35583. For the relationship predicate, I have chosen only relationships that have a weight greater than five. We can run any of the graph algorithms on the newly filtered in-memory subgraph:
CALL gds.eigenvector.stream('first_half')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name as character, scoreORDER BY scoreDESC LIMIT 5
Results
Lastly, when you are done with your graph analysis, you can use the following Cypher query to drop all the projected in-memory graphs:
CALL gds.graph.list() YIELD graphNameCALL gds.graph.drop(graphName)YIELD databaseRETURN 'dropped ' + graphName
Subgraph filtering is a nice addition to the GDS library that allows smoother workflows. Instead of having to store the algoritm results back to Neo4j and use Native or Cypher projections to create a new in-memory graph, you can use subgraph filtering to filter an existing in-memory graph. Try it out on Neo4j Sandbox and let me know how it goes!
As always, the code is available on GitHub.
|
[
{
"code": null,
"e": 617,
"s": 172,
"text": "It has been a while since I wrote a post about new features in the Neo4j Graph Data Science library (GDS). For those of you that never heard of the GDS library, it features more than 50 graph algorithms ranging from community detection to node embedding algorithms and more. In this blog post, I will present Subgraph filtering, one of the library’s newer features. To quickly recap how the GDS library works, let’s look at the following image:"
},
{
"code": null,
"e": 1556,
"s": 617,
"text": "Neo4j Graph Data Science library uses the Graph Loader component to project an in-memory graph. The in-memory project graph is separate from the stored graph in the Neo4j database. The GDS library then uses the in-memory graph projection, optimized for topology and property lookup operations, to execute graph algorithms. You can use either Native or Cypher projections to project an in-memory graph. In addition, subgraph filtering allows you to create a new projected in-memory graph based on an existing projected graph. For example, you could project a graph, identify the weakly connected components within that network, and then use subgraph filtering to create a new projected graph that consists only of the largest component in the network. This allows you a smoother graph data science workflow, where you don’t have to store intermediate results back to the database and then use Graph Loader to project a new in-memory graph."
},
{
"code": null,
"e": 1775,
"s": 1556,
"text": "In this blog post, we will be using the Harry Potter network dataset I have created in one of my previous blog posts. It consists of interactions between characters in the Harry Potter and the Philosopher’s Stone book."
},
{
"code": null,
"e": 2230,
"s": 1775,
"text": "The graph schema is relatively simple. It consists of characters and their interactions. We know the name of the characters and when they first appeared in the book (firstSeen). The INTERACTS relationship holds the information about how many times two characters have interacted (weight) and when they first interacted (firstSeen). If you want to follow along with exercises in this post, I would suggest you use Neo4j Sandbox and select a blank project."
},
{
"code": null,
"e": 2487,
"s": 2230,
"text": "Neo4j Sandbox provides a free cloud-instance of Neo4j database and comes with both APOC and GDS libraries pre-installed. However, if you want a local setup of Neo4j database, I have another blog post where I described how to get started with Neo4j Desktop."
},
{
"code": null,
"e": 2579,
"s": 2487,
"text": "To import the HP interaction network, you need to execute the following two Cypher queries."
},
{
"code": null,
"e": 2598,
"s": 2579,
"text": "Import characters:"
},
{
"code": null,
"e": 2797,
"s": 2598,
"text": "LOAD CSV WITH HEADERS FROM \"https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/HP/character_first_seen.csv\" as rowMERGE (c:Character{name:row.name})SET c.firstSeen = toInteger(row.value)"
},
{
"code": null,
"e": 2818,
"s": 2797,
"text": "Import interactions:"
},
{
"code": null,
"e": 3112,
"s": 2818,
"text": "LOAD CSV WITH HEADERS FROM \"https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/HP/HP_rels.csv\" as rowMATCH (s:Character{name:row.source})MATCH (t:Character{name:row.target})MERGE (s)-[i:INTERACTS]->(t)SET i.weight = toInteger(row.weight), i.firstSeen = toInteger(row.first_seen)"
},
{
"code": null,
"e": 3208,
"s": 3112,
"text": "Once you have imported the dataset, you can inspect a sample subgraph with the following query:"
},
{
"code": null,
"e": 3273,
"s": 3208,
"text": "MATCH p=(:Character)-[:INTERACTS]->(:Character)RETURN p LIMIT 25"
},
{
"code": null,
"e": 3330,
"s": 3273,
"text": "You should see a similar visualization in Neo4j Browser:"
},
{
"code": null,
"e": 3554,
"s": 3330,
"text": "As mention, the goal of this blog post is to demonstrate the power of subgraph filtering. We will not delve into specific algorithms and how they work. We will begin by projecting an in-memory graph with Native projections."
},
{
"code": null,
"e": 3734,
"s": 3554,
"text": "CALL gds.graph.create('interactions', 'Character', {INTERACTS : {orientation:'UNDIRECTED'}}, {nodeProperties:['firstSeen'], relationshipProperties: ['firstSeen', 'weight']})"
},
{
"code": null,
"e": 4020,
"s": 3734,
"text": "We have projected an in-memory graph under the “interactions” name. The projected graph includes all Character nodes and their firstSeen properties. We have also defined that we want to project the INTERACTS relationships as undirected and include both firstSeen and weight properties."
},
{
"code": null,
"e": 4311,
"s": 4020,
"text": "Now that we have the projected named graph, we can go ahead and execute any of the graph algorithms on it. Here, I have chosen to run the Weakly Connected Components algorithm (WCC). The WCC algorithm is used to identify disconnected parts of your network that are also known as components."
},
{
"code": null,
"e": 4389,
"s": 4311,
"text": "CALL gds.wcc.stats('interactions')YIELD componentCount, componentDistribution"
},
{
"code": null,
"e": 4396,
"s": 4389,
"text": "Result"
},
{
"code": null,
"e": 4791,
"s": 4396,
"text": "You can use the stats mode of the algorithm when you are only interested in the high-level overview of the results and have no wish to store the results back to Neo4j or to the projected graph. We can observe that there are four components in our network, the largest having 110 members. Now, we will begin with subgraph filtering. The syntax for the subgraph filtering procedure is as follows:"
},
{
"code": null,
"e": 5066,
"s": 4791,
"text": "CALL gds.beta.graph.subgraph( graphName: String, -> name of the new projected graph fromGraphName: String, -> name of the existing projected graph nodeFilter: String, -> predicate used to filter nodes relationshipFilter: String -> predicate used to filter relationships)"
},
{
"code": null,
"e": 5394,
"s": 5066,
"text": "You can use the nodeFilter parameter to filter nodes based on node properties or labels. Similarly, you can use relationshipFilter parameter to filter relationships based on their properties and types. There is only a single node label and relationships type in our HP network, so we will only focus on filtering by properties."
},
{
"code": null,
"e": 5558,
"s": 5394,
"text": "We will begin by using the subgraph filtering to create a new projected in-memory graph that holds only relationships that have the weight property greater than 1."
},
{
"code": null,
"e": 5777,
"s": 5558,
"text": "CALL gds.beta.graph.create.subgraph( 'wgt1', // name of the new projected graph 'interactions', // name of the existing projected graph '*', // node predicate filter 'r.weight > 1' // relationship predicate filter)"
},
{
"code": null,
"e": 6088,
"s": 5777,
"text": "The wildcard operator * is used to define that we don’t want to apply any filtering. In this case, we have only filtered relationships, but kept all the nodes. The predicate syntax is similar to Cypher query. The relationship entity is always identified by r and the node entity is identified with variable n ."
},
{
"code": null,
"e": 6278,
"s": 6088,
"text": "We can go ahead and run the WCC algorithm on the new in-memory graph that we created with the subgraph filtering. It is available under the wgt1name, for a lack of better name nomenclature."
},
{
"code": null,
"e": 6373,
"s": 6278,
"text": "CALL gds.wcc.mutate('wgt1', {mutateProperty:'wcc'})YIELD componentCount, componentDistribution"
},
{
"code": null,
"e": 6380,
"s": 6373,
"text": "Result"
},
{
"code": null,
"e": 6668,
"s": 6380,
"text": "The filtered projected graph has 43 components. This is reasonable as we ignored all the relationships that have the weight property equal or smaller to one, but left all the nodes. We have used the mutate mode of the algorithm to write the results back to the projected in-memory graph."
},
{
"code": null,
"e": 7027,
"s": 6668,
"text": "Let’s say we now want to run Eigenvector centrality only on the largest component of the graph. First, we need to identify the ID of the largest component. The results of the WCC algorithm are stored in the projected in-memory graph, so we need to use the gds.graph.streamNodeProperties procedure to access the WCC results and identify the largest component."
},
{
"code": null,
"e": 7195,
"s": 7027,
"text": "CALL gds.graph.streamNodeProperties('wgt1', ['wcc']) YIELD propertyValueRETURN propertyValue as component, count(*) as componentSizeORDER BY componentSize DESC LIMIT 5"
},
{
"code": null,
"e": 7203,
"s": 7195,
"text": "Results"
},
{
"code": null,
"e": 7414,
"s": 7203,
"text": "As we saw before, the largest component has 78 members and its id is 0. We can use the subgraph filtering feature to create a new projected in-memory graph that contains only the nodes in the largest component."
},
{
"code": null,
"e": 7504,
"s": 7414,
"text": "CALL gds.beta.graph.create.subgraph( 'largest_community', 'wgt1', 'n.wcc = 0', '*')"
},
{
"code": null,
"e": 7618,
"s": 7504,
"text": "Now, we can go ahead and accomplish our task by running the Eigenvector centrality on the largest component only."
},
{
"code": null,
"e": 7767,
"s": 7618,
"text": "CALL gds.eigenvector.stream('largest_community')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name as character, scoreORDER BY score DESCLIMIT 5"
},
{
"code": null,
"e": 7774,
"s": 7767,
"text": "Result"
},
{
"code": null,
"e": 8154,
"s": 7774,
"text": "In the Harry Potter universe, there is a good chance that Harry Potter will always come out on top. We have already done two subgraph filtering steps, so you might get confused about what version of network is projected now. The GDS library offers a gds.graph.exportfeature that allows you to export a projected graph as a separate database instance within the same Neo4j server."
},
{
"code": null,
"e": 8217,
"s": 8154,
"text": "CALL gds.graph.export('largest_community', { dbName: 'lc1' });"
},
{
"code": null,
"e": 8322,
"s": 8217,
"text": "Before you can access the new database instance in Neo4j Browser, you need to run the following command:"
},
{
"code": null,
"e": 8343,
"s": 8322,
"text": "CREATE DATABASE lc1;"
},
{
"code": null,
"e": 8433,
"s": 8343,
"text": "Now you can select the lc1database in the database dropdown menu and inspect its content."
},
{
"code": null,
"e": 8762,
"s": 8433,
"text": "I don’t know why, but the Sandbox instance doesn’t work well with the graph export, while the local Desktop version works just fine. At the moment, you can’t export string properties to a separate database. However, I’ve heard through the grapevine that string properties in a projected in-memory graph are to be supported soon."
},
{
"code": null,
"e": 9032,
"s": 8762,
"text": "In the last example, I will show how you can combine multiple node and relationship predicates using the AND or OR logical operators. First we will run the degree centrality on the interactions network and store the results to the projected graph using the mutate mode."
},
{
"code": null,
"e": 9099,
"s": 9032,
"text": "CALL gds.degree.mutate('interactions', {mutateProperty:'degree'})"
},
{
"code": null,
"e": 9195,
"s": 9099,
"text": "Now we can go ahead and filter the subgraph by using multiple node and relationship predicates:"
},
{
"code": null,
"e": 9419,
"s": 9195,
"text": "CALL gds.beta.graph.create.subgraph( 'first_half', // new projected graph 'interactions', // existing projected graph 'n.firstSeen < 35583 AND n.degree > 2', // node predicates 'r.weight > 5' // relationship predicates)"
},
{
"code": null,
"e": 9734,
"s": 9419,
"text": "In the node predicate, we have selected nodes with a degree value greater than two and the first seen property smaller than 35583. For the relationship predicate, I have chosen only relationships that have a weight greater than five. We can run any of the graph algorithms on the newly filtered in-memory subgraph:"
},
{
"code": null,
"e": 9876,
"s": 9734,
"text": "CALL gds.eigenvector.stream('first_half')YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).name as character, scoreORDER BY scoreDESC LIMIT 5"
},
{
"code": null,
"e": 9884,
"s": 9876,
"text": "Results"
},
{
"code": null,
"e": 10019,
"s": 9884,
"text": "Lastly, when you are done with your graph analysis, you can use the following Cypher query to drop all the projected in-memory graphs:"
},
{
"code": null,
"e": 10130,
"s": 10019,
"text": "CALL gds.graph.list() YIELD graphNameCALL gds.graph.drop(graphName)YIELD databaseRETURN 'dropped ' + graphName"
},
{
"code": null,
"e": 10478,
"s": 10130,
"text": "Subgraph filtering is a nice addition to the GDS library that allows smoother workflows. Instead of having to store the algoritm results back to Neo4j and use Native or Cypher projections to create a new in-memory graph, you can use subgraph filtering to filter an existing in-memory graph. Try it out on Neo4j Sandbox and let me know how it goes!"
}
] |
Decimal.Divide() Method in C# - GeeksforGeeks
|
11 Oct, 2021
This method is used to divide the two specified decimal values.
Syntax: public static decimal Divide (decimal a1, decimal a2);
Parameters:a1: This parameter specifies the dividend.a2: This parameter specifies the divisor.
Return Value: The result of dividing a1 by a2.
Exceptions:
DivideByZeroException: This occurs when a2 is zero.
OverflowException: If the result of dividing a1 and a2 is less than smallest possible value of Decimal or greater than the largest possible value of Decimal.
Below programs illustrate the use of Decimal.Divide(Decimal, Decimal) Method:
Example 1:
// C# program to demonstrate the// Decimal.Divide(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 2.01m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine("Result of "+ "division : {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Result of division : 2
Example 2: Program for OverflowException
// C# program to demonstrate the// Decimal.Divide(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = Decimal.MaxValue; Decimal a2 = 0.01m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine("Result of "+ "division : {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.OverflowException
Example 3: Program for DivideByZeroException
// C# program to demonstrate the// Decimal.Divide(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 0.00m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine("Result of"+ " division : {0}", value); } catch (DivideByZeroException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.DivideByZeroException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.divide?view=netframework-4.7.2
surindertarika1234
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Class and Object
C# | Abstract Classes
C# | Data Types
|
[
{
"code": null,
"e": 24614,
"s": 24586,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 24678,
"s": 24614,
"text": "This method is used to divide the two specified decimal values."
},
{
"code": null,
"e": 24741,
"s": 24678,
"text": "Syntax: public static decimal Divide (decimal a1, decimal a2);"
},
{
"code": null,
"e": 24836,
"s": 24741,
"text": "Parameters:a1: This parameter specifies the dividend.a2: This parameter specifies the divisor."
},
{
"code": null,
"e": 24883,
"s": 24836,
"text": "Return Value: The result of dividing a1 by a2."
},
{
"code": null,
"e": 24895,
"s": 24883,
"text": "Exceptions:"
},
{
"code": null,
"e": 24947,
"s": 24895,
"text": "DivideByZeroException: This occurs when a2 is zero."
},
{
"code": null,
"e": 25105,
"s": 24947,
"text": "OverflowException: If the result of dividing a1 and a2 is less than smallest possible value of Decimal or greater than the largest possible value of Decimal."
},
{
"code": null,
"e": 25183,
"s": 25105,
"text": "Below programs illustrate the use of Decimal.Divide(Decimal, Decimal) Method:"
},
{
"code": null,
"e": 25194,
"s": 25183,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Decimal.Divide(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 2.01m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine(\"Result of \"+ \"division : {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25907,
"s": 25194,
"text": null
},
{
"code": null,
"e": 25931,
"s": 25907,
"text": "Result of division : 2\n"
},
{
"code": null,
"e": 25972,
"s": 25931,
"text": "Example 2: Program for OverflowException"
},
{
"code": "// C# program to demonstrate the// Decimal.Divide(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = Decimal.MaxValue; Decimal a2 = 0.01m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine(\"Result of \"+ \"division : {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26698,
"s": 25972,
"text": null
},
{
"code": null,
"e": 26742,
"s": 26698,
"text": "Exception Thrown: System.OverflowException\n"
},
{
"code": null,
"e": 26787,
"s": 26742,
"text": "Example 3: Program for DivideByZeroException"
},
{
"code": "// C# program to demonstrate the// Decimal.Divide(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 0.00m; // dividing the two Decimal value // using Divide() method; Decimal value = Decimal.Divide(a1, a2); // Display the division Console.WriteLine(\"Result of\"+ \" division : {0}\", value); } catch (DivideByZeroException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 27502,
"s": 26787,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27502,
"text": "Exception Thrown: System.DivideByZeroException\n"
},
{
"code": null,
"e": 27561,
"s": 27550,
"text": "Reference:"
},
{
"code": null,
"e": 27651,
"s": 27561,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal.divide?view=netframework-4.7.2"
},
{
"code": null,
"e": 27670,
"s": 27651,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27692,
"s": 27670,
"text": "CSharp-Decimal-Struct"
},
{
"code": null,
"e": 27706,
"s": 27692,
"text": "CSharp-method"
},
{
"code": null,
"e": 27709,
"s": 27706,
"text": "C#"
},
{
"code": null,
"e": 27807,
"s": 27709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27825,
"s": 27807,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27871,
"s": 27825,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27886,
"s": 27871,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27926,
"s": 27886,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27944,
"s": 27926,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27967,
"s": 27944,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27998,
"s": 27967,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28020,
"s": 27998,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28042,
"s": 28020,
"text": "C# | Abstract Classes"
}
] |
Number of ways to represent a number as sum of k fibonacci numbers - GeeksforGeeks
|
13 May, 2021
Given two numbers N and K. Find the number of ways to represent N as the sum of K Fibonacci numbers. Examples:
Input : n = 12, k = 1
Output : 0
Input : n = 13, k = 3
Output : 2
Explanation : 2 + 3 + 8, 3 + 5 + 5.
Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i>1. Let’s suppose F(x, k, n) be the number of ways to form the sum x using exactly k numbers from f(0), f(1), ...f(n-1). To find a recurrence for F(x, k, n), notice that there are two cases: whether f(n-1) in the sum or not.
If f(n-1) is not in the sum, then x is formed as a sum using exactly k numbers from f(0), f(1), ..., f(n-2).
If f(n-1) is in the sum, then the remaining x-f(n-1) is formed using exactly k-1 numbers from f(0), f(1), ..., f(n-1). (Notice that f(n-1) is still included because duplicate numbers are allowed.).
So the recurrence relation will be:
F(x, k, n)= F(x, k, n-1)+F(x-f(n-1), k-1, n)
Base cases:
If k=0, then there are zero numbers from the series, so the sum can only be 0. Hence, F(0, 0, n)=1.
F(x, 0, n)=0, if x is not equals to 0.
Also, there are other cases that make F(x, k, n)=0, like the following:
If k>0 and x=0 because having at least one positive number must result in a positive sum.
If k>0 and n=0 because there’s no possible choice of numbers left.
If x<0 because there’s no way to form a negative sum using a finite number of nonnegative numbers.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // to store fibonacci numbers// 42 second number in fibonacci series// largest possible integerint fib[43] = { 0 }; // Function to generate fibonacci seriesvoid fibonacci(){ fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2];} // Recursive function to return the// number of waysint rec(int x, int y, int last){ // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 and fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum;} // Driver codeint main(){ fibonacci(); int n = 13, k = 3; cout << "Possible ways are: " << rec(n, k, 42); return 0;}
//Java implementation of above approachpublic class AQW { //to store fibonacci numbers //42 second number in fibonacci series //largest possible integer static int fib[] = new int[43]; //Function to generate fibonacci series static void fibonacci() { fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } //Recursive function to return the //number of ways static int rec(int x, int y, int last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } //Driver code public static void main(String[] args) { fibonacci(); int n = 13, k = 3; System.out.println("Possible ways are: "+ rec(n, k, 42)); } }
# Python3 implementation of the above approach # To store fibonacci numbers 42 second# number in fibonacci series largest# possible integerfib = [0] * 43 # Function to generate fibonacci# seriesdef fibonacci(): fib[0] = 1 fib[1] = 2 for i in range(2, 43): fib[i] = fib[i - 1] + fib[i - 2] # Recursive function to return the# number of waysdef rec(x, y, last): # base condition if y == 0: if x == 0: return 1 return 0 Sum, i = 0, last # for recursive function call while i >= 0 and fib[i] * y >= x: if fib[i] > x: i -= 1 continue Sum += rec(x - fib[i], y - 1, i) i -= 1 return Sum # Driver codeif __name__ == "__main__": fibonacci() n, k = 13, 3 print("Possible ways are:", rec(n, k, 42)) # This code is contributed# by Rituraj Jain
// C# implementation of above approachusing System; class GFG{ // to store fibonacci numbers // 42 second number in fibonacci series // largest possible integer static int[] fib = new int[43]; // Function to generate fibonacci series public static void fibonacci() { fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } // Recursive function to return the // number of ways public static int rec(int x, int y, int last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } // Driver code static void Main() { for(int i = 0; i < 43; i++) fib[i] = 0; fibonacci(); int n = 13, k = 3; Console.Write("Possible ways are: " + rec(n, k, 42)); } //This code is contributed by DrRoot_}
<?php// PHP implementation of above approach // To store fibonacci numbers// 42 second number in fibonacci series// largest possible integer$fib = array_fill(0, 43, 0); // Function to generate// fibonacci seriesfunction fibonacci(){ global $fib; $fib[0] = 1; $fib[1] = 2; for ($i = 2; $i < 43; $i++) $fib[$i] = $fib[$i - 1] + $fib[$i - 2];} // Recursive function to return// the number of waysfunction rec($x, $y, $last){ global $fib; // base condition if ($y == 0) { if ($x == 0) return 1; return 0; } $sum = 0; // for recursive function call for ($i = $last; $i >= 0 and $fib[$i] * $y >= $x; $i--) { if ($fib[$i] > $x) continue; $sum += rec($x - $fib[$i], $y - 1, $i); } return $sum;} // Driver codefibonacci();$n = 13;$k = 3;echo "Possible ways are: " . rec($n, $k, 42); // This code is contributed by mits?>
<script>//Javascript implementation of above approach //to store fibonacci numbers //42 second number in fibonacci series //largest possible integer let fib=new Array(43); //Function to generate fibonacci series function fibonacci() { fib[0] = 1; fib[1] = 2; for (let i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } //Recursive function to return the //number of ways function rec(x,y,last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } let sum = 0; // for recursive function call for (let i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } //Driver code fibonacci(); let n = 13, k = 3; document.write("Possible ways are: "+ rec(n, k, 42)); // This code is contributed by rag2127</script>
Possible ways are: 2
Mithun Kumar
DrRoot_
ukasp
rituraj_jain
rag2127
Algorithms-Dynamic Programming
Algorithms-Recursion
Fibonacci
Dynamic Programming
Dynamic Programming
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Maximum sum such that no two elements are adjacent
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Gold Mine Problem
Count All Palindrome Sub-Strings in a String | Set 1
3 Different ways to print Fibonacci series in Java
Optimal Binary Search Tree | DP-24
Word Break Problem | DP-32
Binomial Coefficient | DP-9
|
[
{
"code": null,
"e": 24307,
"s": 24279,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 24420,
"s": 24307,
"text": "Given two numbers N and K. Find the number of ways to represent N as the sum of K Fibonacci numbers. Examples: "
},
{
"code": null,
"e": 24526,
"s": 24420,
"text": "Input : n = 12, k = 1 \nOutput : 0\n\nInput : n = 13, k = 3\nOutput : 2\nExplanation : 2 + 3 + 8, 3 + 5 + 5. "
},
{
"code": null,
"e": 24831,
"s": 24528,
"text": "Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i>1. Let’s suppose F(x, k, n) be the number of ways to form the sum x using exactly k numbers from f(0), f(1), ...f(n-1). To find a recurrence for F(x, k, n), notice that there are two cases: whether f(n-1) in the sum or not. "
},
{
"code": null,
"e": 24940,
"s": 24831,
"text": "If f(n-1) is not in the sum, then x is formed as a sum using exactly k numbers from f(0), f(1), ..., f(n-2)."
},
{
"code": null,
"e": 25138,
"s": 24940,
"text": "If f(n-1) is in the sum, then the remaining x-f(n-1) is formed using exactly k-1 numbers from f(0), f(1), ..., f(n-1). (Notice that f(n-1) is still included because duplicate numbers are allowed.)."
},
{
"code": null,
"e": 25176,
"s": 25138,
"text": "So the recurrence relation will be: "
},
{
"code": null,
"e": 25221,
"s": 25176,
"text": "F(x, k, n)= F(x, k, n-1)+F(x-f(n-1), k-1, n)"
},
{
"code": null,
"e": 25235,
"s": 25221,
"text": "Base cases: "
},
{
"code": null,
"e": 25335,
"s": 25235,
"text": "If k=0, then there are zero numbers from the series, so the sum can only be 0. Hence, F(0, 0, n)=1."
},
{
"code": null,
"e": 25374,
"s": 25335,
"text": "F(x, 0, n)=0, if x is not equals to 0."
},
{
"code": null,
"e": 25448,
"s": 25374,
"text": "Also, there are other cases that make F(x, k, n)=0, like the following: "
},
{
"code": null,
"e": 25538,
"s": 25448,
"text": "If k>0 and x=0 because having at least one positive number must result in a positive sum."
},
{
"code": null,
"e": 25605,
"s": 25538,
"text": "If k>0 and n=0 because there’s no possible choice of numbers left."
},
{
"code": null,
"e": 25704,
"s": 25605,
"text": "If x<0 because there’s no way to form a negative sum using a finite number of nonnegative numbers."
},
{
"code": null,
"e": 25753,
"s": 25704,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25757,
"s": 25753,
"text": "C++"
},
{
"code": null,
"e": 25762,
"s": 25757,
"text": "Java"
},
{
"code": null,
"e": 25770,
"s": 25762,
"text": "Python3"
},
{
"code": null,
"e": 25773,
"s": 25770,
"text": "C#"
},
{
"code": null,
"e": 25777,
"s": 25773,
"text": "PHP"
},
{
"code": null,
"e": 25788,
"s": 25777,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // to store fibonacci numbers// 42 second number in fibonacci series// largest possible integerint fib[43] = { 0 }; // Function to generate fibonacci seriesvoid fibonacci(){ fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2];} // Recursive function to return the// number of waysint rec(int x, int y, int last){ // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 and fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum;} // Driver codeint main(){ fibonacci(); int n = 13, k = 3; cout << \"Possible ways are: \" << rec(n, k, 42); return 0;}",
"e": 26686,
"s": 25788,
"text": null
},
{
"code": "//Java implementation of above approachpublic class AQW { //to store fibonacci numbers //42 second number in fibonacci series //largest possible integer static int fib[] = new int[43]; //Function to generate fibonacci series static void fibonacci() { fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } //Recursive function to return the //number of ways static int rec(int x, int y, int last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } //Driver code public static void main(String[] args) { fibonacci(); int n = 13, k = 3; System.out.println(\"Possible ways are: \"+ rec(n, k, 42)); } }",
"e": 27700,
"s": 26686,
"text": null
},
{
"code": "# Python3 implementation of the above approach # To store fibonacci numbers 42 second# number in fibonacci series largest# possible integerfib = [0] * 43 # Function to generate fibonacci# seriesdef fibonacci(): fib[0] = 1 fib[1] = 2 for i in range(2, 43): fib[i] = fib[i - 1] + fib[i - 2] # Recursive function to return the# number of waysdef rec(x, y, last): # base condition if y == 0: if x == 0: return 1 return 0 Sum, i = 0, last # for recursive function call while i >= 0 and fib[i] * y >= x: if fib[i] > x: i -= 1 continue Sum += rec(x - fib[i], y - 1, i) i -= 1 return Sum # Driver codeif __name__ == \"__main__\": fibonacci() n, k = 13, 3 print(\"Possible ways are:\", rec(n, k, 42)) # This code is contributed# by Rituraj Jain",
"e": 28565,
"s": 27700,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // to store fibonacci numbers // 42 second number in fibonacci series // largest possible integer static int[] fib = new int[43]; // Function to generate fibonacci series public static void fibonacci() { fib[0] = 1; fib[1] = 2; for (int i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } // Recursive function to return the // number of ways public static int rec(int x, int y, int last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } int sum = 0; // for recursive function call for (int i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } // Driver code static void Main() { for(int i = 0; i < 43; i++) fib[i] = 0; fibonacci(); int n = 13, k = 3; Console.Write(\"Possible ways are: \" + rec(n, k, 42)); } //This code is contributed by DrRoot_}",
"e": 29745,
"s": 28565,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // To store fibonacci numbers// 42 second number in fibonacci series// largest possible integer$fib = array_fill(0, 43, 0); // Function to generate// fibonacci seriesfunction fibonacci(){ global $fib; $fib[0] = 1; $fib[1] = 2; for ($i = 2; $i < 43; $i++) $fib[$i] = $fib[$i - 1] + $fib[$i - 2];} // Recursive function to return// the number of waysfunction rec($x, $y, $last){ global $fib; // base condition if ($y == 0) { if ($x == 0) return 1; return 0; } $sum = 0; // for recursive function call for ($i = $last; $i >= 0 and $fib[$i] * $y >= $x; $i--) { if ($fib[$i] > $x) continue; $sum += rec($x - $fib[$i], $y - 1, $i); } return $sum;} // Driver codefibonacci();$n = 13;$k = 3;echo \"Possible ways are: \" . rec($n, $k, 42); // This code is contributed by mits?>",
"e": 30721,
"s": 29745,
"text": null
},
{
"code": "<script>//Javascript implementation of above approach //to store fibonacci numbers //42 second number in fibonacci series //largest possible integer let fib=new Array(43); //Function to generate fibonacci series function fibonacci() { fib[0] = 1; fib[1] = 2; for (let i = 2; i < 43; i++) fib[i] = fib[i - 1] + fib[i - 2]; } //Recursive function to return the //number of ways function rec(x,y,last) { // base condition if (y == 0) { if (x == 0) return 1; return 0; } let sum = 0; // for recursive function call for (let i = last; i >= 0 && fib[i] * y >= x; i--) { if (fib[i] > x) continue; sum += rec(x - fib[i], y - 1, i); } return sum; } //Driver code fibonacci(); let n = 13, k = 3; document.write(\"Possible ways are: \"+ rec(n, k, 42)); // This code is contributed by rag2127</script>",
"e": 31718,
"s": 30721,
"text": null
},
{
"code": null,
"e": 31739,
"s": 31718,
"text": "Possible ways are: 2"
},
{
"code": null,
"e": 31754,
"s": 31741,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31762,
"s": 31754,
"text": "DrRoot_"
},
{
"code": null,
"e": 31768,
"s": 31762,
"text": "ukasp"
},
{
"code": null,
"e": 31781,
"s": 31768,
"text": "rituraj_jain"
},
{
"code": null,
"e": 31789,
"s": 31781,
"text": "rag2127"
},
{
"code": null,
"e": 31820,
"s": 31789,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 31841,
"s": 31820,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 31851,
"s": 31841,
"text": "Fibonacci"
},
{
"code": null,
"e": 31871,
"s": 31851,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31891,
"s": 31871,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31901,
"s": 31891,
"text": "Fibonacci"
},
{
"code": null,
"e": 31999,
"s": 31901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32008,
"s": 31999,
"text": "Comments"
},
{
"code": null,
"e": 32021,
"s": 32008,
"text": "Old Comments"
},
{
"code": null,
"e": 32081,
"s": 32021,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 32132,
"s": 32081,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 32153,
"s": 32132,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 32209,
"s": 32153,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 32227,
"s": 32209,
"text": "Gold Mine Problem"
},
{
"code": null,
"e": 32280,
"s": 32227,
"text": "Count All Palindrome Sub-Strings in a String | Set 1"
},
{
"code": null,
"e": 32331,
"s": 32280,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 32366,
"s": 32331,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 32393,
"s": 32366,
"text": "Word Break Problem | DP-32"
}
] |
Date Class in Java
|
Java provides the Date class available in java. util package, this class encapsulates the current date and time.
The Date class supports two constructors as shown in the following table.
Following are the methods of the date class.
This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows −
Live Demo
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
This will produce the following result −
on May 04 09:51:52 CDT 2009
Following are the three ways to compare two dates −
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Java provides the Date class available in java. util package, this class encapsulates the current date and time."
},
{
"code": null,
"e": 1249,
"s": 1175,
"text": "The Date class supports two constructors as shown in the following table."
},
{
"code": null,
"e": 1294,
"s": 1249,
"text": "Following are the methods of the date class."
},
{
"code": null,
"e": 1463,
"s": 1294,
"text": "This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows −"
},
{
"code": null,
"e": 1473,
"s": 1463,
"text": "Live Demo"
},
{
"code": null,
"e": 1729,
"s": 1473,
"text": "import java.util.Date;\npublic class DateDemo {\n\n public static void main(String args[]) {\n // Instantiate a Date object\n Date date = new Date();\n\n // display time and date using toString()\n System.out.println(date.toString());\n }\n}"
},
{
"code": null,
"e": 1770,
"s": 1729,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1798,
"s": 1770,
"text": "on May 04 09:51:52 CDT 2009"
},
{
"code": null,
"e": 1850,
"s": 1798,
"text": "Following are the three ways to compare two dates −"
},
{
"code": null,
"e": 2013,
"s": 1850,
"text": "You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values."
},
{
"code": null,
"e": 2176,
"s": 2013,
"text": "You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values."
},
{
"code": null,
"e": 2365,
"s": 2176,
"text": "You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true."
},
{
"code": null,
"e": 2554,
"s": 2365,
"text": "You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true."
},
{
"code": null,
"e": 2661,
"s": 2554,
"text": "You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date."
},
{
"code": null,
"e": 2768,
"s": 2661,
"text": "You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date."
}
] |
Multithreading vs. Multiprocessing in Python | by Gennaro S. Rodrigues | Towards Data Science
|
Python is often regarded as an almost obscene programming language. A libertarian place where everything is permitted and our wildest dreams come true. Forget about labels and definitions, and, above all, brackets. It is a language that welcomes everyone, from the most experienced programmer (that weird guy that still uses Fortran for some reason you don’t really want to know about) to the egotistic millennial newbie. Well, that is, except if you are working with multiprocessing or multithreading.
The challenges of working with parallelism and concurrency in Python begins with the fact that even the internet does not understand very well how it works. Indeed, I’ve found multiple wrong statements on stackoverflow responses (some with a high count of up votes) and even very serious-looking blogs. Therefore, differently from other cases, where programming may also be called stackoverflowing, you better know at least the basics of what you are doing before starting to work with multiprocessing or multithreading in Python.
Or else, you might have a bad time.
When looking for the difference between python multiprocessing and multithreading, one might have the impression that they work pretty much the same. That could not be more wrong. The key differences are:
A process is an independent instance executed in a processor core. Threads are components of a process and run concurrently (inside that process).
Processes do not share the same memory space, while threads do (their mother’s memory, poetic, right?).
Threads are lighter and cause less overhead. Also, because they share the same memory inside a process, it is easier, faster, and safer to share data.
True parallelism can ONLY be achieved using multiprocessing. That is because only one thread can be executed at a given time inside a process time-space. This is assured by Python’s global interpreter lock (GIL) (see Python GIL at RealPython).
Processes execution is scheduled by the operating system, while threads are scheduled by the GIL.
We should also understand the difference between concurrency and parallelism.
Concurrent execution means that two or more tasks are progressing at the same time.
Parallel execution implies that two or more jobs are being executed simultaneously.
Now remember: multithreading implements concurrency, multiprocessing implements parallelism. Processes run on separate processing nodes.
So how do we decide between multiprocessing and multithreading? The short answer is:
Multithreading for I/O intensive tasks and;
Multiprocessing for CPU intensive tasks (if you have multiple cores available)
But why?
Imagine you have a task that relies on the input from another part of the system, or from the user.
There is no reason to dedicate a process for that job because it would spend most of its time waiting for the stimuli to begin its work. It would be a waste of resources to dedicate a computing node for that, and it would bring no speedup whatsoever, given that the bottleneck is not on execution but on a third-party call. In this case, multithreading is the way to go.
Indeed, multithreading is usually implemented to handle GUIs. E.g., in a text editor program, one thread would be responsible for getting input from the keyboard, while another would check the spelling, and a third one could handle the formatting configurations.
I/O intensive programs can also directly benefit from multithreading because their bottlenecks are usually reading or writing operations (or downloads in the case of web scrappers, for example). Check the following example:
This function loads some URL addresses into memory and writes them in a local text file (50 times, always overwriting the same file). That is pretty dumb, but its purpose is just to stress an I/O bound execution. You can check this code and execute it yourself in this Notebook.
Let us run that method over a list of 16 addresses and check their execution times for some different thread counts. That would get us the following graph (executing on a MacBook Air 2019).
Where the result for one thread stands for the serial execution of the code. We can see by the graphs that multithreading is capable of considerably reducing the algorithm’s execution time. We could keep increasing the number of threads, but the gains would stop once we reach the point where each address is handled by a thread.
Now imagine you got a massive amount of data loaded in memory, and it all needs to be processed. Programs that are computing-bound will benefit from multiprocessing because their bottleneck is time and resources. Image and graphics processing are an excellent example of that. They consist of vast amounts of math operations, which can often be divided into separate tasks because their data is independent. GPUs are the state-of-the-art hardware in this regard, being designed to process large chunks of data in parallel.
To simulate computing-intensive algorithm, we will use the following code:
Again, you can check this code in this notebook and execute it yourself (I strongly suggest you to take a look on that, as we have to make some workarounds to execute it properly on windows).
My MacBook features a dual-core processor with hyper-threading, so there is no use to force more than 4 processes running on it. Those are the results for the performance tests on this benchmark:
The multithreading provided no speedup (the execution times are virtually the same). However, we had a significant speedup when using multiprocessing. It was not enough to drop the execution time to one fourth of the original because of the time spent with process management. Remember that processes are much heavier than threads.
Even though this is not their best use case, there is no reason to expect multiprocessing to perform poorly on I/O intensive tasks. It is a waste of resources: imagine dedicating a processor core to a function that will, for a significant part of its execution, just wait for an input. A processor, even a cluster, only has so many processing nodes. We are better off dedicating them to real parallelism of applications that can only be accelerated by those means.
But for the sake of science, what would happen if we executed the first I/O-bound code using multiprocessing? The following graph shows it.
As expected, multiprocessing is also able to provide speedup on I/O bound computations. It is also noticeable that we kept the speedup even with 8 processes. The reason for that is processes start executing like threads in this case. The speedup is not coming from the parallelism, but from concurrency.
Now, let’s take a deeper look on how we can implement multiprocessing and multithreading in Python and how a Data Scientist can profit from them. There are many different ways to do it, and I encourage you to get some ideas from the documentation (here, here, and here) and try them out on the examples model I provided at this notebook as an exercise.
In a VERY broad aspect, a data science project follows four steps:
Get the data;Process the data;Do something with the data;Store other data
Get the data;
Process the data;
Do something with the data;
Store other data
Now, you may say: “nah, my project is way different”. Well, I beg to differ, but I’m sure you can follow this blog post to get some ideas on how to accelerate your own so-different-from-all-the-others project.
Remember the golden rule: multithreading for I/O bound tasks and multiprocessing for CPU bound task.
Now, it should not be hard to follow that the “get the data” and “store other data” steps are probably the ones where we should use multithreading. All the others (“process the data” and “do something with the data”) are most probably better off using multiprocessing. You may argue that processing a lot of data might present an I/O bottleneck, and in some cases you might be right. If that is your case, you should try to break up this processing into “getting data” and “processing data” parts, so that the best strategy can be applied to each of them.
Let’s see how we can apply what we’ve learned in a classic Natural Language Processing (NLP) problem: text classification. The idea is to find out the category of a news article just by its text (e.g.: if it should be categorised as “sports”, “finances”, “economy”, etc).
If you are here only to see how multiprocessing and multithreading can be used in a real project, just follow along, you don’t really need to know anything about NLP to understand this example. However, if you are interested by the subject, you should start by studying what word vectors are. I like this article. You can also follow this GitHub repository where I and a colleague have been working on some text classification models (there are some cool notebooks there).
Our project is quite simple, we will:
Get some data from Reuters News Agency containing news and their respective labels (defining what type of news they are) (Data source);Vectorize them using GloVe pre-trained word vectors (trained from Wikipedia) (GloVe project page);Train a model using Random Forests with scikit-learn to classify texts under the given labels.
Get some data from Reuters News Agency containing news and their respective labels (defining what type of news they are) (Data source);
Vectorize them using GloVe pre-trained word vectors (trained from Wikipedia) (GloVe project page);
Train a model using Random Forests with scikit-learn to classify texts under the given labels.
By now it shall be straightforward to see that step 1 can possibly be accelerated in Python using multithreading, while step 3 should use multiprocessing.
Let’s start by the pre-trained GloVe word vectors loading. You can check the full code and execute it yourself in this notebook. Loading this pre-trained word vector file can take a lot of time. The file is considerably long, and we have to process it line per line. Each line contains a word and then a list of values for each dimension of its word vector.
The GloveVectorizer() loads the pre-trained vectors in its __init__ function, and can do it both asynchronously or serially. This is how it performs the basic line-per-line file reading:
And here is the multithread implementation:
Again, I strongly recommend you to check how it was implemented in the full code.
The ThreadPoolExecutor runs its threads asynchronously. The last for loop is used to guarantee the execution will only keep going after all the threads submitted to the executor are finished. Check the Python Documentation for more details on how ThreadPoolExecutor works.
But how faster does the vectors loading gets with multithreading? In my MacBook Air the first serial version loads the 400000 word vectors in around 269.19898986816406s. The asynchronous approach loads the 400000 word vectors in 27.559515953063965s, using 10 workers (it could probably reach the same execution time with even less workers, as the bottleneck is reading the lines, not processing).
Now the cool part: training and testing.
Luckly for us, scikit-learn offers multiprocessing nativelly, just by setting it up on the model’s parameters. The two following code examples train a same model with the same data serially or using a set number of jobs (which are mapped to processes in scikit-learn).
Using multiprocessing in scikit-learn is as easy as setting the n_jobs model parameter. Here, we will set it to two:
It’s so easy you may doubt it works. But it does. The following bar graph shows the training time of this same model for different numbers of jobs:
Oh, and if you are curious, the model accuracy (RandomForestClassifier.scoreTrain) turns out not bad at all:
Train score: 0.9992707383773929Test score: 0.9346733668341709
I think it covers pretty much everything. This last example shows how Python multiprocessing and multithreading features can be used to accelerate real projects, and sometimes with little-to-none code modifications. All that glitters is not gold, though. You will soon find out, when looking forward to more complex parallel and asynchronous executions in python that things can get quite messy.
|
[
{
"code": null,
"e": 675,
"s": 172,
"text": "Python is often regarded as an almost obscene programming language. A libertarian place where everything is permitted and our wildest dreams come true. Forget about labels and definitions, and, above all, brackets. It is a language that welcomes everyone, from the most experienced programmer (that weird guy that still uses Fortran for some reason you don’t really want to know about) to the egotistic millennial newbie. Well, that is, except if you are working with multiprocessing or multithreading."
},
{
"code": null,
"e": 1206,
"s": 675,
"text": "The challenges of working with parallelism and concurrency in Python begins with the fact that even the internet does not understand very well how it works. Indeed, I’ve found multiple wrong statements on stackoverflow responses (some with a high count of up votes) and even very serious-looking blogs. Therefore, differently from other cases, where programming may also be called stackoverflowing, you better know at least the basics of what you are doing before starting to work with multiprocessing or multithreading in Python."
},
{
"code": null,
"e": 1242,
"s": 1206,
"text": "Or else, you might have a bad time."
},
{
"code": null,
"e": 1447,
"s": 1242,
"text": "When looking for the difference between python multiprocessing and multithreading, one might have the impression that they work pretty much the same. That could not be more wrong. The key differences are:"
},
{
"code": null,
"e": 1594,
"s": 1447,
"text": "A process is an independent instance executed in a processor core. Threads are components of a process and run concurrently (inside that process)."
},
{
"code": null,
"e": 1698,
"s": 1594,
"text": "Processes do not share the same memory space, while threads do (their mother’s memory, poetic, right?)."
},
{
"code": null,
"e": 1849,
"s": 1698,
"text": "Threads are lighter and cause less overhead. Also, because they share the same memory inside a process, it is easier, faster, and safer to share data."
},
{
"code": null,
"e": 2093,
"s": 1849,
"text": "True parallelism can ONLY be achieved using multiprocessing. That is because only one thread can be executed at a given time inside a process time-space. This is assured by Python’s global interpreter lock (GIL) (see Python GIL at RealPython)."
},
{
"code": null,
"e": 2191,
"s": 2093,
"text": "Processes execution is scheduled by the operating system, while threads are scheduled by the GIL."
},
{
"code": null,
"e": 2269,
"s": 2191,
"text": "We should also understand the difference between concurrency and parallelism."
},
{
"code": null,
"e": 2353,
"s": 2269,
"text": "Concurrent execution means that two or more tasks are progressing at the same time."
},
{
"code": null,
"e": 2437,
"s": 2353,
"text": "Parallel execution implies that two or more jobs are being executed simultaneously."
},
{
"code": null,
"e": 2574,
"s": 2437,
"text": "Now remember: multithreading implements concurrency, multiprocessing implements parallelism. Processes run on separate processing nodes."
},
{
"code": null,
"e": 2659,
"s": 2574,
"text": "So how do we decide between multiprocessing and multithreading? The short answer is:"
},
{
"code": null,
"e": 2703,
"s": 2659,
"text": "Multithreading for I/O intensive tasks and;"
},
{
"code": null,
"e": 2782,
"s": 2703,
"text": "Multiprocessing for CPU intensive tasks (if you have multiple cores available)"
},
{
"code": null,
"e": 2791,
"s": 2782,
"text": "But why?"
},
{
"code": null,
"e": 2891,
"s": 2791,
"text": "Imagine you have a task that relies on the input from another part of the system, or from the user."
},
{
"code": null,
"e": 3262,
"s": 2891,
"text": "There is no reason to dedicate a process for that job because it would spend most of its time waiting for the stimuli to begin its work. It would be a waste of resources to dedicate a computing node for that, and it would bring no speedup whatsoever, given that the bottleneck is not on execution but on a third-party call. In this case, multithreading is the way to go."
},
{
"code": null,
"e": 3525,
"s": 3262,
"text": "Indeed, multithreading is usually implemented to handle GUIs. E.g., in a text editor program, one thread would be responsible for getting input from the keyboard, while another would check the spelling, and a third one could handle the formatting configurations."
},
{
"code": null,
"e": 3749,
"s": 3525,
"text": "I/O intensive programs can also directly benefit from multithreading because their bottlenecks are usually reading or writing operations (or downloads in the case of web scrappers, for example). Check the following example:"
},
{
"code": null,
"e": 4028,
"s": 3749,
"text": "This function loads some URL addresses into memory and writes them in a local text file (50 times, always overwriting the same file). That is pretty dumb, but its purpose is just to stress an I/O bound execution. You can check this code and execute it yourself in this Notebook."
},
{
"code": null,
"e": 4218,
"s": 4028,
"text": "Let us run that method over a list of 16 addresses and check their execution times for some different thread counts. That would get us the following graph (executing on a MacBook Air 2019)."
},
{
"code": null,
"e": 4548,
"s": 4218,
"text": "Where the result for one thread stands for the serial execution of the code. We can see by the graphs that multithreading is capable of considerably reducing the algorithm’s execution time. We could keep increasing the number of threads, but the gains would stop once we reach the point where each address is handled by a thread."
},
{
"code": null,
"e": 5071,
"s": 4548,
"text": "Now imagine you got a massive amount of data loaded in memory, and it all needs to be processed. Programs that are computing-bound will benefit from multiprocessing because their bottleneck is time and resources. Image and graphics processing are an excellent example of that. They consist of vast amounts of math operations, which can often be divided into separate tasks because their data is independent. GPUs are the state-of-the-art hardware in this regard, being designed to process large chunks of data in parallel."
},
{
"code": null,
"e": 5146,
"s": 5071,
"text": "To simulate computing-intensive algorithm, we will use the following code:"
},
{
"code": null,
"e": 5338,
"s": 5146,
"text": "Again, you can check this code in this notebook and execute it yourself (I strongly suggest you to take a look on that, as we have to make some workarounds to execute it properly on windows)."
},
{
"code": null,
"e": 5534,
"s": 5338,
"text": "My MacBook features a dual-core processor with hyper-threading, so there is no use to force more than 4 processes running on it. Those are the results for the performance tests on this benchmark:"
},
{
"code": null,
"e": 5866,
"s": 5534,
"text": "The multithreading provided no speedup (the execution times are virtually the same). However, we had a significant speedup when using multiprocessing. It was not enough to drop the execution time to one fourth of the original because of the time spent with process management. Remember that processes are much heavier than threads."
},
{
"code": null,
"e": 6331,
"s": 5866,
"text": "Even though this is not their best use case, there is no reason to expect multiprocessing to perform poorly on I/O intensive tasks. It is a waste of resources: imagine dedicating a processor core to a function that will, for a significant part of its execution, just wait for an input. A processor, even a cluster, only has so many processing nodes. We are better off dedicating them to real parallelism of applications that can only be accelerated by those means."
},
{
"code": null,
"e": 6471,
"s": 6331,
"text": "But for the sake of science, what would happen if we executed the first I/O-bound code using multiprocessing? The following graph shows it."
},
{
"code": null,
"e": 6775,
"s": 6471,
"text": "As expected, multiprocessing is also able to provide speedup on I/O bound computations. It is also noticeable that we kept the speedup even with 8 processes. The reason for that is processes start executing like threads in this case. The speedup is not coming from the parallelism, but from concurrency."
},
{
"code": null,
"e": 7128,
"s": 6775,
"text": "Now, let’s take a deeper look on how we can implement multiprocessing and multithreading in Python and how a Data Scientist can profit from them. There are many different ways to do it, and I encourage you to get some ideas from the documentation (here, here, and here) and try them out on the examples model I provided at this notebook as an exercise."
},
{
"code": null,
"e": 7195,
"s": 7128,
"text": "In a VERY broad aspect, a data science project follows four steps:"
},
{
"code": null,
"e": 7269,
"s": 7195,
"text": "Get the data;Process the data;Do something with the data;Store other data"
},
{
"code": null,
"e": 7283,
"s": 7269,
"text": "Get the data;"
},
{
"code": null,
"e": 7301,
"s": 7283,
"text": "Process the data;"
},
{
"code": null,
"e": 7329,
"s": 7301,
"text": "Do something with the data;"
},
{
"code": null,
"e": 7346,
"s": 7329,
"text": "Store other data"
},
{
"code": null,
"e": 7556,
"s": 7346,
"text": "Now, you may say: “nah, my project is way different”. Well, I beg to differ, but I’m sure you can follow this blog post to get some ideas on how to accelerate your own so-different-from-all-the-others project."
},
{
"code": null,
"e": 7657,
"s": 7556,
"text": "Remember the golden rule: multithreading for I/O bound tasks and multiprocessing for CPU bound task."
},
{
"code": null,
"e": 8213,
"s": 7657,
"text": "Now, it should not be hard to follow that the “get the data” and “store other data” steps are probably the ones where we should use multithreading. All the others (“process the data” and “do something with the data”) are most probably better off using multiprocessing. You may argue that processing a lot of data might present an I/O bottleneck, and in some cases you might be right. If that is your case, you should try to break up this processing into “getting data” and “processing data” parts, so that the best strategy can be applied to each of them."
},
{
"code": null,
"e": 8485,
"s": 8213,
"text": "Let’s see how we can apply what we’ve learned in a classic Natural Language Processing (NLP) problem: text classification. The idea is to find out the category of a news article just by its text (e.g.: if it should be categorised as “sports”, “finances”, “economy”, etc)."
},
{
"code": null,
"e": 8958,
"s": 8485,
"text": "If you are here only to see how multiprocessing and multithreading can be used in a real project, just follow along, you don’t really need to know anything about NLP to understand this example. However, if you are interested by the subject, you should start by studying what word vectors are. I like this article. You can also follow this GitHub repository where I and a colleague have been working on some text classification models (there are some cool notebooks there)."
},
{
"code": null,
"e": 8996,
"s": 8958,
"text": "Our project is quite simple, we will:"
},
{
"code": null,
"e": 9324,
"s": 8996,
"text": "Get some data from Reuters News Agency containing news and their respective labels (defining what type of news they are) (Data source);Vectorize them using GloVe pre-trained word vectors (trained from Wikipedia) (GloVe project page);Train a model using Random Forests with scikit-learn to classify texts under the given labels."
},
{
"code": null,
"e": 9460,
"s": 9324,
"text": "Get some data from Reuters News Agency containing news and their respective labels (defining what type of news they are) (Data source);"
},
{
"code": null,
"e": 9559,
"s": 9460,
"text": "Vectorize them using GloVe pre-trained word vectors (trained from Wikipedia) (GloVe project page);"
},
{
"code": null,
"e": 9654,
"s": 9559,
"text": "Train a model using Random Forests with scikit-learn to classify texts under the given labels."
},
{
"code": null,
"e": 9809,
"s": 9654,
"text": "By now it shall be straightforward to see that step 1 can possibly be accelerated in Python using multithreading, while step 3 should use multiprocessing."
},
{
"code": null,
"e": 10167,
"s": 9809,
"text": "Let’s start by the pre-trained GloVe word vectors loading. You can check the full code and execute it yourself in this notebook. Loading this pre-trained word vector file can take a lot of time. The file is considerably long, and we have to process it line per line. Each line contains a word and then a list of values for each dimension of its word vector."
},
{
"code": null,
"e": 10354,
"s": 10167,
"text": "The GloveVectorizer() loads the pre-trained vectors in its __init__ function, and can do it both asynchronously or serially. This is how it performs the basic line-per-line file reading:"
},
{
"code": null,
"e": 10398,
"s": 10354,
"text": "And here is the multithread implementation:"
},
{
"code": null,
"e": 10480,
"s": 10398,
"text": "Again, I strongly recommend you to check how it was implemented in the full code."
},
{
"code": null,
"e": 10753,
"s": 10480,
"text": "The ThreadPoolExecutor runs its threads asynchronously. The last for loop is used to guarantee the execution will only keep going after all the threads submitted to the executor are finished. Check the Python Documentation for more details on how ThreadPoolExecutor works."
},
{
"code": null,
"e": 11150,
"s": 10753,
"text": "But how faster does the vectors loading gets with multithreading? In my MacBook Air the first serial version loads the 400000 word vectors in around 269.19898986816406s. The asynchronous approach loads the 400000 word vectors in 27.559515953063965s, using 10 workers (it could probably reach the same execution time with even less workers, as the bottleneck is reading the lines, not processing)."
},
{
"code": null,
"e": 11191,
"s": 11150,
"text": "Now the cool part: training and testing."
},
{
"code": null,
"e": 11460,
"s": 11191,
"text": "Luckly for us, scikit-learn offers multiprocessing nativelly, just by setting it up on the model’s parameters. The two following code examples train a same model with the same data serially or using a set number of jobs (which are mapped to processes in scikit-learn)."
},
{
"code": null,
"e": 11577,
"s": 11460,
"text": "Using multiprocessing in scikit-learn is as easy as setting the n_jobs model parameter. Here, we will set it to two:"
},
{
"code": null,
"e": 11725,
"s": 11577,
"text": "It’s so easy you may doubt it works. But it does. The following bar graph shows the training time of this same model for different numbers of jobs:"
},
{
"code": null,
"e": 11834,
"s": 11725,
"text": "Oh, and if you are curious, the model accuracy (RandomForestClassifier.scoreTrain) turns out not bad at all:"
},
{
"code": null,
"e": 11896,
"s": 11834,
"text": "Train score: 0.9992707383773929Test score: 0.9346733668341709"
}
] |
How to build a contextual assistant using RASA Forms | by Amal Menzli | Towards Data Science
|
We know very well that the ChatBots are the future of this generation and I believe that everyone must know the basics of how Chatbots work. This is exactly the aim of my article and I hope that after reading it you can build your own Bot.
You can find many tutorials on RASA that are using RASA APIs to build a Chatbot. But I haven’t recently found anything that talks in detail and simplifies my research like installation problems which for me was the most crucial part.
In this article, I will be happy to share with you my journey building a Chatbot with Rasa framework in which we will collect some information from the user. We will start by the installation part until speaking with the Bot.
Information Retrieval ChatBotsOverview of the RASA frameworkInstalling Rasa and its DependenciesBuild ChatBot that receives user information using forms
Information Retrieval ChatBots
Overview of the RASA framework
Installing Rasa and its Dependencies
Build ChatBot that receives user information using forms
A chatbot is a computer program or an artificial intelligence which conducts a conversation via auditory or textual methods. Such programs are often designed to convincingly simulate how a human would behave as a conversational partner. Chatbots are typically used in dialog systems for various practical purposes including customer service or information acquisition. Some chatbots use sophisticated natural language processing systems -but many simpler systems scan for keywords within the input- then pull a reply with the most matching keywords, or the most similar wording pattern, from a database. For more details about the Chatbot definition and for more basic understanding like What are intents? and Entities? You can check my previous article about chatbots in this link.
Nowadays, most of the chatbots are used for one specific application which is collecting a few pieces of information from a user in order to offer something (book a restaurant, search a database,etc.). This is also called slot filling. This class of bots is designed to provide human-like answers without human intervention. Here, the system tries to understand what question you are trying to ask. And answer you by giving such Form to fill to save your specific information.
In this article, we will build a chatbot to fill such a simple form for learning purposes. That’s why you need to follow me to the end.
RASA is an open-source Conversational AI framework. What I like the most about this framework, is data privacy, where you don’t need to worry about putting your data in someone else’s cloud-like Microsoft Luis or Amazon Lex. For now, there are 3 types of AI assistants:
Notifications Assistants: Capable of sending simple notifications, like a text message, push notification.
FAQ Assistants: The most common type of assistant today. It can answer simple questions, like FAQs.
Contextual Assistants: can handle any user goal gracefully and help accomplish it as best as possible. Which means that it is capable of understanding and responding to different and unexpected inputs.
RASA framework has three major components that work together to create contextual assistants:
RASA NLU: is Natural Language Understanding. Suppose the user says “I want to order a book”. NLU’s job is to take this input, understand the intent of the user, and find the entities in the input. For example, in the above sentence, the intent is ordering and the entity is a book. Rasa NLU internally uses Bag-of-Word (BoW) algorithm to find intent and Conditional Random Field (CRF) to find entities. Although you can use other algorithms for finding intent and entities using Rasa.
RASA CORE: Core is Rasa’s dialogue management component. It decides how an assistant should respond based on “the state of the conversation” and “the context”. Rasa Core learns by observing patterns in conversational data between users and an assistant. Rather than a bunch of if/else statements, it uses a machine learning model trained on example conversations to decide what to do next.
RASA X: is a toolset for developers to build, improve, and deploy contextual assistants with the Rasa framework. The good thing about Rasa X is that you can share your assistant with real users and collect the conversations they have with the bot, allowing you to improve it without interrupting the bot running in production.
Usage: After installing Rasa, you will find 3 files, namely:
domain.yml, stories.md, nlu.md
They define respectively the universe your bot lives in, the conversational backbone the bot has to follow, and the data on which it is trained to classify intents and entities.
Domain: defines the universe in which your bot operates. It specifies exactly:- which intents you are expecting to respond to- which slots you wish to track- which actions your bot can takeWhat are Slots?Slots are the things you want to keep track of during a conversation.
Actions: are the things your bot can do. For example, an action can:- respond to a user.- make an external API call.- query a database.
Stories: A training data sample for the dialogue system is called a story. This shows the bot how to act and react to the inputs given by the user. It starts with a name preceded by two hashes ##
NLU Data: The data to train the NLU. So, this is what it looks like:
The model is trained on these examples. The golden rule is, the more the examples (for each intent), the better the prediction.
Hence, depending on the definition and content of the above 3 files, your bot will be trained and will perform accordingly.
I have installed RASA in both windows 10 and Ubuntu 19.04. And to be honest, I always believe that the fastest way to begin building an AI assistant with RASA is on the command line, with very simple steps.You can install both Rasa (NLU and Core) and Rasa X with a single command, but you need first to upgrade your pip, here are the steps of installation in Ubuntu 19.04.
$python3 -m pip install --user --upgrade pip$python3 -m pip install --user rasa --default-timeout=100
Dependencies for spaCy: For more information on spaCy, check out the spaCy docs. You can install it with the following commands:
$python3 -m pip install --user -U spacy$python3 --user -m spacy download en_core_web_sm
Congratulations! You have successfully installed Rasa Open Source! 🥳
You can now create your new project. To do this, you need just to run:
$mkdir myfirst_Bot$cd myfirst_Bot$rasa init --no-prompt
The rasa init creates all the files that a Rasa project needs and trains a simple bot on some sample data. If you leave out the --no-prompt flag you will be asked some questions about how you want your project to be set up.
Now, it’s time to learn about some more advanced RASA features.
We know now that a contextual assistant goes beyond simple FAQ bot. It needs to have collected important details needed to answer user questions in the right context. In this article, I will show you how to build a simple demo Form Bot, about the admission process, it will ask you about your name, your SSN number, and the subject you want to learn.
So, how do you implement this ChatBot? 🤔 Glad you asked. 👇
To get started, we need to create a new folder you can name it whatever you want. Then run rasa init to create all the files that a RASA project needs.
The best part about the forms is that the assistant learns to handle the admission path from one single training story. To simplify the things and avoid a boring long article, the process of creating this Chatbot has been summarized in the gif with details. Check out the gif below for more illustration: 💡 👇👇
We can now, try Rasa X for depth understanding and verify if our validation function works fine or not. 👇
And it’s working!! 🎉🎉 👏 👏
Now, you can also create a simple but good conversational chatbot that behaves like a human. 😉😉
“One good conversation can shift the direction of change forever.” — Linda Lambert.
This was a tutorial to create a conversational ChatBot that uses Forms to receive information. Now, I think that you had the basics and you can add as much interactivity as you want to create your own ChatBot for a restaurant booking, doctor appointments, etc.
Through this article, I want to show you that creating Chatbots is neither easy nor tough. We used the capabilities of Rasa to create a bot with minimum training data. Rasa is a pretty useful library and you can experiment and tinker with it to create some truly useful chatbots. Don’t stop yourself here — go on and experiment more. 🤖👩💻
Happy reading, happy learning, and happy coding.
Let me know if you have any questions or if anything is unclear, you can contact me through my LinkedIn or send me an email if you want the source code for this project.
You can also check my previous article on building Chatbot:
medium.com
RASA documentation (Rasa basics).A tutorial from Justina on how to build contextual assistants with Rasa.
RASA documentation (Rasa basics).
A tutorial from Justina on how to build contextual assistants with Rasa.
|
[
{
"code": null,
"e": 412,
"s": 172,
"text": "We know very well that the ChatBots are the future of this generation and I believe that everyone must know the basics of how Chatbots work. This is exactly the aim of my article and I hope that after reading it you can build your own Bot."
},
{
"code": null,
"e": 646,
"s": 412,
"text": "You can find many tutorials on RASA that are using RASA APIs to build a Chatbot. But I haven’t recently found anything that talks in detail and simplifies my research like installation problems which for me was the most crucial part."
},
{
"code": null,
"e": 872,
"s": 646,
"text": "In this article, I will be happy to share with you my journey building a Chatbot with Rasa framework in which we will collect some information from the user. We will start by the installation part until speaking with the Bot."
},
{
"code": null,
"e": 1025,
"s": 872,
"text": "Information Retrieval ChatBotsOverview of the RASA frameworkInstalling Rasa and its DependenciesBuild ChatBot that receives user information using forms"
},
{
"code": null,
"e": 1056,
"s": 1025,
"text": "Information Retrieval ChatBots"
},
{
"code": null,
"e": 1087,
"s": 1056,
"text": "Overview of the RASA framework"
},
{
"code": null,
"e": 1124,
"s": 1087,
"text": "Installing Rasa and its Dependencies"
},
{
"code": null,
"e": 1181,
"s": 1124,
"text": "Build ChatBot that receives user information using forms"
},
{
"code": null,
"e": 1964,
"s": 1181,
"text": "A chatbot is a computer program or an artificial intelligence which conducts a conversation via auditory or textual methods. Such programs are often designed to convincingly simulate how a human would behave as a conversational partner. Chatbots are typically used in dialog systems for various practical purposes including customer service or information acquisition. Some chatbots use sophisticated natural language processing systems -but many simpler systems scan for keywords within the input- then pull a reply with the most matching keywords, or the most similar wording pattern, from a database. For more details about the Chatbot definition and for more basic understanding like What are intents? and Entities? You can check my previous article about chatbots in this link."
},
{
"code": null,
"e": 2441,
"s": 1964,
"text": "Nowadays, most of the chatbots are used for one specific application which is collecting a few pieces of information from a user in order to offer something (book a restaurant, search a database,etc.). This is also called slot filling. This class of bots is designed to provide human-like answers without human intervention. Here, the system tries to understand what question you are trying to ask. And answer you by giving such Form to fill to save your specific information."
},
{
"code": null,
"e": 2577,
"s": 2441,
"text": "In this article, we will build a chatbot to fill such a simple form for learning purposes. That’s why you need to follow me to the end."
},
{
"code": null,
"e": 2847,
"s": 2577,
"text": "RASA is an open-source Conversational AI framework. What I like the most about this framework, is data privacy, where you don’t need to worry about putting your data in someone else’s cloud-like Microsoft Luis or Amazon Lex. For now, there are 3 types of AI assistants:"
},
{
"code": null,
"e": 2954,
"s": 2847,
"text": "Notifications Assistants: Capable of sending simple notifications, like a text message, push notification."
},
{
"code": null,
"e": 3054,
"s": 2954,
"text": "FAQ Assistants: The most common type of assistant today. It can answer simple questions, like FAQs."
},
{
"code": null,
"e": 3256,
"s": 3054,
"text": "Contextual Assistants: can handle any user goal gracefully and help accomplish it as best as possible. Which means that it is capable of understanding and responding to different and unexpected inputs."
},
{
"code": null,
"e": 3350,
"s": 3256,
"text": "RASA framework has three major components that work together to create contextual assistants:"
},
{
"code": null,
"e": 3835,
"s": 3350,
"text": "RASA NLU: is Natural Language Understanding. Suppose the user says “I want to order a book”. NLU’s job is to take this input, understand the intent of the user, and find the entities in the input. For example, in the above sentence, the intent is ordering and the entity is a book. Rasa NLU internally uses Bag-of-Word (BoW) algorithm to find intent and Conditional Random Field (CRF) to find entities. Although you can use other algorithms for finding intent and entities using Rasa."
},
{
"code": null,
"e": 4225,
"s": 3835,
"text": "RASA CORE: Core is Rasa’s dialogue management component. It decides how an assistant should respond based on “the state of the conversation” and “the context”. Rasa Core learns by observing patterns in conversational data between users and an assistant. Rather than a bunch of if/else statements, it uses a machine learning model trained on example conversations to decide what to do next."
},
{
"code": null,
"e": 4552,
"s": 4225,
"text": "RASA X: is a toolset for developers to build, improve, and deploy contextual assistants with the Rasa framework. The good thing about Rasa X is that you can share your assistant with real users and collect the conversations they have with the bot, allowing you to improve it without interrupting the bot running in production."
},
{
"code": null,
"e": 4613,
"s": 4552,
"text": "Usage: After installing Rasa, you will find 3 files, namely:"
},
{
"code": null,
"e": 4644,
"s": 4613,
"text": "domain.yml, stories.md, nlu.md"
},
{
"code": null,
"e": 4822,
"s": 4644,
"text": "They define respectively the universe your bot lives in, the conversational backbone the bot has to follow, and the data on which it is trained to classify intents and entities."
},
{
"code": null,
"e": 5096,
"s": 4822,
"text": "Domain: defines the universe in which your bot operates. It specifies exactly:- which intents you are expecting to respond to- which slots you wish to track- which actions your bot can takeWhat are Slots?Slots are the things you want to keep track of during a conversation."
},
{
"code": null,
"e": 5232,
"s": 5096,
"text": "Actions: are the things your bot can do. For example, an action can:- respond to a user.- make an external API call.- query a database."
},
{
"code": null,
"e": 5428,
"s": 5232,
"text": "Stories: A training data sample for the dialogue system is called a story. This shows the bot how to act and react to the inputs given by the user. It starts with a name preceded by two hashes ##"
},
{
"code": null,
"e": 5497,
"s": 5428,
"text": "NLU Data: The data to train the NLU. So, this is what it looks like:"
},
{
"code": null,
"e": 5625,
"s": 5497,
"text": "The model is trained on these examples. The golden rule is, the more the examples (for each intent), the better the prediction."
},
{
"code": null,
"e": 5749,
"s": 5625,
"text": "Hence, depending on the definition and content of the above 3 files, your bot will be trained and will perform accordingly."
},
{
"code": null,
"e": 6122,
"s": 5749,
"text": "I have installed RASA in both windows 10 and Ubuntu 19.04. And to be honest, I always believe that the fastest way to begin building an AI assistant with RASA is on the command line, with very simple steps.You can install both Rasa (NLU and Core) and Rasa X with a single command, but you need first to upgrade your pip, here are the steps of installation in Ubuntu 19.04."
},
{
"code": null,
"e": 6224,
"s": 6122,
"text": "$python3 -m pip install --user --upgrade pip$python3 -m pip install --user rasa --default-timeout=100"
},
{
"code": null,
"e": 6353,
"s": 6224,
"text": "Dependencies for spaCy: For more information on spaCy, check out the spaCy docs. You can install it with the following commands:"
},
{
"code": null,
"e": 6441,
"s": 6353,
"text": "$python3 -m pip install --user -U spacy$python3 --user -m spacy download en_core_web_sm"
},
{
"code": null,
"e": 6510,
"s": 6441,
"text": "Congratulations! You have successfully installed Rasa Open Source! 🥳"
},
{
"code": null,
"e": 6581,
"s": 6510,
"text": "You can now create your new project. To do this, you need just to run:"
},
{
"code": null,
"e": 6637,
"s": 6581,
"text": "$mkdir myfirst_Bot$cd myfirst_Bot$rasa init --no-prompt"
},
{
"code": null,
"e": 6861,
"s": 6637,
"text": "The rasa init creates all the files that a Rasa project needs and trains a simple bot on some sample data. If you leave out the --no-prompt flag you will be asked some questions about how you want your project to be set up."
},
{
"code": null,
"e": 6925,
"s": 6861,
"text": "Now, it’s time to learn about some more advanced RASA features."
},
{
"code": null,
"e": 7276,
"s": 6925,
"text": "We know now that a contextual assistant goes beyond simple FAQ bot. It needs to have collected important details needed to answer user questions in the right context. In this article, I will show you how to build a simple demo Form Bot, about the admission process, it will ask you about your name, your SSN number, and the subject you want to learn."
},
{
"code": null,
"e": 7335,
"s": 7276,
"text": "So, how do you implement this ChatBot? 🤔 Glad you asked. 👇"
},
{
"code": null,
"e": 7487,
"s": 7335,
"text": "To get started, we need to create a new folder you can name it whatever you want. Then run rasa init to create all the files that a RASA project needs."
},
{
"code": null,
"e": 7797,
"s": 7487,
"text": "The best part about the forms is that the assistant learns to handle the admission path from one single training story. To simplify the things and avoid a boring long article, the process of creating this Chatbot has been summarized in the gif with details. Check out the gif below for more illustration: 💡 👇👇"
},
{
"code": null,
"e": 7903,
"s": 7797,
"text": "We can now, try Rasa X for depth understanding and verify if our validation function works fine or not. 👇"
},
{
"code": null,
"e": 7929,
"s": 7903,
"text": "And it’s working!! 🎉🎉 👏 👏"
},
{
"code": null,
"e": 8025,
"s": 7929,
"text": "Now, you can also create a simple but good conversational chatbot that behaves like a human. 😉😉"
},
{
"code": null,
"e": 8109,
"s": 8025,
"text": "“One good conversation can shift the direction of change forever.” — Linda Lambert."
},
{
"code": null,
"e": 8370,
"s": 8109,
"text": "This was a tutorial to create a conversational ChatBot that uses Forms to receive information. Now, I think that you had the basics and you can add as much interactivity as you want to create your own ChatBot for a restaurant booking, doctor appointments, etc."
},
{
"code": null,
"e": 8709,
"s": 8370,
"text": "Through this article, I want to show you that creating Chatbots is neither easy nor tough. We used the capabilities of Rasa to create a bot with minimum training data. Rasa is a pretty useful library and you can experiment and tinker with it to create some truly useful chatbots. Don’t stop yourself here — go on and experiment more. 🤖👩💻"
},
{
"code": null,
"e": 8758,
"s": 8709,
"text": "Happy reading, happy learning, and happy coding."
},
{
"code": null,
"e": 8928,
"s": 8758,
"text": "Let me know if you have any questions or if anything is unclear, you can contact me through my LinkedIn or send me an email if you want the source code for this project."
},
{
"code": null,
"e": 8988,
"s": 8928,
"text": "You can also check my previous article on building Chatbot:"
},
{
"code": null,
"e": 8999,
"s": 8988,
"text": "medium.com"
},
{
"code": null,
"e": 9105,
"s": 8999,
"text": "RASA documentation (Rasa basics).A tutorial from Justina on how to build contextual assistants with Rasa."
},
{
"code": null,
"e": 9139,
"s": 9105,
"text": "RASA documentation (Rasa basics)."
}
] |
gpic - Unix, Linux Command
|
It is the user’s responsibility to provide appropriate definitions of the
PS and
PE macros.
When the macro package being used does not supply such definitions
(for example, old versions of -ms),
appropriate definitions can be obtained with
-mpic: these will center each picture.
/usr/share/doc/groff/1.18.1.1/pic.ms
\centerline{\box\graph}
Actually, since the vbox has a height of zero this will produce
slightly more vertical space above the picture than below it;
\centerline{\raise 1em\box\graph}
would avoid this.
You must use a driver that supports the
tpic specials, version 2.
Lines beginning with
\ are passed through transparently; a
% is added to the end of the line to avoid unwanted spaces.
You can safely use this feature to change fonts or to
change the value of
\baselineskip. Anything else may well produce undesirable results; use at your own risk.
Lines beginning with a period are not given any special treatment.
.PS
copy thru % circle at ($1,$2) % until "END"
1 2
3 4
5 6
END
box
.PE
.PS
circle at (1,2)
circle at (3,4)
circle at (5,6)
box
.PE
.PS
x = 3
y = 3
[
x := 5
y = 5
]
print x " " y
.PE
x ^ y (exponentiation)
sin(x)
cos(x)
atan2(y, x)
log(x) (base 10)
exp(x) (base 10, ie
10^x)
sqrt(x)
int(x)
rand() (return a random number between 0 and 1)
rand(x) (return a random number between 1 and
x; deprecated)
srand(x) (set the random number seed)
max(e1, e2)
min(e1, e2)
!e
e1 && e2
e1 || e2
e1 == e2
e1 != e2
e1 >= e2
e1 > e2
e1 <= e2
e1 < e2
"str1" == "str2"
"str1" != "str2"
String comparison expressions must be parenthesised in some contexts
to avoid ambiguity.
circle thickness 1.5
circle shaded green outline black
for i = 1 to 4 do {
line from ‘i’th box.nw to ‘i+1’th box.se
}
It is necessary to feed this file into
groff without adding any page information, so you must check which
.PS and
.PE requests are actually called.
For example, the mm macro package adds a page number, which is very
annoying.
At the moment, calling standard
groff without any macro package works.
Alternatively, you can define your own requests, e.g. to do nothing:
.de PS
..
.de PE
..
groff itself does not provide direct conversion into other graphics file
formats.
But there are lots of possibilities if you first transform your picture
into PostScript® format using the
groff option
-Tps. Since this
ps-file lacks BoundingBox information it is not very useful by itself, but it
may be fed into other conversion programs, usually named
ps2other or
pstoother or the like.
Moreover, the PostScript interpreter
ghostscript (gs) has built-in graphics conversion devices that are called with the option
gs -sDEVICE=<devname>
Call
gs --help
for a list of the available devices.
As the Encapsulated PostScript File Format
EPS is getting more and more important, and the conversion wasn’t regarded
trivial in the past you might be interested to know that there is a
conversion tool named
ps2eps which does the right job.
It is much better than the tool
ps2epsi packaged with
gs.
For bitmapped graphic formats, you should use
pstopnm; the resulting (intermediate)
PNM file can be then converted to virtually any graphics format using the tools
of the
netpbm package .
$ cat sample.pic
.PS
ellipse "GPIC TEST";
.PE
$ gpic sample.pic
.lf 1 sample.pic
.lf 1
.PS 0.500i 0.750i
.\" 0 -0.25 0.75 0.25
.\" 0.000i 0.500i 0.750i 0.000i
.nr 00 \n(.u
.nf
.nr 0x 1
\h'0.750i'
.sp -1
\D't -1.000p'\h'1.000p'
.sp -1
\h'0.000i'\v'0.250i'\D'e0.750i 0.500i'
.sp -1
.lf 2
\h'0.375i-(\w'GPIC TEST'u/2u)'\v'0.250i-(0v/2u)+0v+0.22m'GPIC TEST
.sp -1
.sp 0.500i+1
.if \n(00 .fi
.br
.nr 0x 0
.lf 3
.PE
.lf 4
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": 10858,
"s": 10577,
"text": "\nIt is the user’s responsibility to provide appropriate definitions of the\nPS and\nPE macros.\nWhen the macro package being used does not supply such definitions\n(for example, old versions of -ms),\nappropriate definitions can be obtained with\n-mpic: these will center each picture.\n"
},
{
"code": null,
"e": 10897,
"s": 10858,
"text": "\n/usr/share/doc/groff/1.18.1.1/pic.ms "
},
{
"code": null,
"e": 10924,
"s": 10897,
"text": "\n \\centerline{\\box\\graph}\n"
},
{
"code": null,
"e": 11052,
"s": 10924,
"text": "\nActually, since the vbox has a height of zero this will produce\nslightly more vertical space above the picture than below it;\n"
},
{
"code": null,
"e": 11089,
"s": 11052,
"text": "\n \\centerline{\\raise 1em\\box\\graph}\n"
},
{
"code": null,
"e": 11109,
"s": 11089,
"text": "\nwould avoid this.\n"
},
{
"code": null,
"e": 11178,
"s": 11109,
"text": "\nYou must use a driver that supports the\ntpic specials, version 2.\n"
},
{
"code": null,
"e": 11529,
"s": 11178,
"text": "\nLines beginning with\n\\ are passed through transparently; a\n% is added to the end of the line to avoid unwanted spaces.\nYou can safely use this feature to change fonts or to\nchange the value of\n\\baselineskip. Anything else may well produce undesirable results; use at your own risk.\nLines beginning with a period are not given any special treatment.\n"
},
{
"code": null,
"e": 11602,
"s": 11529,
"text": ".PS\ncopy thru % circle at ($1,$2) % until \"END\"\n1 2\n3 4\n5 6\nEND\nbox\n.PE\n"
},
{
"code": null,
"e": 11663,
"s": 11602,
"text": ".PS\ncircle at (1,2)\ncircle at (3,4)\ncircle at (5,6)\nbox\n.PE\n"
},
{
"code": null,
"e": 11719,
"s": 11663,
"text": ".PS\nx = 3\ny = 3\n[\n x := 5\n y = 5\n]\nprint x \" \" y\n.PE\n"
},
{
"code": null,
"e": 12133,
"s": 11719,
"text": "\nx ^ y (exponentiation)\n\nsin(x) \ncos(x) \natan2(y, x) \nlog(x) (base 10)\n\nexp(x) (base 10, ie\n\n\n 10^x)\n\nsqrt(x) \nint(x) \nrand() (return a random number between 0 and 1)\n\nrand(x) (return a random number between 1 and\nx; deprecated)\n\nsrand(x) (set the random number seed)\n\nmax(e1, e2) \nmin(e1, e2) \n!e \ne1 && e2\n\ne1 || e2\n\ne1 == e2\n\ne1 != e2\n\ne1 >= e2\n\ne1 > e2\n\ne1 <= e2\n\ne1 < e2\n\n\"str1\" == \"str2\"\n\n\"str1\" != \"str2\"\n"
},
{
"code": null,
"e": 12224,
"s": 12133,
"text": "\nString comparison expressions must be parenthesised in some contexts\nto avoid ambiguity.\n"
},
{
"code": null,
"e": 12247,
"s": 12224,
"text": "\ncircle thickness 1.5 "
},
{
"code": null,
"e": 12287,
"s": 12247,
"text": "\ncircle shaded green outline black "
},
{
"code": null,
"e": 12354,
"s": 12287,
"text": "for i = 1 to 4 do {\n line from ‘i’th box.nw to ‘i+1’th box.se\n}\n"
},
{
"code": null,
"e": 12722,
"s": 12354,
"text": "\nIt is necessary to feed this file into\ngroff without adding any page information, so you must check which\n.PS and\n.PE requests are actually called.\nFor example, the mm macro package adds a page number, which is very\nannoying.\nAt the moment, calling standard\ngroff without any macro package works.\nAlternatively, you can define your own requests, e.g. to do nothing:\n"
},
{
"code": null,
"e": 12745,
"s": 12724,
"text": ".de PS\n..\n.de PE\n..\n"
},
{
"code": null,
"e": 13262,
"s": 12745,
"text": "\ngroff itself does not provide direct conversion into other graphics file\nformats.\nBut there are lots of possibilities if you first transform your picture\ninto PostScript® format using the\ngroff option\n-Tps. Since this\nps-file lacks BoundingBox information it is not very useful by itself, but it\nmay be fed into other conversion programs, usually named\nps2other or\npstoother or the like.\nMoreover, the PostScript interpreter\nghostscript (gs) has built-in graphics conversion devices that are called with the option\n"
},
{
"code": null,
"e": 13286,
"s": 13262,
"text": "\ngs -sDEVICE=<devname> "
},
{
"code": null,
"e": 13303,
"s": 13286,
"text": "\nCall\ngs --help "
},
{
"code": null,
"e": 13342,
"s": 13303,
"text": "\nfor a list of the available devices.\n"
},
{
"code": null,
"e": 13643,
"s": 13342,
"text": "\nAs the Encapsulated PostScript File Format\nEPS is getting more and more important, and the conversion wasn’t regarded\ntrivial in the past you might be interested to know that there is a\nconversion tool named\nps2eps which does the right job.\nIt is much better than the tool\nps2epsi packaged with\ngs. "
},
{
"code": null,
"e": 13833,
"s": 13643,
"text": "\nFor bitmapped graphic formats, you should use\npstopnm; the resulting (intermediate)\nPNM file can be then converted to virtually any graphics format using the tools\nof the\nnetpbm package .\n"
},
{
"code": null,
"e": 13880,
"s": 13833,
"text": "$ cat sample.pic\n.PS\nellipse \"GPIC TEST\";\n.PE\n"
},
{
"code": null,
"e": 14251,
"s": 13880,
"text": "$ gpic sample.pic\n.lf 1 sample.pic\n.lf 1\n.PS 0.500i 0.750i\n.\\\" 0 -0.25 0.75 0.25\n.\\\" 0.000i 0.500i 0.750i 0.000i\n.nr 00 \\n(.u\n.nf\n.nr 0x 1\n\\h'0.750i'\n.sp -1\n\\D't -1.000p'\\h'1.000p'\n.sp -1\n\\h'0.000i'\\v'0.250i'\\D'e0.750i 0.500i'\n.sp -1\n.lf 2\n\\h'0.375i-(\\w'GPIC TEST'u/2u)'\\v'0.250i-(0v/2u)+0v+0.22m'GPIC TEST\n.sp -1\n.sp 0.500i+1\n.if \\n(00 .fi\n.br\n.nr 0x 0\n.lf 3\n.PE\n.lf 4\n"
},
{
"code": null,
"e": 14286,
"s": 14251,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 14314,
"s": 14286,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14348,
"s": 14314,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 14365,
"s": 14348,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 14398,
"s": 14365,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 14409,
"s": 14398,
"text": " Pradeep D"
},
{
"code": null,
"e": 14444,
"s": 14409,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14460,
"s": 14444,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 14493,
"s": 14460,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 14505,
"s": 14493,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 14537,
"s": 14505,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 14545,
"s": 14537,
"text": " Uplatz"
},
{
"code": null,
"e": 14552,
"s": 14545,
"text": " Print"
},
{
"code": null,
"e": 14563,
"s": 14552,
"text": " Add Notes"
}
] |
Maximize the number by rearranging bits - GeeksforGeeks
|
15 Feb, 2022
Given an unsigned number, find the maximum number that could be formed by using the bits of the given unsigned number.
Examples :
Input : 1 (0000....0001)
Output : 2147483648 (1000....0000)
Input : 7 (0000....0111)
Output : 3758096384 (0111....0000)
Method 1 (Simple) 1. Find binary representation of the number using simple decimal to binary representation technique. 2. Count number of set bits in the binary representation equal to ‘n’. 3. Create a binary representation with its ‘n’ most significant bits set to 1. 4. Convert the binary representation back to the number.
C++
Java
Python3
C#
PHP
Javascript
// An simple C++ program to find// minimum number formed by bits of a// given number.#include <bits/stdc++.h>#define ll unsigned intusing namespace std; // Returns maximum number formed by// bits of a given number.ll maximize(ll a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. ll n = _popcnt32(a); // Set most significant n bits of res. ll res = 0; for (int i=1; i<=n; i++) res |= (1 << (32 - i)); return res;} // Driver function.int main(){ ll a = 1; cout << maximize(a) << endl; return 0;}
// An simple Java program to find// minimum number formed by bits// of a given number.import java.io.*; class GFG{ private static int _popcnt32(long number) { int counter = 0; while(number > 0) { if(number % 2 == 1) { counter++; } //or number = number >> 1 number = number / 2; } return counter; } // Returns maximum number formed // by bits of a given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. int n = _popcnt32(a); // Set most significant // n bits of res. long res = 0; for (int i = 1; i <= n; i++) res = (int)res | (1 << (32 - i)); return Math.abs(res); } // Driver Code public static void main(String args[]) { long a = 1; System.out.print(maximize(a)); }} // This code is contributed by// Manish Shaw(manishshaw1)
# An simple Python program to# find minimum number formed# by bits of a given number.def _popcnt32(number) : counter = 0 while(number > 0) : if(number % 2 == 1) : counter = counter + 1 # or number = number >> 1 number = int(number / 2) return counter # Returns maximum number formed# by bits of a given number.def maximize(a) : # _popcnt32(a) gives number # of 1's present in binary # representation of a. n = _popcnt32(a) # Set most significant # n bits of res. res = 0 for i in range(1, n + 1) : res = int(res | (1 << (32 - i))) return abs(res) # Driver Codea = 1print (maximize(a)) # This code is contributed by# Manish Shaw(manishshaw1)
// An simple C# program to find// minimum number formed by bits// of a given number.using System; class GFG{ // Returns maximum number formed // by bits of a given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. string binaryString = Convert.ToString(a, 2); int n = binaryString.Split(new [] {'0'}, StringSplitOptions.RemoveEmptyEntries).Length; // Set most significant n bits of res. long res = 0; for (int i = 1; i <= n; i++) res = (int)res | (1 << (32 - i)); return Math.Abs(res); } // Driver Code. static void Main() { long a = 1; Console.WriteLine(maximize(a)); }}// This code is contributed by// Manish Shaw(manishshaw1)
<?php// An simple PHP program to find// minimum number formed by bits// of a given number.function _popcnt32($number){ $counter = 0; while($number > 0) { if($number % 2 == 1) { $counter++; } //or number = number >> 1 $number = intval($number / 2); } return $counter;} // Returns maximum number formed// by bits of a given number.function maximize($a){ // _popcnt32(a) gives number // of 1's present in binary // representation of a. $n = _popcnt32($a); // Set most significant // n bits of res. $res = 0; for ($i = 1; $i <= $n; $i++) $res = intval($res | (1 << (32 - $i))); return abs($res);} // Driver Code$a = 1;echo (maximize($a)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // An simple JavaScript program to find// minimum number formed by bits of a// given number. function _popcnt32(number){ var counter = 0; while(number > 0) { if(number % 2 == 1) { counter++; } //or number = number >> 1 number = parseInt(number / 2); } return counter;} // Returns maximum number formed by// bits of a given number.function maximize(a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. var n = _popcnt32(a); // Set most significant n bits of res. var res = 0; for (var i=1; i<=n; i++) res |= (1 << (32 - i)); return Math.abs(res);} // Driver function.var a = 1;document.write(maximize(a)); </script>
2147483648
Method 2 (Efficient) The idea is to first find a number with n least significant set bits, then shift the number left by 32-n.
C++
Java
Python3
C#
PHP
// An efficient C++ program to find// minimum number formed by bits of a// given number.#include <bits/stdc++.h>#define ll unsigned intusing namespace std; // Returns maximum number formed by// bits of a given number.ll maximize(ll a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. ll n = _popcnt32(a); // If all 32 bits are set. if (n == 32) return a; // find a number with n least // significant set bits. ll res = (1 << n) - 1; // Now shift result by 32 - n return (res << (32 - n)) ;} // Driver function.int main(){ ll a = 3; cout << maximize(a) << endl; return 0;}
// An efficient Java program to// find minimum number formed// by bits of a given number.import java.io.*; class GFG{ static long _popcnt32(long n) { long count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } // Returns maximum number // formed by bits of a // given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. long n = _popcnt32(a); // If along 32 // bits are set. if (n == 32) return a; // find a number with // n least significant // set bits. long res = (1 << n) - 1; // Now shift result // by 32 - n return (res << (32 - n)) ; } // Driver Code public static void main(String args[]) { long a = 3; System.out.print(maximize(a)); }} // This code is contributed by// ManishShaw(manishshaw1)
# An efficient python3 program to find# minimum number formed by bits of a# given number.def _popcnt32(n): count = 0 while (n != 0): n = n & (n - 1) count = count + 1 return count # Returns maximum number formed by# bits of a given number.def maximize(a): # _popcnt32(a) gives number of 1's # present in binary representation of a. n = _popcnt32(a) # If all 32 bits are set. if (n == 32): return a # Find a number with n least # significant set bits. res = (1 << n) - 1 # Now shift result by 32 - n return (res << (32 - n)) # Driver codeif __name__ == '__main__': a = 3 print(maximize(a)) # This code is contributed by nirajgusain5
// An efficient C# program to// find minimum number formed// by bits of a given number.using System; class GFG{ static long _popcnt32(long n) { long count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } // Returns maximum number // formed by bits of a // given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. long n = _popcnt32(a); // If along 32 // bits are set. if (n == 32) return a; // find a number with n // least significant set bits. long res = (1 << Convert.ToInt32(n)) - 1; // Now shift result // by 32 - n return (res << (32 - Convert.ToInt32(n))) ; } // Driver Code static void Main() { long a = 3; Console.WriteLine(maximize(a)); }} // This code is contributed by// ManishShaw(manishshaw1)
<?php// An efficient Java program to// find minimum number formed// by bits of a given number. function _popcnt32($n){ $count = 0; while ($n != 0) { $n = $n & ($n - 1); $count++; } return $count;} // Returns maximum number// formed by bits of a// given number.function maximize($a){ // _popcnt32(a) gives number // of 1's present in binary // representation of a. $n = _popcnt32($a); // If a$32 // bits are set. if ($n == 32) return $a; // find a number with // n least significant // set bits. $res = (1 << $n) - 1; // Now shift result // by 32 - n return ($res << (32 - $n)) ;} // Driver Code$a = 3;echo (maximize($a)); // This code is contributed by// ManishShaw(manishshaw1)?>
3221225472
Note: The above codes use GCC specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer.
manishshaw1
itsok
nirajgusain5
simmytarika5
Bit Magic
C Language
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Reverse actual bits of the given number
Program to find parity
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
|
[
{
"code": null,
"e": 24621,
"s": 24593,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 24740,
"s": 24621,
"text": "Given an unsigned number, find the maximum number that could be formed by using the bits of the given unsigned number."
},
{
"code": null,
"e": 24752,
"s": 24740,
"text": "Examples : "
},
{
"code": null,
"e": 24873,
"s": 24752,
"text": "Input : 1 (0000....0001)\nOutput : 2147483648 (1000....0000)\n\nInput : 7 (0000....0111)\nOutput : 3758096384 (0111....0000)"
},
{
"code": null,
"e": 25200,
"s": 24873,
"text": "Method 1 (Simple) 1. Find binary representation of the number using simple decimal to binary representation technique. 2. Count number of set bits in the binary representation equal to ‘n’. 3. Create a binary representation with its ‘n’ most significant bits set to 1. 4. Convert the binary representation back to the number. "
},
{
"code": null,
"e": 25204,
"s": 25200,
"text": "C++"
},
{
"code": null,
"e": 25209,
"s": 25204,
"text": "Java"
},
{
"code": null,
"e": 25217,
"s": 25209,
"text": "Python3"
},
{
"code": null,
"e": 25220,
"s": 25217,
"text": "C#"
},
{
"code": null,
"e": 25224,
"s": 25220,
"text": "PHP"
},
{
"code": null,
"e": 25235,
"s": 25224,
"text": "Javascript"
},
{
"code": "// An simple C++ program to find// minimum number formed by bits of a// given number.#include <bits/stdc++.h>#define ll unsigned intusing namespace std; // Returns maximum number formed by// bits of a given number.ll maximize(ll a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. ll n = _popcnt32(a); // Set most significant n bits of res. ll res = 0; for (int i=1; i<=n; i++) res |= (1 << (32 - i)); return res;} // Driver function.int main(){ ll a = 1; cout << maximize(a) << endl; return 0;}",
"e": 25799,
"s": 25235,
"text": null
},
{
"code": "// An simple Java program to find// minimum number formed by bits// of a given number.import java.io.*; class GFG{ private static int _popcnt32(long number) { int counter = 0; while(number > 0) { if(number % 2 == 1) { counter++; } //or number = number >> 1 number = number / 2; } return counter; } // Returns maximum number formed // by bits of a given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. int n = _popcnt32(a); // Set most significant // n bits of res. long res = 0; for (int i = 1; i <= n; i++) res = (int)res | (1 << (32 - i)); return Math.abs(res); } // Driver Code public static void main(String args[]) { long a = 1; System.out.print(maximize(a)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 26876,
"s": 25799,
"text": null
},
{
"code": "# An simple Python program to# find minimum number formed# by bits of a given number.def _popcnt32(number) : counter = 0 while(number > 0) : if(number % 2 == 1) : counter = counter + 1 # or number = number >> 1 number = int(number / 2) return counter # Returns maximum number formed# by bits of a given number.def maximize(a) : # _popcnt32(a) gives number # of 1's present in binary # representation of a. n = _popcnt32(a) # Set most significant # n bits of res. res = 0 for i in range(1, n + 1) : res = int(res | (1 << (32 - i))) return abs(res) # Driver Codea = 1print (maximize(a)) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 27646,
"s": 26876,
"text": null
},
{
"code": "// An simple C# program to find// minimum number formed by bits// of a given number.using System; class GFG{ // Returns maximum number formed // by bits of a given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. string binaryString = Convert.ToString(a, 2); int n = binaryString.Split(new [] {'0'}, StringSplitOptions.RemoveEmptyEntries).Length; // Set most significant n bits of res. long res = 0; for (int i = 1; i <= n; i++) res = (int)res | (1 << (32 - i)); return Math.Abs(res); } // Driver Code. static void Main() { long a = 1; Console.WriteLine(maximize(a)); }}// This code is contributed by// Manish Shaw(manishshaw1)",
"e": 28503,
"s": 27646,
"text": null
},
{
"code": "<?php// An simple PHP program to find// minimum number formed by bits// of a given number.function _popcnt32($number){ $counter = 0; while($number > 0) { if($number % 2 == 1) { $counter++; } //or number = number >> 1 $number = intval($number / 2); } return $counter;} // Returns maximum number formed// by bits of a given number.function maximize($a){ // _popcnt32(a) gives number // of 1's present in binary // representation of a. $n = _popcnt32($a); // Set most significant // n bits of res. $res = 0; for ($i = 1; $i <= $n; $i++) $res = intval($res | (1 << (32 - $i))); return abs($res);} // Driver Code$a = 1;echo (maximize($a)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 29333,
"s": 28503,
"text": null
},
{
"code": "<script> // An simple JavaScript program to find// minimum number formed by bits of a// given number. function _popcnt32(number){ var counter = 0; while(number > 0) { if(number % 2 == 1) { counter++; } //or number = number >> 1 number = parseInt(number / 2); } return counter;} // Returns maximum number formed by// bits of a given number.function maximize(a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. var n = _popcnt32(a); // Set most significant n bits of res. var res = 0; for (var i=1; i<=n; i++) res |= (1 << (32 - i)); return Math.abs(res);} // Driver function.var a = 1;document.write(maximize(a)); </script>",
"e": 30092,
"s": 29333,
"text": null
},
{
"code": null,
"e": 30103,
"s": 30092,
"text": "2147483648"
},
{
"code": null,
"e": 30233,
"s": 30105,
"text": "Method 2 (Efficient) The idea is to first find a number with n least significant set bits, then shift the number left by 32-n. "
},
{
"code": null,
"e": 30237,
"s": 30233,
"text": "C++"
},
{
"code": null,
"e": 30242,
"s": 30237,
"text": "Java"
},
{
"code": null,
"e": 30250,
"s": 30242,
"text": "Python3"
},
{
"code": null,
"e": 30253,
"s": 30250,
"text": "C#"
},
{
"code": null,
"e": 30257,
"s": 30253,
"text": "PHP"
},
{
"code": "// An efficient C++ program to find// minimum number formed by bits of a// given number.#include <bits/stdc++.h>#define ll unsigned intusing namespace std; // Returns maximum number formed by// bits of a given number.ll maximize(ll a){ // _popcnt32(a) gives number of 1's // present in binary representation of a. ll n = _popcnt32(a); // If all 32 bits are set. if (n == 32) return a; // find a number with n least // significant set bits. ll res = (1 << n) - 1; // Now shift result by 32 - n return (res << (32 - n)) ;} // Driver function.int main(){ ll a = 3; cout << maximize(a) << endl; return 0;}",
"e": 30914,
"s": 30257,
"text": null
},
{
"code": "// An efficient Java program to// find minimum number formed// by bits of a given number.import java.io.*; class GFG{ static long _popcnt32(long n) { long count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } // Returns maximum number // formed by bits of a // given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. long n = _popcnt32(a); // If along 32 // bits are set. if (n == 32) return a; // find a number with // n least significant // set bits. long res = (1 << n) - 1; // Now shift result // by 32 - n return (res << (32 - n)) ; } // Driver Code public static void main(String args[]) { long a = 3; System.out.print(maximize(a)); }} // This code is contributed by// ManishShaw(manishshaw1)",
"e": 31945,
"s": 30914,
"text": null
},
{
"code": "# An efficient python3 program to find# minimum number formed by bits of a# given number.def _popcnt32(n): count = 0 while (n != 0): n = n & (n - 1) count = count + 1 return count # Returns maximum number formed by# bits of a given number.def maximize(a): # _popcnt32(a) gives number of 1's # present in binary representation of a. n = _popcnt32(a) # If all 32 bits are set. if (n == 32): return a # Find a number with n least # significant set bits. res = (1 << n) - 1 # Now shift result by 32 - n return (res << (32 - n)) # Driver codeif __name__ == '__main__': a = 3 print(maximize(a)) # This code is contributed by nirajgusain5",
"e": 32671,
"s": 31945,
"text": null
},
{
"code": "// An efficient C# program to// find minimum number formed// by bits of a given number.using System; class GFG{ static long _popcnt32(long n) { long count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } // Returns maximum number // formed by bits of a // given number. static long maximize(long a) { // _popcnt32(a) gives number // of 1's present in binary // representation of a. long n = _popcnt32(a); // If along 32 // bits are set. if (n == 32) return a; // find a number with n // least significant set bits. long res = (1 << Convert.ToInt32(n)) - 1; // Now shift result // by 32 - n return (res << (32 - Convert.ToInt32(n))) ; } // Driver Code static void Main() { long a = 3; Console.WriteLine(maximize(a)); }} // This code is contributed by// ManishShaw(manishshaw1)",
"e": 33701,
"s": 32671,
"text": null
},
{
"code": "<?php// An efficient Java program to// find minimum number formed// by bits of a given number. function _popcnt32($n){ $count = 0; while ($n != 0) { $n = $n & ($n - 1); $count++; } return $count;} // Returns maximum number// formed by bits of a// given number.function maximize($a){ // _popcnt32(a) gives number // of 1's present in binary // representation of a. $n = _popcnt32($a); // If a$32 // bits are set. if ($n == 32) return $a; // find a number with // n least significant // set bits. $res = (1 << $n) - 1; // Now shift result // by 32 - n return ($res << (32 - $n)) ;} // Driver Code$a = 3;echo (maximize($a)); // This code is contributed by// ManishShaw(manishshaw1)?>",
"e": 34467,
"s": 33701,
"text": null
},
{
"code": null,
"e": 34478,
"s": 34467,
"text": "3221225472"
},
{
"code": null,
"e": 34618,
"s": 34480,
"text": "Note: The above codes use GCC specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer. "
},
{
"code": null,
"e": 34630,
"s": 34618,
"text": "manishshaw1"
},
{
"code": null,
"e": 34636,
"s": 34630,
"text": "itsok"
},
{
"code": null,
"e": 34649,
"s": 34636,
"text": "nirajgusain5"
},
{
"code": null,
"e": 34662,
"s": 34649,
"text": "simmytarika5"
},
{
"code": null,
"e": 34672,
"s": 34662,
"text": "Bit Magic"
},
{
"code": null,
"e": 34683,
"s": 34672,
"text": "C Language"
},
{
"code": null,
"e": 34693,
"s": 34683,
"text": "Bit Magic"
},
{
"code": null,
"e": 34791,
"s": 34693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34800,
"s": 34791,
"text": "Comments"
},
{
"code": null,
"e": 34813,
"s": 34800,
"text": "Old Comments"
},
{
"code": null,
"e": 34864,
"s": 34813,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34901,
"s": 34864,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 34965,
"s": 34901,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 35005,
"s": 34965,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 35028,
"s": 35005,
"text": "Program to find parity"
},
{
"code": null,
"e": 35106,
"s": 35028,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 35122,
"s": 35106,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35145,
"s": 35122,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 35180,
"s": 35145,
"text": "Multidimensional Arrays in C / C++"
}
] |
How to Sort LinkedHashSet Elements in Descending Order in Java? - GeeksforGeeks
|
23 Feb, 2022
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet iteration is through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted.
Elements in HashSet does maintain order while TreeSet maintains objects in sorted order defined by either comparable or comparator method in Java. TreeSet elements are sorted in ascending order by default. So now the problem that occurs is to sort given HashSet in descending order. So here with the help of a TreeSet is necessary to store the element in descending order.
Illustration:
Input : LinkedHashSet = [4, 3, 6, 5, 8]
Output: LinkedHashSet = [8, 6, 5, 4, 3]
Input: LinkedHashSet = [22, 44, 33, 66, 55]
Output: LinkedHashSet = [66, 55, 44, 33, 22]
Algorithm:
Create HashSet to take input and store all the elements from the user.
Now, create TreeSet which stores the elements in decreasing order by adding all the elements from above HashSet in reverse order.
Create HashSet to take input and store all the elements from the user.
Now, create TreeSet which stores the elements in decreasing order by adding all the elements from above HashSet in reverse order.
Pseude Code: TreeSet<Integer> ts = new TreeSet<>(Collections.reverseOrder());
ts.addAll(lh);
Example:
Java
// Java Program to sort LinkedHashSet elements
// in descending order
// Importing java generic libraries
import java.util.*;
import java.io.*;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating and Initializing LinkedHashSet
Set<Integer> linkhasset
= new LinkedHashSet<Integer>();
// Adding elements to above LinkedHashSet
// Custom inputs
linkhasset.add(26);
linkhasset.add(23);
linkhasset.add(24);
linkhasset.add(21);
linkhasset.add(25);
linkhasset.add(22);
// TreeSet storing elements in descending order by
// adding all elements of HashSet in reverse order
TreeSet<Integer> ts
= new TreeSet<>(Collections.reverseOrder());
// Add all elements from LinkedHashSet to TreeSet
ts.addAll(linkhasset);
// Print all elements of TreeSet
System.out.println("Element in descending order : "
+ ts);
}
}
Element in descending order : [26, 25, 24, 23, 22, 21]
simmytarika5
varshagumber28
java-LinkedHashSet
Picked
Java
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23629,
"s": 23598,
"text": " \n23 Feb, 2022\n"
},
{
"code": null,
"e": 24094,
"s": 23629,
"text": "The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet iteration is through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted."
},
{
"code": null,
"e": 24467,
"s": 24094,
"text": "Elements in HashSet does maintain order while TreeSet maintains objects in sorted order defined by either comparable or comparator method in Java. TreeSet elements are sorted in ascending order by default. So now the problem that occurs is to sort given HashSet in descending order. So here with the help of a TreeSet is necessary to store the element in descending order."
},
{
"code": null,
"e": 24481,
"s": 24467,
"text": "Illustration:"
},
{
"code": null,
"e": 24651,
"s": 24481,
"text": "Input : LinkedHashSet = [4, 3, 6, 5, 8]\nOutput: LinkedHashSet = [8, 6, 5, 4, 3]\n\nInput: LinkedHashSet = [22, 44, 33, 66, 55]\nOutput: LinkedHashSet = [66, 55, 44, 33, 22]"
},
{
"code": null,
"e": 24663,
"s": 24651,
"text": "Algorithm: "
},
{
"code": null,
"e": 24866,
"s": 24663,
"text": "\nCreate HashSet to take input and store all the elements from the user.\nNow, create TreeSet which stores the elements in decreasing order by adding all the elements from above HashSet in reverse order.\n"
},
{
"code": null,
"e": 24937,
"s": 24866,
"text": "Create HashSet to take input and store all the elements from the user."
},
{
"code": null,
"e": 25067,
"s": 24937,
"text": "Now, create TreeSet which stores the elements in decreasing order by adding all the elements from above HashSet in reverse order."
},
{
"code": null,
"e": 25173,
"s": 25067,
"text": "Pseude Code: TreeSet<Integer> ts = new TreeSet<>(Collections.reverseOrder());\n ts.addAll(lh);"
},
{
"code": null,
"e": 25182,
"s": 25173,
"text": "Example:"
},
{
"code": null,
"e": 25187,
"s": 25182,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to sort LinkedHashSet elements\n// in descending order\n \n// Importing java generic libraries\nimport java.util.*;\nimport java.io.*;\n \n// Class\npublic class GFG {\n \n // Main driver method\n public static void main(String[] args)\n {\n // Creating and Initializing LinkedHashSet\n Set<Integer> linkhasset\n = new LinkedHashSet<Integer>();\n \n // Adding elements to above LinkedHashSet\n // Custom inputs\n linkhasset.add(26);\n linkhasset.add(23);\n linkhasset.add(24);\n linkhasset.add(21);\n linkhasset.add(25);\n linkhasset.add(22);\n \n // TreeSet storing elements in descending order by\n // adding all elements of HashSet in reverse order\n TreeSet<Integer> ts\n = new TreeSet<>(Collections.reverseOrder());\n \n // Add all elements from LinkedHashSet to TreeSet\n ts.addAll(linkhasset);\n \n // Print all elements of TreeSet\n System.out.println(\"Element in descending order : \"\n + ts);\n }\n}\n\n\n\n\n\n",
"e": 26276,
"s": 25197,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26276,
"text": "Element in descending order : [26, 25, 24, 23, 22, 21]"
},
{
"code": null,
"e": 26349,
"s": 26336,
"text": "simmytarika5"
},
{
"code": null,
"e": 26364,
"s": 26349,
"text": "varshagumber28"
},
{
"code": null,
"e": 26385,
"s": 26364,
"text": "\njava-LinkedHashSet\n"
},
{
"code": null,
"e": 26394,
"s": 26385,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26401,
"s": 26394,
"text": "\nJava\n"
},
{
"code": null,
"e": 26417,
"s": 26401,
"text": "\nJava Programs\n"
},
{
"code": null,
"e": 26622,
"s": 26417,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26640,
"s": 26622,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 26661,
"s": 26640,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26707,
"s": 26661,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26750,
"s": 26707,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26790,
"s": 26750,
"text": "Java Math random() method with Examples"
},
{
"code": null,
"e": 26834,
"s": 26790,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26860,
"s": 26834,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26894,
"s": 26860,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26941,
"s": 26894,
"text": "Implementing a Linked List in Java using Class"
}
] |
Tile (Slice) YOLO Dataset for Small Objects Detection | by Rostyslav Neskorozhenyi | Towards Data Science
|
In one of my projects I was faced with the task of detecting very small cracks in very high resolution images. I was provided with an already labeled dataset (in YOLO format), and the simplest solution would be to train the object detection model on it as is. But such an approach would require a lot of computing power and a lot of time. The alternative option to reduce the images (say to a size of 416x416) resulted in a serious loss of detail and accuracy (some cracks just disappeared).
Finally, I came up with a simple solution that allowed me to save computing resources and preserve accuracy. I sliced each image (and its corresponding labels) into small tiles (the same 416x416) and trained the model on the resulting tiles. The resulting detection on a high-dimensional image was collected from several detections on tiles from which this image was composed.
To cut the dataset, I wrote a small script, which I want to share with you. In this article I will briefly describe the algorithm of the script. You can get the script itself from the link on github. So let’s get started.
We will need pandas to load and save the dataset, numpy for working with arrays, PIL for working with images, shapely for labels slicing, glob for listing images in a folder, and matplotlib for visualization.
import pandas as pdimport numpy as npfrom PIL import Imagefrom shapely.geometry import Polygon, Pointfrom matplotlib import pyplot as pltimport glob
We assume that we have a dataset in YOLO format, which consists of a folder with images and text files with labels corresponding to these images. For example, if I have an image named im1.JPG, the corresponding labels will be stored in the im1.txt file. The file with labels follows this syntax, for each bounding box the file will contain a line in the format: <object-class> <x_center> <y_center> <width> <height>. We also need a classes.names file for human-readable class names, as well as train.txt and test.txt files to split the dataset into train/test parts. In my case, I have only one class - "crack". We will implement the train/test split further.
The structure of our dataset at this stage should look like this:
yolosample/ classes.names ts/ im2.txt im1.txt im1.JPG im2.JPG
I recommend reading more about the dataset format, as well as YOLOv4 training on your custom dataset in this excellent article.
Let’s visualize labels on one of the images. First, let’s open the image and the corresponding labels.
imname = 'im1'im = Image.open(f'yolosample/ts/{imname}.JPG')df = pd.read_csv(f'yolosample/ts/{imname}.txt', sep=' ', names=['class', 'x1', 'y1', 'w', 'h'])imr = np.array(im, dtype=np.uint8)
Rescale the coordinates from labels according to the dimensions of the image, since they are now normalized from 0 to 1.
df_scaled = df.iloc[:, 1:]df_scaled[['x1', 'w']] = df_scaled[['x1', 'w']] * imr.shape[1]df_scaled[['y1', 'h']] = df_scaled[['y1', 'h']] * imr.shape[0]
We can now display labels on the image.
import matplotlib.patches as patches# Create figure and axesfig,ax = plt.subplots(1, figsize=(10,10))# Display the imageax.imshow(imr)for box in df_scaled.values: # Create a Rectangle patch rect = patches.Rectangle((box[0]-(box[2]/2),box[1]-(box[3]/2)),box[2],box[3],linewidth=2,edgecolor='g',facecolor='none')# Add the patch to the axes ax.add_patch(rect) plt.show()
As we can see, the objects are very small and difficult to distinguish. This is where the slicing comes in handy.
In this script, we slice the image into tiles of slice_sizeXslice_size and save these tiles in the newpath folder. We use shapely to find the bounding boxes that intersect with each specific tile and store the intersection in the labels file for the corresponding tile. We will also save the tiles with no bounding boxes in the falsepath folder.
Now we can see what we got.
imname = 'im1_2_10'im = Image.open(f'sampletiled/ts/{imname}.JPG')imr = np.array(im, dtype=np.uint8)df = pd.read_csv(f'sampletiled/ts/{imname}.txt', sep=' ', names=['class', 'x1', 'y1', 'w', 'h'])# rescale coordinates for visualizationdf_scaled = df.iloc[:, 1:]df_scaled[['x1', 'w']] = df_scaled[['x1', 'w']] * imr.shape[1]df_scaled[['y1', 'h']] = df_scaled[['y1', 'h']] * imr.shape[0]# create figure and axesfig,ax = plt.subplots(1, figsize=(10,10))# display the imageax.imshow(imr)for box in df_scaled.values: # create a Rectangle patch rect = patches.Rectangle((box[0]-(box[2]/2),box[1]-(box[3]/2)),box[2],box[3],linewidth=3,edgecolor='g',facecolor='none')# add the patch to the axes ax.add_patch(rect) plt.show()
Everything looks good and now we just need to split the dataset into train/test parts.
import shutilimport osimport random# get image names and set train/test split ratioratio = 0.8imnames = glob.glob('sampletiled/ts/*.JPG')names = [name.split('/')[2] for name in imnames]# split dataset for train and testtrain = []test = []for name in names: if random.random() > ratio: test.append(f'sampletiled/ts/{name}') else: train.append(f'sampletiled/ts/{name}')print('train:', len(train))print('test:', len(test))
Save train.txt, test.txt and classes.names for a new dataset. In my case I have only one class. You can specify any needed classes.
# save train partwith open('sampletiled/train.txt', 'w') as f: for item in train: f.write("%s\n" % item)# save test partwith open('sampletiled/test.txt', 'w') as f: for item in test: f.write("%s\n" % item)# save classes namesclasses = ['crack']with open('sampletiled/classes.names', 'w') as f: for item in classes: f.write("%s\n" % item)
Congratulations! We have implemented a tiling script and with its help generated a new dataset on which our model can learn to better detect small objects. As I already mentioned, you can find the final script on github by the link. Yo can also find this article packed in Google Colab by this link. If you liked the article and the script was useful for you, then do not forget to clap for this post, I will appreciate it.
Good luck with Computer Vision!
|
[
{
"code": null,
"e": 663,
"s": 171,
"text": "In one of my projects I was faced with the task of detecting very small cracks in very high resolution images. I was provided with an already labeled dataset (in YOLO format), and the simplest solution would be to train the object detection model on it as is. But such an approach would require a lot of computing power and a lot of time. The alternative option to reduce the images (say to a size of 416x416) resulted in a serious loss of detail and accuracy (some cracks just disappeared)."
},
{
"code": null,
"e": 1040,
"s": 663,
"text": "Finally, I came up with a simple solution that allowed me to save computing resources and preserve accuracy. I sliced each image (and its corresponding labels) into small tiles (the same 416x416) and trained the model on the resulting tiles. The resulting detection on a high-dimensional image was collected from several detections on tiles from which this image was composed."
},
{
"code": null,
"e": 1262,
"s": 1040,
"text": "To cut the dataset, I wrote a small script, which I want to share with you. In this article I will briefly describe the algorithm of the script. You can get the script itself from the link on github. So let’s get started."
},
{
"code": null,
"e": 1471,
"s": 1262,
"text": "We will need pandas to load and save the dataset, numpy for working with arrays, PIL for working with images, shapely for labels slicing, glob for listing images in a folder, and matplotlib for visualization."
},
{
"code": null,
"e": 1620,
"s": 1471,
"text": "import pandas as pdimport numpy as npfrom PIL import Imagefrom shapely.geometry import Polygon, Pointfrom matplotlib import pyplot as pltimport glob"
},
{
"code": null,
"e": 2280,
"s": 1620,
"text": "We assume that we have a dataset in YOLO format, which consists of a folder with images and text files with labels corresponding to these images. For example, if I have an image named im1.JPG, the corresponding labels will be stored in the im1.txt file. The file with labels follows this syntax, for each bounding box the file will contain a line in the format: <object-class> <x_center> <y_center> <width> <height>. We also need a classes.names file for human-readable class names, as well as train.txt and test.txt files to split the dataset into train/test parts. In my case, I have only one class - \"crack\". We will implement the train/test split further."
},
{
"code": null,
"e": 2346,
"s": 2280,
"text": "The structure of our dataset at this stage should look like this:"
},
{
"code": null,
"e": 2442,
"s": 2346,
"text": "yolosample/ classes.names ts/ im2.txt im1.txt im1.JPG im2.JPG"
},
{
"code": null,
"e": 2570,
"s": 2442,
"text": "I recommend reading more about the dataset format, as well as YOLOv4 training on your custom dataset in this excellent article."
},
{
"code": null,
"e": 2673,
"s": 2570,
"text": "Let’s visualize labels on one of the images. First, let’s open the image and the corresponding labels."
},
{
"code": null,
"e": 2863,
"s": 2673,
"text": "imname = 'im1'im = Image.open(f'yolosample/ts/{imname}.JPG')df = pd.read_csv(f'yolosample/ts/{imname}.txt', sep=' ', names=['class', 'x1', 'y1', 'w', 'h'])imr = np.array(im, dtype=np.uint8)"
},
{
"code": null,
"e": 2984,
"s": 2863,
"text": "Rescale the coordinates from labels according to the dimensions of the image, since they are now normalized from 0 to 1."
},
{
"code": null,
"e": 3135,
"s": 2984,
"text": "df_scaled = df.iloc[:, 1:]df_scaled[['x1', 'w']] = df_scaled[['x1', 'w']] * imr.shape[1]df_scaled[['y1', 'h']] = df_scaled[['y1', 'h']] * imr.shape[0]"
},
{
"code": null,
"e": 3175,
"s": 3135,
"text": "We can now display labels on the image."
},
{
"code": null,
"e": 3555,
"s": 3175,
"text": "import matplotlib.patches as patches# Create figure and axesfig,ax = plt.subplots(1, figsize=(10,10))# Display the imageax.imshow(imr)for box in df_scaled.values: # Create a Rectangle patch rect = patches.Rectangle((box[0]-(box[2]/2),box[1]-(box[3]/2)),box[2],box[3],linewidth=2,edgecolor='g',facecolor='none')# Add the patch to the axes ax.add_patch(rect) plt.show()"
},
{
"code": null,
"e": 3669,
"s": 3555,
"text": "As we can see, the objects are very small and difficult to distinguish. This is where the slicing comes in handy."
},
{
"code": null,
"e": 4015,
"s": 3669,
"text": "In this script, we slice the image into tiles of slice_sizeXslice_size and save these tiles in the newpath folder. We use shapely to find the bounding boxes that intersect with each specific tile and store the intersection in the labels file for the corresponding tile. We will also save the tiles with no bounding boxes in the falsepath folder."
},
{
"code": null,
"e": 4043,
"s": 4015,
"text": "Now we can see what we got."
},
{
"code": null,
"e": 4772,
"s": 4043,
"text": "imname = 'im1_2_10'im = Image.open(f'sampletiled/ts/{imname}.JPG')imr = np.array(im, dtype=np.uint8)df = pd.read_csv(f'sampletiled/ts/{imname}.txt', sep=' ', names=['class', 'x1', 'y1', 'w', 'h'])# rescale coordinates for visualizationdf_scaled = df.iloc[:, 1:]df_scaled[['x1', 'w']] = df_scaled[['x1', 'w']] * imr.shape[1]df_scaled[['y1', 'h']] = df_scaled[['y1', 'h']] * imr.shape[0]# create figure and axesfig,ax = plt.subplots(1, figsize=(10,10))# display the imageax.imshow(imr)for box in df_scaled.values: # create a Rectangle patch rect = patches.Rectangle((box[0]-(box[2]/2),box[1]-(box[3]/2)),box[2],box[3],linewidth=3,edgecolor='g',facecolor='none')# add the patch to the axes ax.add_patch(rect) plt.show()"
},
{
"code": null,
"e": 4859,
"s": 4772,
"text": "Everything looks good and now we just need to split the dataset into train/test parts."
},
{
"code": null,
"e": 5299,
"s": 4859,
"text": "import shutilimport osimport random# get image names and set train/test split ratioratio = 0.8imnames = glob.glob('sampletiled/ts/*.JPG')names = [name.split('/')[2] for name in imnames]# split dataset for train and testtrain = []test = []for name in names: if random.random() > ratio: test.append(f'sampletiled/ts/{name}') else: train.append(f'sampletiled/ts/{name}')print('train:', len(train))print('test:', len(test))"
},
{
"code": null,
"e": 5431,
"s": 5299,
"text": "Save train.txt, test.txt and classes.names for a new dataset. In my case I have only one class. You can specify any needed classes."
},
{
"code": null,
"e": 5799,
"s": 5431,
"text": "# save train partwith open('sampletiled/train.txt', 'w') as f: for item in train: f.write(\"%s\\n\" % item)# save test partwith open('sampletiled/test.txt', 'w') as f: for item in test: f.write(\"%s\\n\" % item)# save classes namesclasses = ['crack']with open('sampletiled/classes.names', 'w') as f: for item in classes: f.write(\"%s\\n\" % item)"
},
{
"code": null,
"e": 6223,
"s": 5799,
"text": "Congratulations! We have implemented a tiling script and with its help generated a new dataset on which our model can learn to better detect small objects. As I already mentioned, you can find the final script on github by the link. Yo can also find this article packed in Google Colab by this link. If you liked the article and the script was useful for you, then do not forget to clap for this post, I will appreciate it."
}
] |
Design a running car animation using HTML and CSS - GeeksforGeeks
|
28 Dec, 2020
Project Introduction: In this project, we are going to implement a car running on a track using HTML and CSS with sound effects. The prerequisites of this project are HTML, CSS, and JavaScript.
File structure:
index.html
style.css
script.js
HTML code: In the following code, we have placed the sky div in such a way that it covers the whole webpage. After that, the tree, track, car are put over the sky and finally, the wheels are fitted in the car so that they can rotate, and we can create an animation for a running car. We have added the styles using the file style.css and applied the sound effects from script.js.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Lamborghini car animation</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script></head><body> <div class="sky"> <div class="tree"></div> <div class="track"></div> <div class="car"></div> <div class=" wheel wheel1"></div> <div class="wheel wheel2"></div> </div></body></html>
style.css: The following is the code for file “style.css” which is used in the above HTML code.
/* CSS Reset */
*{
margin: 0;
padding: 0;
}
/* Sky Styling */
.sky {
width: 100vw;
height: 100vh;
background-image: url(sky.jpeg);
background-repeat: no-repeat;
background-size: cover;
position: absolute;
}
/* Tree Styling and positioning */
.tree {
height: 100vh;
background-image: url(tree-removebg-preview\ \(1\).png);
background-repeat:no-repeat;
background-size: cover;
}
/* Track Styling and positioning */
.track {
background-image: url(track.jpeg);
background-repeat: repeat-x;
position: absolute;
bottom: 0px;
width: 1000vw;
height: 20vh;
animation: trackanimation 6s linear infinite;
}
/* Car Styling and positioning */
.car {
background-image: url(car-removebg-preview.png);
background-repeat: no-repeat;
background-size: cover;
width: 17rem;
height: 4.699rem;
position: absolute;
bottom: 77px;
left: 396px;
}
/* Wheel's Styling and positioning */
.wheel {
position: absolute;
animation: wheelanimation linear .6s infinite;
}
.wheel1 {
background-image: url(wheel1-removebg-preview.png);
background-size: contain;
background-repeat: no-repeat;
width: 46px;
height: 49px;
bottom: 71px;
left: 570px;
}
.wheel2 {
background-image: url(wheel2-removebg-preview.png);
background-size: cover;
background-repeat: no-repeat;
width: 43px;
height: 44px;
bottom: 77px;
left: 433px;
}
/* Rotation of the wheels */
@keyframes wheelanimation{
100% {
transform: rotate(360deg);
}
}
/* Moving the track backwards */
@keyframes trackanimation {
100% {
transform: translate(-500vw);
}
}
Explanation:
sky: We have placed the sky such that it covers the full viewport by assigning it 100vw and 100vh and we have set the position to absolute.
tree: We have positioned the tree such that it occupies the bottom of the webpage by using position: absolute property.
track: We have positioned the track to the bottom of the webpage, and we have repeated the track in the x-direction such that it always remains visible in the animation. We have also assigned a very large width to the track too for the same purpose. Now, the animation applied to the track moves the track in the backward direction such that it appears that the car is moving.
car, wheel: We have positioned the car and its wheels to their desired positions first and then made the wheels rotate by applying proper animation to it as given in the code above.
script.js: The following is the code for script.js file used in the above HTML file. This file is basically for applying the desired sound effects.
var aud=document.createElement('audio');
aud.setAttribute('src','sound.mp4');
aud.loop=true;
aud.play();
Output:
Source code link: https://github.com/SAEb-ai/Racing-Car-Animation
Output link: https://drive.google.com/file/d/18rT4MxajPJXjlscsjbMaVxVkihGavGQh/view?usp=drivesdk
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 24678,
"s": 24650,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24872,
"s": 24678,
"text": "Project Introduction: In this project, we are going to implement a car running on a track using HTML and CSS with sound effects. The prerequisites of this project are HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 24888,
"s": 24872,
"text": "File structure:"
},
{
"code": null,
"e": 24899,
"s": 24888,
"text": "index.html"
},
{
"code": null,
"e": 24909,
"s": 24899,
"text": "style.css"
},
{
"code": null,
"e": 24919,
"s": 24909,
"text": "script.js"
},
{
"code": null,
"e": 25300,
"s": 24919,
"text": "HTML code: In the following code, we have placed the sky div in such a way that it covers the whole webpage. After that, the tree, track, car are put over the sky and finally, the wheels are fitted in the car so that they can rotate, and we can create an animation for a running car. We have added the styles using the file style.css and applied the sound effects from script.js."
},
{
"code": null,
"e": 25305,
"s": 25300,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Lamborghini car animation</title> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"script.js\"></script></head><body> <div class=\"sky\"> <div class=\"tree\"></div> <div class=\"track\"></div> <div class=\"car\"></div> <div class=\" wheel wheel1\"></div> <div class=\"wheel wheel2\"></div> </div></body></html>",
"e": 25809,
"s": 25305,
"text": null
},
{
"code": null,
"e": 25905,
"s": 25809,
"text": "style.css: The following is the code for file “style.css” which is used in the above HTML code."
},
{
"code": null,
"e": 27595,
"s": 25905,
"text": "/* CSS Reset */\n*{\n margin: 0;\n padding: 0;\n}\n\n/* Sky Styling */\n.sky {\n width: 100vw;\n height: 100vh;\n background-image: url(sky.jpeg);\n background-repeat: no-repeat;\n background-size: cover;\n position: absolute;\n}\n\n/* Tree Styling and positioning */\n.tree {\n height: 100vh;\n background-image: url(tree-removebg-preview\\ \\(1\\).png);\n background-repeat:no-repeat;\n background-size: cover;\n}\n\n/* Track Styling and positioning */\n.track {\n background-image: url(track.jpeg);\n background-repeat: repeat-x;\n position: absolute;\n bottom: 0px;\n width: 1000vw;\n height: 20vh;\n animation: trackanimation 6s linear infinite;\n}\n\n/* Car Styling and positioning */\n.car {\n background-image: url(car-removebg-preview.png);\n background-repeat: no-repeat;\n background-size: cover;\n width: 17rem;\n height: 4.699rem;\n position: absolute;\n bottom: 77px;\n left: 396px;\n}\n\n/* Wheel's Styling and positioning */\n.wheel {\n position: absolute;\n animation: wheelanimation linear .6s infinite;\n}\n.wheel1 {\n background-image: url(wheel1-removebg-preview.png);\n background-size: contain;\n background-repeat: no-repeat;\n width: 46px;\n height: 49px;\n bottom: 71px;\n left: 570px;\n}\n.wheel2 {\n background-image: url(wheel2-removebg-preview.png);\n background-size: cover;\n background-repeat: no-repeat;\n width: 43px;\n height: 44px;\n bottom: 77px;\n left: 433px;\n}\n\n/* Rotation of the wheels */\n@keyframes wheelanimation{\n 100% {\n transform: rotate(360deg);\n }\n}\n\n/* Moving the track backwards */\n@keyframes trackanimation {\n 100% {\n transform: translate(-500vw);\n }\n}"
},
{
"code": null,
"e": 27608,
"s": 27595,
"text": "Explanation:"
},
{
"code": null,
"e": 27748,
"s": 27608,
"text": "sky: We have placed the sky such that it covers the full viewport by assigning it 100vw and 100vh and we have set the position to absolute."
},
{
"code": null,
"e": 27868,
"s": 27748,
"text": "tree: We have positioned the tree such that it occupies the bottom of the webpage by using position: absolute property."
},
{
"code": null,
"e": 28245,
"s": 27868,
"text": "track: We have positioned the track to the bottom of the webpage, and we have repeated the track in the x-direction such that it always remains visible in the animation. We have also assigned a very large width to the track too for the same purpose. Now, the animation applied to the track moves the track in the backward direction such that it appears that the car is moving."
},
{
"code": null,
"e": 28427,
"s": 28245,
"text": "car, wheel: We have positioned the car and its wheels to their desired positions first and then made the wheels rotate by applying proper animation to it as given in the code above."
},
{
"code": null,
"e": 28575,
"s": 28427,
"text": "script.js: The following is the code for script.js file used in the above HTML file. This file is basically for applying the desired sound effects."
},
{
"code": null,
"e": 28680,
"s": 28575,
"text": "var aud=document.createElement('audio');\naud.setAttribute('src','sound.mp4');\naud.loop=true;\naud.play();"
},
{
"code": null,
"e": 28688,
"s": 28680,
"text": "Output:"
},
{
"code": null,
"e": 28754,
"s": 28688,
"text": "Source code link: https://github.com/SAEb-ai/Racing-Car-Animation"
},
{
"code": null,
"e": 28851,
"s": 28754,
"text": "Output link: https://drive.google.com/file/d/18rT4MxajPJXjlscsjbMaVxVkihGavGQh/view?usp=drivesdk"
},
{
"code": null,
"e": 28988,
"s": 28851,
"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": 28997,
"s": 28988,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29007,
"s": 28997,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29031,
"s": 29007,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29035,
"s": 29031,
"text": "CSS"
},
{
"code": null,
"e": 29040,
"s": 29035,
"text": "HTML"
},
{
"code": null,
"e": 29059,
"s": 29040,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29076,
"s": 29059,
"text": "Web Technologies"
},
{
"code": null,
"e": 29081,
"s": 29076,
"text": "HTML"
},
{
"code": null,
"e": 29179,
"s": 29081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29237,
"s": 29179,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29274,
"s": 29237,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29338,
"s": 29274,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29379,
"s": 29338,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29416,
"s": 29379,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29476,
"s": 29416,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29537,
"s": 29476,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29590,
"s": 29537,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29640,
"s": 29590,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Conquer Class Imbalanced Dataset Issues using GANs | by Swanand Mhalagi | Towards Data Science
|
A common problem in real life deep learning applications is that some classes have a significantly higher number of examples in the training set than other classes. Let’s consider a manufacturer is building a visual inspection system to detect damaged products. No manufacturer will have as many damaged product images as good product images. This difference is referred to as class imbalance. Class imbalanced datasets are common across different domains such as health, banking, security and others. With such datasets, the learning algorithms are often biased towards the majority classes and therefore there is a higher miss-classification rate for the minority class instances.
There are different strategies such as oversampling, under sampling, two phase training and cost sensitive learning to address this problem. Methods that generate artificial data for the minority class constitute a more general approach compared to algorithmic improvements. This article is all about reducing this gap in datasets using Deep Convolution Generative Adversarial Networks (DC-GAN) to improve classification performance.
GANs are like Rubik's cube. Once you know the trick to solve the cube, there are multiple ways to get to the perfect cube. It can be as fast as 3.47 sec (current world record for 3x3 Rubik’s cube) and it's easy to discover if you have messed up. But if you don’t know the trick to solve the cube it can take forever. The time & cost to failure for GAN is pretty high (considering training time and dollar value of resources), especially when you have limited resources and you might still wonder what went wrong. Once you know GAN dependencies, it will be relatively easy to get to a perfect solution.
Throughout this article we will tackle the following topics -
Tips and tricks to make GANs work/stable.How to define GAN. How to shape GAN for real world datasets of Kaggle competitions ?Exciting use cases of GANs.
Tips and tricks to make GANs work/stable.
How to define GAN. How to shape GAN for real world datasets of Kaggle competitions ?
Exciting use cases of GANs.
Tips and tricks to make GANs work/stable -
Developing a GAN for generating images requires a discriminator convolutional neural network model for classifying whether a given image is real or generated and a generator model that uses inverse convolutional layers to transform an input to a full two-dimensional image of pixel values.
These generator and discriminator models compete in a zero-sum game. It means that improvements to one model come at the cost of degrading of performance in the other model. The result is a very unstable training process that can often lead to failure.
While research in GANs continues to improve fundamental stability of these models, there are bunch of tricks to train them and make them stable.
Use Strided Convolution >> Do not use max pooling layers and instead use the stride in convolutional layer to perform down sampling in the discriminator model. Use Conv2DTranspose and stride for up sampling.Remove Fully-Connected Layers >> Fully-Connected layers are not used in discriminator, instead convolutional layers are flattened and passed directly to the output layer.Use Batch Normalization >> Batch norm layers are recommended in both the discriminator and generator models, except the output of the generator and input to the discriminator.Use of ReLU, Leaky ReLU and Tanh >> ReLU is recommended only for generators but for discriminator variation of ReLU that allows values less than zero, called Leaky ReLU is preferred. Additionally, the generator uses Tanh and discriminator uses Sigmoid activation function in the output layer.Normalize the input >> Normalize the input images between -1 to 1. Construct different mini-batches for real and fake, i.e. each mini-batch needs to contain only all real images or all generated images.Learning rates >> Use different learning rates for discriminator (1e-3) and generator (1e-4). Use Adam optimizer for both.Performance hack >> Train discriminator twice and generator once. Use 50% dropout in generator.Track failures early >> A loss of 0.0 in the discriminator is a failure mode. If the loss of the generator steadily decreases, it is likely fooling the discriminator with garbage images. When training is working smooth, discriminator loss has low variance and goes down overtime.
Use Strided Convolution >> Do not use max pooling layers and instead use the stride in convolutional layer to perform down sampling in the discriminator model. Use Conv2DTranspose and stride for up sampling.
Remove Fully-Connected Layers >> Fully-Connected layers are not used in discriminator, instead convolutional layers are flattened and passed directly to the output layer.
Use Batch Normalization >> Batch norm layers are recommended in both the discriminator and generator models, except the output of the generator and input to the discriminator.
Use of ReLU, Leaky ReLU and Tanh >> ReLU is recommended only for generators but for discriminator variation of ReLU that allows values less than zero, called Leaky ReLU is preferred. Additionally, the generator uses Tanh and discriminator uses Sigmoid activation function in the output layer.
Normalize the input >> Normalize the input images between -1 to 1. Construct different mini-batches for real and fake, i.e. each mini-batch needs to contain only all real images or all generated images.
Learning rates >> Use different learning rates for discriminator (1e-3) and generator (1e-4). Use Adam optimizer for both.
Performance hack >> Train discriminator twice and generator once. Use 50% dropout in generator.
Track failures early >> A loss of 0.0 in the discriminator is a failure mode. If the loss of the generator steadily decreases, it is likely fooling the discriminator with garbage images. When training is working smooth, discriminator loss has low variance and goes down overtime.
All such tricks we need to put together to create a perfect GAN.
How to define GAN? How to shape GAN for real world datasets of Kaggle competitions? -
Researchers have developed multiple flavor GANs and there are multiple solutions out there on web to address class imbalance issue but all of these are mainly on toy datasets such as MNIST, CIFAR-10 and ImageNet. I have been working on a medical image classification (Diabetic Retinopathy Detection) dataset from Kaggle competitions. This dataset has 4 classes where class 1 has 13k samples whereas class 4 has only 600. One of the recent methodology used by Kaggle competition winners to address class imbalance issue is nothing but use of DC-GAN. We will use DC-GAN to create artificial samples for class 4 of Diabetic Retinopathy Detection database.
Let's begin the coding exercise and implement these tricks to generate new images. All the experiments are done on NVIDIA Quadro M400 GPU. This GPU has a 8 GB RAM. GPU is configured with CUDA 9.0, cuDNN 7.4, TF for GPU 1.8.0 on Ubuntu 16.04 instance.
Import all the necessary environments. This code expects all the packages are installed beforehand.
I have already downloaded the database from Kaggle. The images in this database are hard to distinguish by naked eyes hence this dataset is very different from all toy datasets. The database has several zip files, we need to unzip them into train/test folders containing respective images. All the labels for train images are provided in a separate csv file.
In the code below we will read a csv file containing labels and name of the images. We need to do some sanity checks (adding .jpeg extension, delete all the images of size 0 KB, remove entries of deleted images from the data frame) before we move forward.
In this dataset class 3 and 4 are minority classes since they have very low representation in entire dataset. We will train GAN to generate images for class 4.
Below section defines discriminator and generator. The discriminator uses convolution layer with 2 x 2 strides to down sample the input image (Trick #1 & 2). The output layer use Sigmoid activation function to predict whether the input sample is real or fake. The model is trained to minimize binary cross entropy loss function with the use of Adam optimizer (Trick #4).
The generator is defined with Conv2DTranspose with 2 x 2 strides to up-sample the images up-to 128 pixels. The output layer uses Tanh activation function to ensure output values are in desired range of [-1, 1] (Trick #4). We have intentionally used different learning rates for discriminator and generator (Trick #6).
The define_gan() function uses already defined generator and discriminator models and create a new logical model.
The function load_real_samples() below will read actual data from the dataset and normalize the images (Trick #5) before feeding them to generate_real_samples() while invoking train().
The generate_fake_samples() function generates images with random pixel values and a fake label 0.
There are no metrics to evaluate GAN performance, the images generated must be evaluated for quality by human operator. This makes hard to decide where to stop the training.
Due to adversarial nature, the generator properties are changing after every epoch. Once an acceptable quality of image is generated, the generator may not improve the performance, in many cases even degrade with subsequent epochs.
This problem is handled using 3 options
Periodically evaluate the classification accuracy of discriminator on real and fake images.Periodically generate images and save them for human operator review.Periodically save the generator model for later use.
Periodically evaluate the classification accuracy of discriminator on real and fake images.
Periodically generate images and save them for human operator review.
Periodically save the generator model for later use.
All this action will be performed by summarize_performance() function to evaluate discriminator model. Training GAN for multiple epochs will generate snapshots of model every 10th epoch simultaneously save_plat() will keep saving images. This will be helpful to back track the progress of GAN image generation.
The train() function is defined below, the number of batches within each epoch is defined by how many times the batch size divides into the training dataset.
Train discriminator model is updated twice (with fake and real samples each time) and generator once for each batch iteration (Trick #7).
It is critical to observe the loss while training the GAN, sudden drop in discriminator loss indicates that the generator model has started generating bad samples that discriminator can easily discriminate (Trick #8).
In order to visualize the models we can plot the them using plot_model() function.
The summary() function can also be used to see the model layout and number of trainable parameters. Call the train() function to begin the discriminator and generator training.
Discriminator model
_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_1 (Conv2D) (None, 128, 128, 16) 448 _________________________________________________________________leaky_re_lu_1 (LeakyReLU) (None, 128, 128, 16) 0 _________________________________________________________________conv2d_2 (Conv2D) (None, 64, 64, 8) 1160 _________________________________________________________________leaky_re_lu_2 (LeakyReLU) (None, 64, 64, 8) 0 _________________________________________________________________conv2d_3 (Conv2D) (None, 32, 32, 16) 1168 _________________________________________________________________leaky_re_lu_3 (LeakyReLU) (None, 32, 32, 16) 0 _________________________________________________________________conv2d_4 (Conv2D) (None, 16, 16, 8) 1160 _________________________________________________________________leaky_re_lu_4 (LeakyReLU) (None, 16, 16, 8) 0 _________________________________________________________________flatten_1 (Flatten) (None, 2048) 0 _________________________________________________________________dropout_1 (Dropout) (None, 2048) 0 _________________________________________________________________dense_1 (Dense) (None, 1) 2049 =================================================================Total params: 11,970Trainable params: 5,985Non-trainable params: 5,985_________________________________________________________________
Generator model
_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense_2 (Dense) (None, 65536) 6619136 _________________________________________________________________leaky_re_lu_5 (LeakyReLU) (None, 65536) 0 _________________________________________________________________reshape_1 (Reshape) (None, 16, 16, 256) 0 _________________________________________________________________conv2d_transpose_1 (Conv2DTr (None, 32, 32, 128) 524416 _________________________________________________________________leaky_re_lu_6 (LeakyReLU) (None, 32, 32, 128) 0 _________________________________________________________________conv2d_transpose_2 (Conv2DTr (None, 64, 64, 128) 262272 _________________________________________________________________leaky_re_lu_7 (LeakyReLU) (None, 64, 64, 128) 0 _________________________________________________________________conv2d_transpose_3 (Conv2DTr (None, 128, 128, 128) 262272 _________________________________________________________________leaky_re_lu_8 (LeakyReLU) (None, 128, 128, 128) 0 _________________________________________________________________conv2d_5 (Conv2D) (None, 128, 128, 3) 3459 =================================================================Total params: 7,671,555Trainable params: 7,671,555Non-trainable params: 0_________________________________________________________________
The training processes will look like below snippet
.....>319, 5/10, d1=0.692, d2=0.761 g=0.709>319, 6/10, d1=0.822, d2=0.759 g=0.690>319, 7/10, d1=0.733, d2=0.764 g=0.723>319, 8/10, d1=0.662, d2=0.740 g=0.743>319, 9/10, d1=0.701, d2=0.683 g=0.758>319, 10/10, d1=0.830, d2=0.744 g=0.728>320, 1/10, d1=0.749, d2=0.717 g=0.731>320, 2/10, d1=0.677, d2=0.796 g=0.722>320, 3/10, d1=0.766, d2=0.700 g=0.717>320, 4/10, d1=0.676, d2=0.736 g=0.765>320, 5/10, d1=0.792, d2=0.762 g=0.730>320, 6/10, d1=0.690, d2=0.710 g=0.719>320, 7/10, d1=0.807, d2=0.759 g=0.708>320, 8/10, d1=0.715, d2=0.747 g=0.711>320, 9/10, d1=0.719, d2=0.720 g=0.731>320, 10/10, d1=0.695, d2=0.717 g=0.694################# Summarize ###################>Accuracy real: 35%, fake: 57%
After 320 epochs, below is the quality of images I was able to produce. Training for this GAN took ~ 30 minutes. More complex generator and discriminator model could have produced better quality images.
Progression of the GAN towards a perfect cube
Now these newly generated minority class images can be added to the original imbalanced dataset. This will help convert imbalanced multi class data into a balanced dataset. This will improve the classification performance of the model.
An image classification algorithm for this imbalanced dataset can be found here
towardsdatascience.com
All the iPython notebooks are available at https://github.com/swanandM/DC-GAN-RetinopathyImages
Image classification notebooks https://github.com/swanandM/Diabetic-Retinopathy-Detection-with-TF
Exciting use cases of GANs
GAN has made impressive progress in its first few years. In 2017, GAN was able to create a 1024 x 1024 size images which were able to fool almost everyone. Although this kind of technology can create serious social trustworthiness issue considering the amount of fake news getting publish these days. Engineers have to be careful before developing any such application that will generate social unrest.
Creating animation for games as well as for movies takes tremendous efforts. GAN can auto-generate these animation characters without any professional skills. Besides this, a professional animation creator can take inspiration from these designs.
CycleGAN can transform images from one domain to another domain.
PixelDTGAN is used to generate marketing images based on celebrity pictures. This is also used as a suggestion tool based on images.
Text to image is one of the application of domain transfer GAN. This has tremendous applications including photo editing and computer aided design.
Creating emoji from pictures is one of the well-known application already been used in platforms such as Snap chat and Instagram.
References
Effective data generation for imbalanced learning using conditional generative adversarial networksHow to Develop a GAN to Generate CIFAR10 Small Color PhotographsSome cool applications of GANHow to train a GAN?
Effective data generation for imbalanced learning using conditional generative adversarial networks
How to Develop a GAN to Generate CIFAR10 Small Color Photographs
Some cool applications of GAN
How to train a GAN?
|
[
{
"code": null,
"e": 854,
"s": 171,
"text": "A common problem in real life deep learning applications is that some classes have a significantly higher number of examples in the training set than other classes. Let’s consider a manufacturer is building a visual inspection system to detect damaged products. No manufacturer will have as many damaged product images as good product images. This difference is referred to as class imbalance. Class imbalanced datasets are common across different domains such as health, banking, security and others. With such datasets, the learning algorithms are often biased towards the majority classes and therefore there is a higher miss-classification rate for the minority class instances."
},
{
"code": null,
"e": 1288,
"s": 854,
"text": "There are different strategies such as oversampling, under sampling, two phase training and cost sensitive learning to address this problem. Methods that generate artificial data for the minority class constitute a more general approach compared to algorithmic improvements. This article is all about reducing this gap in datasets using Deep Convolution Generative Adversarial Networks (DC-GAN) to improve classification performance."
},
{
"code": null,
"e": 1890,
"s": 1288,
"text": "GANs are like Rubik's cube. Once you know the trick to solve the cube, there are multiple ways to get to the perfect cube. It can be as fast as 3.47 sec (current world record for 3x3 Rubik’s cube) and it's easy to discover if you have messed up. But if you don’t know the trick to solve the cube it can take forever. The time & cost to failure for GAN is pretty high (considering training time and dollar value of resources), especially when you have limited resources and you might still wonder what went wrong. Once you know GAN dependencies, it will be relatively easy to get to a perfect solution."
},
{
"code": null,
"e": 1952,
"s": 1890,
"text": "Throughout this article we will tackle the following topics -"
},
{
"code": null,
"e": 2105,
"s": 1952,
"text": "Tips and tricks to make GANs work/stable.How to define GAN. How to shape GAN for real world datasets of Kaggle competitions ?Exciting use cases of GANs."
},
{
"code": null,
"e": 2147,
"s": 2105,
"text": "Tips and tricks to make GANs work/stable."
},
{
"code": null,
"e": 2232,
"s": 2147,
"text": "How to define GAN. How to shape GAN for real world datasets of Kaggle competitions ?"
},
{
"code": null,
"e": 2260,
"s": 2232,
"text": "Exciting use cases of GANs."
},
{
"code": null,
"e": 2303,
"s": 2260,
"text": "Tips and tricks to make GANs work/stable -"
},
{
"code": null,
"e": 2593,
"s": 2303,
"text": "Developing a GAN for generating images requires a discriminator convolutional neural network model for classifying whether a given image is real or generated and a generator model that uses inverse convolutional layers to transform an input to a full two-dimensional image of pixel values."
},
{
"code": null,
"e": 2846,
"s": 2593,
"text": "These generator and discriminator models compete in a zero-sum game. It means that improvements to one model come at the cost of degrading of performance in the other model. The result is a very unstable training process that can often lead to failure."
},
{
"code": null,
"e": 2991,
"s": 2846,
"text": "While research in GANs continues to improve fundamental stability of these models, there are bunch of tricks to train them and make them stable."
},
{
"code": null,
"e": 4534,
"s": 2991,
"text": "Use Strided Convolution >> Do not use max pooling layers and instead use the stride in convolutional layer to perform down sampling in the discriminator model. Use Conv2DTranspose and stride for up sampling.Remove Fully-Connected Layers >> Fully-Connected layers are not used in discriminator, instead convolutional layers are flattened and passed directly to the output layer.Use Batch Normalization >> Batch norm layers are recommended in both the discriminator and generator models, except the output of the generator and input to the discriminator.Use of ReLU, Leaky ReLU and Tanh >> ReLU is recommended only for generators but for discriminator variation of ReLU that allows values less than zero, called Leaky ReLU is preferred. Additionally, the generator uses Tanh and discriminator uses Sigmoid activation function in the output layer.Normalize the input >> Normalize the input images between -1 to 1. Construct different mini-batches for real and fake, i.e. each mini-batch needs to contain only all real images or all generated images.Learning rates >> Use different learning rates for discriminator (1e-3) and generator (1e-4). Use Adam optimizer for both.Performance hack >> Train discriminator twice and generator once. Use 50% dropout in generator.Track failures early >> A loss of 0.0 in the discriminator is a failure mode. If the loss of the generator steadily decreases, it is likely fooling the discriminator with garbage images. When training is working smooth, discriminator loss has low variance and goes down overtime."
},
{
"code": null,
"e": 4742,
"s": 4534,
"text": "Use Strided Convolution >> Do not use max pooling layers and instead use the stride in convolutional layer to perform down sampling in the discriminator model. Use Conv2DTranspose and stride for up sampling."
},
{
"code": null,
"e": 4913,
"s": 4742,
"text": "Remove Fully-Connected Layers >> Fully-Connected layers are not used in discriminator, instead convolutional layers are flattened and passed directly to the output layer."
},
{
"code": null,
"e": 5089,
"s": 4913,
"text": "Use Batch Normalization >> Batch norm layers are recommended in both the discriminator and generator models, except the output of the generator and input to the discriminator."
},
{
"code": null,
"e": 5382,
"s": 5089,
"text": "Use of ReLU, Leaky ReLU and Tanh >> ReLU is recommended only for generators but for discriminator variation of ReLU that allows values less than zero, called Leaky ReLU is preferred. Additionally, the generator uses Tanh and discriminator uses Sigmoid activation function in the output layer."
},
{
"code": null,
"e": 5585,
"s": 5382,
"text": "Normalize the input >> Normalize the input images between -1 to 1. Construct different mini-batches for real and fake, i.e. each mini-batch needs to contain only all real images or all generated images."
},
{
"code": null,
"e": 5708,
"s": 5585,
"text": "Learning rates >> Use different learning rates for discriminator (1e-3) and generator (1e-4). Use Adam optimizer for both."
},
{
"code": null,
"e": 5804,
"s": 5708,
"text": "Performance hack >> Train discriminator twice and generator once. Use 50% dropout in generator."
},
{
"code": null,
"e": 6084,
"s": 5804,
"text": "Track failures early >> A loss of 0.0 in the discriminator is a failure mode. If the loss of the generator steadily decreases, it is likely fooling the discriminator with garbage images. When training is working smooth, discriminator loss has low variance and goes down overtime."
},
{
"code": null,
"e": 6149,
"s": 6084,
"text": "All such tricks we need to put together to create a perfect GAN."
},
{
"code": null,
"e": 6235,
"s": 6149,
"text": "How to define GAN? How to shape GAN for real world datasets of Kaggle competitions? -"
},
{
"code": null,
"e": 6888,
"s": 6235,
"text": "Researchers have developed multiple flavor GANs and there are multiple solutions out there on web to address class imbalance issue but all of these are mainly on toy datasets such as MNIST, CIFAR-10 and ImageNet. I have been working on a medical image classification (Diabetic Retinopathy Detection) dataset from Kaggle competitions. This dataset has 4 classes where class 1 has 13k samples whereas class 4 has only 600. One of the recent methodology used by Kaggle competition winners to address class imbalance issue is nothing but use of DC-GAN. We will use DC-GAN to create artificial samples for class 4 of Diabetic Retinopathy Detection database."
},
{
"code": null,
"e": 7139,
"s": 6888,
"text": "Let's begin the coding exercise and implement these tricks to generate new images. All the experiments are done on NVIDIA Quadro M400 GPU. This GPU has a 8 GB RAM. GPU is configured with CUDA 9.0, cuDNN 7.4, TF for GPU 1.8.0 on Ubuntu 16.04 instance."
},
{
"code": null,
"e": 7239,
"s": 7139,
"text": "Import all the necessary environments. This code expects all the packages are installed beforehand."
},
{
"code": null,
"e": 7598,
"s": 7239,
"text": "I have already downloaded the database from Kaggle. The images in this database are hard to distinguish by naked eyes hence this dataset is very different from all toy datasets. The database has several zip files, we need to unzip them into train/test folders containing respective images. All the labels for train images are provided in a separate csv file."
},
{
"code": null,
"e": 7854,
"s": 7598,
"text": "In the code below we will read a csv file containing labels and name of the images. We need to do some sanity checks (adding .jpeg extension, delete all the images of size 0 KB, remove entries of deleted images from the data frame) before we move forward."
},
{
"code": null,
"e": 8014,
"s": 7854,
"text": "In this dataset class 3 and 4 are minority classes since they have very low representation in entire dataset. We will train GAN to generate images for class 4."
},
{
"code": null,
"e": 8385,
"s": 8014,
"text": "Below section defines discriminator and generator. The discriminator uses convolution layer with 2 x 2 strides to down sample the input image (Trick #1 & 2). The output layer use Sigmoid activation function to predict whether the input sample is real or fake. The model is trained to minimize binary cross entropy loss function with the use of Adam optimizer (Trick #4)."
},
{
"code": null,
"e": 8703,
"s": 8385,
"text": "The generator is defined with Conv2DTranspose with 2 x 2 strides to up-sample the images up-to 128 pixels. The output layer uses Tanh activation function to ensure output values are in desired range of [-1, 1] (Trick #4). We have intentionally used different learning rates for discriminator and generator (Trick #6)."
},
{
"code": null,
"e": 8817,
"s": 8703,
"text": "The define_gan() function uses already defined generator and discriminator models and create a new logical model."
},
{
"code": null,
"e": 9002,
"s": 8817,
"text": "The function load_real_samples() below will read actual data from the dataset and normalize the images (Trick #5) before feeding them to generate_real_samples() while invoking train()."
},
{
"code": null,
"e": 9101,
"s": 9002,
"text": "The generate_fake_samples() function generates images with random pixel values and a fake label 0."
},
{
"code": null,
"e": 9275,
"s": 9101,
"text": "There are no metrics to evaluate GAN performance, the images generated must be evaluated for quality by human operator. This makes hard to decide where to stop the training."
},
{
"code": null,
"e": 9507,
"s": 9275,
"text": "Due to adversarial nature, the generator properties are changing after every epoch. Once an acceptable quality of image is generated, the generator may not improve the performance, in many cases even degrade with subsequent epochs."
},
{
"code": null,
"e": 9547,
"s": 9507,
"text": "This problem is handled using 3 options"
},
{
"code": null,
"e": 9760,
"s": 9547,
"text": "Periodically evaluate the classification accuracy of discriminator on real and fake images.Periodically generate images and save them for human operator review.Periodically save the generator model for later use."
},
{
"code": null,
"e": 9852,
"s": 9760,
"text": "Periodically evaluate the classification accuracy of discriminator on real and fake images."
},
{
"code": null,
"e": 9922,
"s": 9852,
"text": "Periodically generate images and save them for human operator review."
},
{
"code": null,
"e": 9975,
"s": 9922,
"text": "Periodically save the generator model for later use."
},
{
"code": null,
"e": 10286,
"s": 9975,
"text": "All this action will be performed by summarize_performance() function to evaluate discriminator model. Training GAN for multiple epochs will generate snapshots of model every 10th epoch simultaneously save_plat() will keep saving images. This will be helpful to back track the progress of GAN image generation."
},
{
"code": null,
"e": 10444,
"s": 10286,
"text": "The train() function is defined below, the number of batches within each epoch is defined by how many times the batch size divides into the training dataset."
},
{
"code": null,
"e": 10582,
"s": 10444,
"text": "Train discriminator model is updated twice (with fake and real samples each time) and generator once for each batch iteration (Trick #7)."
},
{
"code": null,
"e": 10800,
"s": 10582,
"text": "It is critical to observe the loss while training the GAN, sudden drop in discriminator loss indicates that the generator model has started generating bad samples that discriminator can easily discriminate (Trick #8)."
},
{
"code": null,
"e": 10883,
"s": 10800,
"text": "In order to visualize the models we can plot the them using plot_model() function."
},
{
"code": null,
"e": 11060,
"s": 10883,
"text": "The summary() function can also be used to see the model layout and number of trainable parameters. Call the train() function to begin the discriminator and generator training."
},
{
"code": null,
"e": 11080,
"s": 11060,
"text": "Discriminator model"
},
{
"code": null,
"e": 12841,
"s": 11080,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_1 (Conv2D) (None, 128, 128, 16) 448 _________________________________________________________________leaky_re_lu_1 (LeakyReLU) (None, 128, 128, 16) 0 _________________________________________________________________conv2d_2 (Conv2D) (None, 64, 64, 8) 1160 _________________________________________________________________leaky_re_lu_2 (LeakyReLU) (None, 64, 64, 8) 0 _________________________________________________________________conv2d_3 (Conv2D) (None, 32, 32, 16) 1168 _________________________________________________________________leaky_re_lu_3 (LeakyReLU) (None, 32, 32, 16) 0 _________________________________________________________________conv2d_4 (Conv2D) (None, 16, 16, 8) 1160 _________________________________________________________________leaky_re_lu_4 (LeakyReLU) (None, 16, 16, 8) 0 _________________________________________________________________flatten_1 (Flatten) (None, 2048) 0 _________________________________________________________________dropout_1 (Dropout) (None, 2048) 0 _________________________________________________________________dense_1 (Dense) (None, 1) 2049 =================================================================Total params: 11,970Trainable params: 5,985Non-trainable params: 5,985_________________________________________________________________"
},
{
"code": null,
"e": 12857,
"s": 12841,
"text": "Generator model"
},
{
"code": null,
"e": 14491,
"s": 12857,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense_2 (Dense) (None, 65536) 6619136 _________________________________________________________________leaky_re_lu_5 (LeakyReLU) (None, 65536) 0 _________________________________________________________________reshape_1 (Reshape) (None, 16, 16, 256) 0 _________________________________________________________________conv2d_transpose_1 (Conv2DTr (None, 32, 32, 128) 524416 _________________________________________________________________leaky_re_lu_6 (LeakyReLU) (None, 32, 32, 128) 0 _________________________________________________________________conv2d_transpose_2 (Conv2DTr (None, 64, 64, 128) 262272 _________________________________________________________________leaky_re_lu_7 (LeakyReLU) (None, 64, 64, 128) 0 _________________________________________________________________conv2d_transpose_3 (Conv2DTr (None, 128, 128, 128) 262272 _________________________________________________________________leaky_re_lu_8 (LeakyReLU) (None, 128, 128, 128) 0 _________________________________________________________________conv2d_5 (Conv2D) (None, 128, 128, 3) 3459 =================================================================Total params: 7,671,555Trainable params: 7,671,555Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 14543,
"s": 14491,
"text": "The training processes will look like below snippet"
},
{
"code": null,
"e": 15236,
"s": 14543,
"text": ".....>319, 5/10, d1=0.692, d2=0.761 g=0.709>319, 6/10, d1=0.822, d2=0.759 g=0.690>319, 7/10, d1=0.733, d2=0.764 g=0.723>319, 8/10, d1=0.662, d2=0.740 g=0.743>319, 9/10, d1=0.701, d2=0.683 g=0.758>319, 10/10, d1=0.830, d2=0.744 g=0.728>320, 1/10, d1=0.749, d2=0.717 g=0.731>320, 2/10, d1=0.677, d2=0.796 g=0.722>320, 3/10, d1=0.766, d2=0.700 g=0.717>320, 4/10, d1=0.676, d2=0.736 g=0.765>320, 5/10, d1=0.792, d2=0.762 g=0.730>320, 6/10, d1=0.690, d2=0.710 g=0.719>320, 7/10, d1=0.807, d2=0.759 g=0.708>320, 8/10, d1=0.715, d2=0.747 g=0.711>320, 9/10, d1=0.719, d2=0.720 g=0.731>320, 10/10, d1=0.695, d2=0.717 g=0.694################# Summarize ###################>Accuracy real: 35%, fake: 57%"
},
{
"code": null,
"e": 15439,
"s": 15236,
"text": "After 320 epochs, below is the quality of images I was able to produce. Training for this GAN took ~ 30 minutes. More complex generator and discriminator model could have produced better quality images."
},
{
"code": null,
"e": 15485,
"s": 15439,
"text": "Progression of the GAN towards a perfect cube"
},
{
"code": null,
"e": 15721,
"s": 15485,
"text": "Now these newly generated minority class images can be added to the original imbalanced dataset. This will help convert imbalanced multi class data into a balanced dataset. This will improve the classification performance of the model."
},
{
"code": null,
"e": 15801,
"s": 15721,
"text": "An image classification algorithm for this imbalanced dataset can be found here"
},
{
"code": null,
"e": 15824,
"s": 15801,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15920,
"s": 15824,
"text": "All the iPython notebooks are available at https://github.com/swanandM/DC-GAN-RetinopathyImages"
},
{
"code": null,
"e": 16018,
"s": 15920,
"text": "Image classification notebooks https://github.com/swanandM/Diabetic-Retinopathy-Detection-with-TF"
},
{
"code": null,
"e": 16045,
"s": 16018,
"text": "Exciting use cases of GANs"
},
{
"code": null,
"e": 16448,
"s": 16045,
"text": "GAN has made impressive progress in its first few years. In 2017, GAN was able to create a 1024 x 1024 size images which were able to fool almost everyone. Although this kind of technology can create serious social trustworthiness issue considering the amount of fake news getting publish these days. Engineers have to be careful before developing any such application that will generate social unrest."
},
{
"code": null,
"e": 16695,
"s": 16448,
"text": "Creating animation for games as well as for movies takes tremendous efforts. GAN can auto-generate these animation characters without any professional skills. Besides this, a professional animation creator can take inspiration from these designs."
},
{
"code": null,
"e": 16760,
"s": 16695,
"text": "CycleGAN can transform images from one domain to another domain."
},
{
"code": null,
"e": 16893,
"s": 16760,
"text": "PixelDTGAN is used to generate marketing images based on celebrity pictures. This is also used as a suggestion tool based on images."
},
{
"code": null,
"e": 17041,
"s": 16893,
"text": "Text to image is one of the application of domain transfer GAN. This has tremendous applications including photo editing and computer aided design."
},
{
"code": null,
"e": 17171,
"s": 17041,
"text": "Creating emoji from pictures is one of the well-known application already been used in platforms such as Snap chat and Instagram."
},
{
"code": null,
"e": 17182,
"s": 17171,
"text": "References"
},
{
"code": null,
"e": 17394,
"s": 17182,
"text": "Effective data generation for imbalanced learning using conditional generative adversarial networksHow to Develop a GAN to Generate CIFAR10 Small Color PhotographsSome cool applications of GANHow to train a GAN?"
},
{
"code": null,
"e": 17494,
"s": 17394,
"text": "Effective data generation for imbalanced learning using conditional generative adversarial networks"
},
{
"code": null,
"e": 17559,
"s": 17494,
"text": "How to Develop a GAN to Generate CIFAR10 Small Color Photographs"
},
{
"code": null,
"e": 17589,
"s": 17559,
"text": "Some cool applications of GAN"
}
] |
Find combined mean and variance of two series in Python
|
Suppose we have two different series A1 and A2 of size b and a respectively. We have to find the mean and variance of combined series.
So, if the input is like A1 = [24, 46, 35, 79, 13, 77, 35] and A2 = [66, 68, 35, 24, 46], then the output will be Mean = [44.1429, 47.8], sd = [548.694, 294.56], combined mean = 45.6667, d1_square = 2.322, d2_square = 4.5511, combined_var = 446.056
To solve this, we will follow these steps −
Define a function mean() . This will take arrreturn average of arr elements
Define a function mean() . This will take arr
return average of arr elements
return average of arr elements
Define a function sd() . This will take arr, n
Define a function sd() . This will take arr, n
sum := 0;
sum := 0;
for i in range 0 to n, dosum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))
for i in range 0 to n, do
sum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))
sum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))
sdd := sum / n
sdd := sum / n
return sdd
return sdd
From the main method, do the following −
From the main method, do the following −
n := size of A1, m := size of A2
n := size of A1, m := size of A2
mean1 := mean(A1), mean2 := mean(A2)
mean1 := mean(A1), mean2 := mean(A2)
display mean1 and mean2
display mean1 and mean2
sd1 := sd(A1, n), sd2 := sd(A2, m)
sd1 := sd(A1, n), sd2 := sd(A2, m)
display sd1 and sd2
display sd1 and sd2
combinedMean :=(n * mean1 + m * mean2) /(n + m)
combinedMean :=(n * mean1 + m * mean2) /(n + m)
display combinedMean
display combinedMean
d1_square :=(mean1 - combinedMean) *(mean1 - combinedMean)
d1_square :=(mean1 - combinedMean) *(mean1 - combinedMean)
d2_square :=(mean2 - combinedMean) *(mean2 - combinedMean)
d2_square :=(mean2 - combinedMean) *(mean2 - combinedMean)
display d1_square, d2_square
display d1_square, d2_square
comb_var :=(n *(sd1 + d1_square) + m *(sd2 + d2_square)) /(n + m)
comb_var :=(n *(sd1 + d1_square) + m *(sd2 + d2_square)) /(n + m)
display comb_var
display comb_var
Let us see the following implementation to get better understanding −
Live Demo
def mean(arr):
return sum(arr)/len(arr)
def sd(arr, n):
sum = 0;
for i in range(n):
sum = sum + ((arr[i] - mean(arr)) * (arr[i] - mean(arr)))
sdd = sum / n
return sdd
def combinedVariance(A1, A2):
n = len(A1)
m = len(A2)
mean1 = mean(A1)
mean2 = mean(A2)
print("mean_1: ", round(mean1, 2), " mean_2: ", round(mean2, 2))
sd1 = sd(A1, n)
sd2 = sd(A2, m)
print("sd_1: ", round(sd1, 2)," sd_2: ", round(sd2, 2))
combinedMean = (n * mean1 + m * mean2) / (n + m)
print("Combined Mean: ", round(combinedMean, 2))
d1_square = ((mean1 - combinedMean) * (mean1 - combinedMean))
d2_square = ((mean2 - combinedMean) * (mean2 - combinedMean))
print("d1_square: ", round(d1_square, 2), " d2_square: ", round(d2_square, 2))
comb_var = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m)
print("Combined Variance: ", round(comb_var, 2))
A1 = [24, 46, 35, 79, 13, 77, 35 ]
A2 = [66, 68, 35, 24, 46 ]
n = len(A1)
m = len(A2)
combinedVariance(A1, A2)
[24, 46, 35, 79, 13, 77, 35 ],[66, 68, 35, 24, 46 ]
mean_1: 44.14 mean_2: 47.8
sd_1: 548.69 sd_2: 294.56
Combined Mean: 45.67
d1_square: 2.32 d2_square: 4.55
Combined Variance: 446.06
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Suppose we have two different series A1 and A2 of size b and a respectively. We have to find the mean and variance of combined series."
},
{
"code": null,
"e": 1446,
"s": 1197,
"text": "So, if the input is like A1 = [24, 46, 35, 79, 13, 77, 35] and A2 = [66, 68, 35, 24, 46], then the output will be Mean = [44.1429, 47.8], sd = [548.694, 294.56], combined mean = 45.6667, d1_square = 2.322, d2_square = 4.5511, combined_var = 446.056"
},
{
"code": null,
"e": 1490,
"s": 1446,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1566,
"s": 1490,
"text": "Define a function mean() . This will take arrreturn average of arr elements"
},
{
"code": null,
"e": 1612,
"s": 1566,
"text": "Define a function mean() . This will take arr"
},
{
"code": null,
"e": 1643,
"s": 1612,
"text": "return average of arr elements"
},
{
"code": null,
"e": 1674,
"s": 1643,
"text": "return average of arr elements"
},
{
"code": null,
"e": 1721,
"s": 1674,
"text": "Define a function sd() . This will take arr, n"
},
{
"code": null,
"e": 1768,
"s": 1721,
"text": "Define a function sd() . This will take arr, n"
},
{
"code": null,
"e": 1778,
"s": 1768,
"text": "sum := 0;"
},
{
"code": null,
"e": 1788,
"s": 1778,
"text": "sum := 0;"
},
{
"code": null,
"e": 1871,
"s": 1788,
"text": "for i in range 0 to n, dosum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))"
},
{
"code": null,
"e": 1897,
"s": 1871,
"text": "for i in range 0 to n, do"
},
{
"code": null,
"e": 1955,
"s": 1897,
"text": "sum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))"
},
{
"code": null,
"e": 2013,
"s": 1955,
"text": "sum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))"
},
{
"code": null,
"e": 2028,
"s": 2013,
"text": "sdd := sum / n"
},
{
"code": null,
"e": 2043,
"s": 2028,
"text": "sdd := sum / n"
},
{
"code": null,
"e": 2054,
"s": 2043,
"text": "return sdd"
},
{
"code": null,
"e": 2065,
"s": 2054,
"text": "return sdd"
},
{
"code": null,
"e": 2106,
"s": 2065,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2147,
"s": 2106,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2180,
"s": 2147,
"text": "n := size of A1, m := size of A2"
},
{
"code": null,
"e": 2213,
"s": 2180,
"text": "n := size of A1, m := size of A2"
},
{
"code": null,
"e": 2250,
"s": 2213,
"text": "mean1 := mean(A1), mean2 := mean(A2)"
},
{
"code": null,
"e": 2287,
"s": 2250,
"text": "mean1 := mean(A1), mean2 := mean(A2)"
},
{
"code": null,
"e": 2311,
"s": 2287,
"text": "display mean1 and mean2"
},
{
"code": null,
"e": 2335,
"s": 2311,
"text": "display mean1 and mean2"
},
{
"code": null,
"e": 2370,
"s": 2335,
"text": "sd1 := sd(A1, n), sd2 := sd(A2, m)"
},
{
"code": null,
"e": 2405,
"s": 2370,
"text": "sd1 := sd(A1, n), sd2 := sd(A2, m)"
},
{
"code": null,
"e": 2425,
"s": 2405,
"text": "display sd1 and sd2"
},
{
"code": null,
"e": 2445,
"s": 2425,
"text": "display sd1 and sd2"
},
{
"code": null,
"e": 2493,
"s": 2445,
"text": "combinedMean :=(n * mean1 + m * mean2) /(n + m)"
},
{
"code": null,
"e": 2541,
"s": 2493,
"text": "combinedMean :=(n * mean1 + m * mean2) /(n + m)"
},
{
"code": null,
"e": 2562,
"s": 2541,
"text": "display combinedMean"
},
{
"code": null,
"e": 2583,
"s": 2562,
"text": "display combinedMean"
},
{
"code": null,
"e": 2642,
"s": 2583,
"text": "d1_square :=(mean1 - combinedMean) *(mean1 - combinedMean)"
},
{
"code": null,
"e": 2701,
"s": 2642,
"text": "d1_square :=(mean1 - combinedMean) *(mean1 - combinedMean)"
},
{
"code": null,
"e": 2760,
"s": 2701,
"text": "d2_square :=(mean2 - combinedMean) *(mean2 - combinedMean)"
},
{
"code": null,
"e": 2819,
"s": 2760,
"text": "d2_square :=(mean2 - combinedMean) *(mean2 - combinedMean)"
},
{
"code": null,
"e": 2848,
"s": 2819,
"text": "display d1_square, d2_square"
},
{
"code": null,
"e": 2877,
"s": 2848,
"text": "display d1_square, d2_square"
},
{
"code": null,
"e": 2943,
"s": 2877,
"text": "comb_var :=(n *(sd1 + d1_square) + m *(sd2 + d2_square)) /(n + m)"
},
{
"code": null,
"e": 3009,
"s": 2943,
"text": "comb_var :=(n *(sd1 + d1_square) + m *(sd2 + d2_square)) /(n + m)"
},
{
"code": null,
"e": 3026,
"s": 3009,
"text": "display comb_var"
},
{
"code": null,
"e": 3043,
"s": 3026,
"text": "display comb_var"
},
{
"code": null,
"e": 3113,
"s": 3043,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3124,
"s": 3113,
"text": " Live Demo"
},
{
"code": null,
"e": 4125,
"s": 3124,
"text": "def mean(arr):\nreturn sum(arr)/len(arr)\ndef sd(arr, n):\n sum = 0;\n for i in range(n):\n sum = sum + ((arr[i] - mean(arr)) * (arr[i] - mean(arr)))\n sdd = sum / n\n return sdd\ndef combinedVariance(A1, A2):\n n = len(A1)\n m = len(A2)\n mean1 = mean(A1)\n mean2 = mean(A2)\n print(\"mean_1: \", round(mean1, 2), \" mean_2: \", round(mean2, 2))\n sd1 = sd(A1, n)\n sd2 = sd(A2, m)\n print(\"sd_1: \", round(sd1, 2),\" sd_2: \", round(sd2, 2))\n combinedMean = (n * mean1 + m * mean2) / (n + m)\n print(\"Combined Mean: \", round(combinedMean, 2))\n d1_square = ((mean1 - combinedMean) * (mean1 - combinedMean))\n d2_square = ((mean2 - combinedMean) * (mean2 - combinedMean))\n print(\"d1_square: \", round(d1_square, 2), \" d2_square: \", round(d2_square, 2))\n comb_var = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m)\n print(\"Combined Variance: \", round(comb_var, 2))\nA1 = [24, 46, 35, 79, 13, 77, 35 ]\nA2 = [66, 68, 35, 24, 46 ]\nn = len(A1)\nm = len(A2)\ncombinedVariance(A1, A2)"
},
{
"code": null,
"e": 4177,
"s": 4125,
"text": "[24, 46, 35, 79, 13, 77, 35 ],[66, 68, 35, 24, 46 ]"
},
{
"code": null,
"e": 4309,
"s": 4177,
"text": "mean_1: 44.14 mean_2: 47.8\nsd_1: 548.69 sd_2: 294.56\nCombined Mean: 45.67\nd1_square: 2.32 d2_square: 4.55\nCombined Variance: 446.06"
}
] |
Working with Docker Volumes
|
To define Docker Volumes, they are file systems that can be mounted on Docker containers. They help in preserving the data and are independent of the container life cycle. One of the major advantages of Docker Volumes is that it allows the developers to backup their data and also allows easy sharing of file systems among Docker containers. We can easily mount a volume when we launch a Docker container. It is also possible to mount the same volume to different containers and this allows easy sharing of data between them and this can be easily achieved with the use of simple commands and flags.
In this article, we are going to discuss how to create, list, inspect, mount and delete docker volumes with the help of commands.
You can create a Docker volume using the create command. On executing the command, Docker creates a particular directory for volume on the local machine. This directory is located in the path /var/lib/docker/volume.
The command for creating a Docker volume is −
sudo docker volume create <volume_name>
For example, if you want to create a volume with the name myVolume, you can do so using the following command.
sudo docker volume create myVolume.
Now that you have created a docker volume, if you want to list all the existing Docker volumes, you can do so using the following command.
sudo docker volume list
Once you run the above command, a list will be displayed which would contain the driver name and the volume name of all the existing volumes.
To inspect a particular Docker volume, you can use the Docker inspect command. It would list all the details regarding the Docker volume which would include the date of creation, mountpoint, driver name, name of the volume, etc.
The command for inspecting a Docker volume is −
sudo docker volume inspect <volume_name>
You can easily mount a Docker Volume to a Docker container using the --mount flag when you are running the Docker run command. You can also mount the same volume to multiple Docker containers and all the containers would have a shared access to the volume. The command for this is
sudo docker run −−mount source=<name of volume>,destination=<path of a directory in container> <image_name>
For example, if you want to mount a volume called myVolume to an ubuntu container at a location /usr/src/app/ inside the container, you can do so using the following command −
sudo docker run −it −−mount source=myVolume,destination=/usr/src/app/ ubuntu
This would open an ubuntu bash with the volume mounted in the specified location. You can verify this by going to the specified location inside the container.
In order to delete a docker volume, you need to ensure that the volume is not in use at that moment. If a container is running with the volume mounted in it, you would have to stop the container first before removing the mounted volume. After you have stopped the container, you can use the following command to remove the volume.
sudo docker rm <name of volume>
In order to delete all the volumes at once, you need to make sure that none of the volumes is currently in use and then use the following command.
sudo docker volume prune
Suppose that you want to share some files with multiple docker containers. In this case, you can put your files in a docker volume, mount that volume with multiple docker containers and get a shared access to that volume. Let’s discuss how to do that.
First create a volume using the volume create command and mount that volume to a particular docker container.
For example,
sudo docker volume create myVolume
sudo docker run −it −−name=container1 −−mount source=myVolume,destination=/app ubuntu
The above two commands would create a docker volume called myVolume and will mount this volume to a container called container1 of ubuntu image at a destination /app. And this would also open the bash of that particular container.
Inside the bash, you can see a directory called /app created there. Use the ls command to do so. Go to that directory and create a file and exit the bash. You can use the commands below.
ls
cd app
touch tutorialspoint.txt
exit
After that create a new container and mount the same volume in that container. You can use the below command.
sudo docker run −it −−name=container2 −−mount source=myVolume,destination=/app ubuntu
This would create a second container called container2 and mount the volume called myVolume at the location /app of the ubuntu image. You can verify the same by using the ls command. After going inside the /app directory, you would see the same tutorialspoint.txt file which you created in container1. If you make any changes inside the file, it would reflect in the other container as well.
To conclude, in this article, we saw all the basic commands to create, inspect, list, remove docker volumes. We also saw how to share a file among multiple docker containers by mounting the same volume to different docker containers.
|
[
{
"code": null,
"e": 1662,
"s": 1062,
"text": "To define Docker Volumes, they are file systems that can be mounted on Docker containers. They help in preserving the data and are independent of the container life cycle. One of the major advantages of Docker Volumes is that it allows the developers to backup their data and also allows easy sharing of file systems among Docker containers. We can easily mount a volume when we launch a Docker container. It is also possible to mount the same volume to different containers and this allows easy sharing of data between them and this can be easily achieved with the use of simple commands and flags."
},
{
"code": null,
"e": 1792,
"s": 1662,
"text": "In this article, we are going to discuss how to create, list, inspect, mount and delete docker volumes with the help of commands."
},
{
"code": null,
"e": 2008,
"s": 1792,
"text": "You can create a Docker volume using the create command. On executing the command, Docker creates a particular directory for volume on the local machine. This directory is located in the path /var/lib/docker/volume."
},
{
"code": null,
"e": 2054,
"s": 2008,
"text": "The command for creating a Docker volume is −"
},
{
"code": null,
"e": 2094,
"s": 2054,
"text": "sudo docker volume create <volume_name>"
},
{
"code": null,
"e": 2205,
"s": 2094,
"text": "For example, if you want to create a volume with the name myVolume, you can do so using the following command."
},
{
"code": null,
"e": 2241,
"s": 2205,
"text": "sudo docker volume create myVolume."
},
{
"code": null,
"e": 2380,
"s": 2241,
"text": "Now that you have created a docker volume, if you want to list all the existing Docker volumes, you can do so using the following command."
},
{
"code": null,
"e": 2404,
"s": 2380,
"text": "sudo docker volume list"
},
{
"code": null,
"e": 2546,
"s": 2404,
"text": "Once you run the above command, a list will be displayed which would contain the driver name and the volume name of all the existing volumes."
},
{
"code": null,
"e": 2775,
"s": 2546,
"text": "To inspect a particular Docker volume, you can use the Docker inspect command. It would list all the details regarding the Docker volume which would include the date of creation, mountpoint, driver name, name of the volume, etc."
},
{
"code": null,
"e": 2823,
"s": 2775,
"text": "The command for inspecting a Docker volume is −"
},
{
"code": null,
"e": 2865,
"s": 2823,
"text": "sudo docker volume inspect <volume_name>\n"
},
{
"code": null,
"e": 3146,
"s": 2865,
"text": "You can easily mount a Docker Volume to a Docker container using the --mount flag when you are running the Docker run command. You can also mount the same volume to multiple Docker containers and all the containers would have a shared access to the volume. The command for this is"
},
{
"code": null,
"e": 3254,
"s": 3146,
"text": "sudo docker run −−mount source=<name of volume>,destination=<path of a directory in container> <image_name>"
},
{
"code": null,
"e": 3430,
"s": 3254,
"text": "For example, if you want to mount a volume called myVolume to an ubuntu container at a location /usr/src/app/ inside the container, you can do so using the following command −"
},
{
"code": null,
"e": 3507,
"s": 3430,
"text": "sudo docker run −it −−mount source=myVolume,destination=/usr/src/app/ ubuntu"
},
{
"code": null,
"e": 3666,
"s": 3507,
"text": "This would open an ubuntu bash with the volume mounted in the specified location. You can verify this by going to the specified location inside the container."
},
{
"code": null,
"e": 3997,
"s": 3666,
"text": "In order to delete a docker volume, you need to ensure that the volume is not in use at that moment. If a container is running with the volume mounted in it, you would have to stop the container first before removing the mounted volume. After you have stopped the container, you can use the following command to remove the volume."
},
{
"code": null,
"e": 4029,
"s": 3997,
"text": "sudo docker rm <name of volume>"
},
{
"code": null,
"e": 4176,
"s": 4029,
"text": "In order to delete all the volumes at once, you need to make sure that none of the volumes is currently in use and then use the following command."
},
{
"code": null,
"e": 4202,
"s": 4176,
"text": "sudo docker volume prune\n"
},
{
"code": null,
"e": 4454,
"s": 4202,
"text": "Suppose that you want to share some files with multiple docker containers. In this case, you can put your files in a docker volume, mount that volume with multiple docker containers and get a shared access to that volume. Let’s discuss how to do that."
},
{
"code": null,
"e": 4564,
"s": 4454,
"text": "First create a volume using the volume create command and mount that volume to a particular docker container."
},
{
"code": null,
"e": 4577,
"s": 4564,
"text": "For example,"
},
{
"code": null,
"e": 4612,
"s": 4577,
"text": "sudo docker volume create myVolume"
},
{
"code": null,
"e": 4698,
"s": 4612,
"text": "sudo docker run −it −−name=container1 −−mount source=myVolume,destination=/app ubuntu"
},
{
"code": null,
"e": 4929,
"s": 4698,
"text": "The above two commands would create a docker volume called myVolume and will mount this volume to a container called container1 of ubuntu image at a destination /app. And this would also open the bash of that particular container."
},
{
"code": null,
"e": 5116,
"s": 4929,
"text": "Inside the bash, you can see a directory called /app created there. Use the ls command to do so. Go to that directory and create a file and exit the bash. You can use the commands below."
},
{
"code": null,
"e": 5156,
"s": 5116,
"text": "ls\ncd app\ntouch tutorialspoint.txt\nexit"
},
{
"code": null,
"e": 5266,
"s": 5156,
"text": "After that create a new container and mount the same volume in that container. You can use the below command."
},
{
"code": null,
"e": 5352,
"s": 5266,
"text": "sudo docker run −it −−name=container2 −−mount source=myVolume,destination=/app ubuntu"
},
{
"code": null,
"e": 5744,
"s": 5352,
"text": "This would create a second container called container2 and mount the volume called myVolume at the location /app of the ubuntu image. You can verify the same by using the ls command. After going inside the /app directory, you would see the same tutorialspoint.txt file which you created in container1. If you make any changes inside the file, it would reflect in the other container as well."
},
{
"code": null,
"e": 5978,
"s": 5744,
"text": "To conclude, in this article, we saw all the basic commands to create, inspect, list, remove docker volumes. We also saw how to share a file among multiple docker containers by mounting the same volume to different docker containers."
}
] |
3 ways to query BigQuery in Python | by Sophia Yang | Towards Data Science
|
How do you query BigQuery data? This article talks about 3 ways to query BigQuery data in Python. Hope you find them useful.
conda install notebook google-cloud-bigquery sqlalchemy pybigquery
To authenticate Google Cloud locally, you will need to install Google Cloud SDK and log in/authenticate through the following command line. More information can be found in the official documentation.
gcloud auth login
To authenticate through a credential file, you can create a service account and get the credential from the service account: Go to the google cloud service account page, click on a project, click “+CREATE SERVICE ACCOUNT” and then it will generate a credential JSON file. In the following examples below, I renamed this credential file to “BIGQUERY_CREDENTIAL”.
The pybigquery project implements an SQLAlchemy tool for BigQuery. SQLAlchemy is a powerful tool to read SQL data in Python. Here is a description of SQLAlchemy from the documentation:
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
To use SQLAlchemy, the first step is to establish connectivity by using create_engine(). In the arguments of this function, we define the database we are trying to connect to "bigquery://" and the path of the credential file. If you are running it locally and authenticated locally, you can run the following without the credential info. If the output data is large, we can increase arraysize, which by default is 5000.
After we establish the connection to BigQuery, there are multiple ways to query the data. My go-to method is to use pd.read_sql from Pandas so that I can get a Pandas dataframe directly. In the pd.read_sql function, all we need is the specified query and the connection.
It is often useful to parameterize our queries. SQLAlchemy provides a built-in function text() that accepts query as input and supports parameterizations. Alternatively, you can write the parameters as f-strings in the query.
The second approach is to use the official Python Client for BigQuery. If you are running it locally and authenticated, you don’t need to define the credentials, and client=bigquery.Client() will just work.
The third approach is to use subprocess to run the bq command-line tool. The query command is bq query. We can pass in flags to the query to define the output format to be csv and specify the queries we want to run. Then we can use subprocess to run the command line code in Python.
bq command line tool supports query parameters. In the example below, we pass in the --parameter flag to define the name, type, and value information of the parameter. In the query itself we use @parameter_name to specify a parameter. Another thing to note is that if the output has too many rows, we can increase the --max_rows flag to be a large number.
In all, I quickly went through three ways to query BigQuery in Python.
The first approach, SQLAlchemy has many nice built-in functionalities and supports many different types of databases. For users who have used SQLAlchemy on other databases and liked its features, you might like the SQLAlchemy approach to query BigQuery.
The second approach is the official Python Client for Google BigQuery, which I personally find not quite as easy to use and the documentation could be better. I haven’t used it as much, so my impression could be wrong.
Finally, the bq command line tool is very powerful. It offers a broad set of functionality, not just querying data. I know a lot of people have concerns and prefer not to use subprocess. So it’s really up to your preferences on which one to use.
Happy BigQuerying!
https://googleapis.dev/python/google-api-core/latest/auth.html https://github.com/googleapis/python-bigquery-sqlalchemy https://www.sqlalchemy.org/ https://github.com/googleapis/python-bigquery https://googleapis.dev/python/bigquery/latest/index.html
By Sophia Yang on June 28, 2021
|
[
{
"code": null,
"e": 297,
"s": 172,
"text": "How do you query BigQuery data? This article talks about 3 ways to query BigQuery data in Python. Hope you find them useful."
},
{
"code": null,
"e": 364,
"s": 297,
"text": "conda install notebook google-cloud-bigquery sqlalchemy pybigquery"
},
{
"code": null,
"e": 565,
"s": 364,
"text": "To authenticate Google Cloud locally, you will need to install Google Cloud SDK and log in/authenticate through the following command line. More information can be found in the official documentation."
},
{
"code": null,
"e": 583,
"s": 565,
"text": "gcloud auth login"
},
{
"code": null,
"e": 945,
"s": 583,
"text": "To authenticate through a credential file, you can create a service account and get the credential from the service account: Go to the google cloud service account page, click on a project, click “+CREATE SERVICE ACCOUNT” and then it will generate a credential JSON file. In the following examples below, I renamed this credential file to “BIGQUERY_CREDENTIAL”."
},
{
"code": null,
"e": 1130,
"s": 945,
"text": "The pybigquery project implements an SQLAlchemy tool for BigQuery. SQLAlchemy is a powerful tool to read SQL data in Python. Here is a description of SQLAlchemy from the documentation:"
},
{
"code": null,
"e": 1269,
"s": 1130,
"text": "SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL."
},
{
"code": null,
"e": 1689,
"s": 1269,
"text": "To use SQLAlchemy, the first step is to establish connectivity by using create_engine(). In the arguments of this function, we define the database we are trying to connect to \"bigquery://\" and the path of the credential file. If you are running it locally and authenticated locally, you can run the following without the credential info. If the output data is large, we can increase arraysize, which by default is 5000."
},
{
"code": null,
"e": 1960,
"s": 1689,
"text": "After we establish the connection to BigQuery, there are multiple ways to query the data. My go-to method is to use pd.read_sql from Pandas so that I can get a Pandas dataframe directly. In the pd.read_sql function, all we need is the specified query and the connection."
},
{
"code": null,
"e": 2186,
"s": 1960,
"text": "It is often useful to parameterize our queries. SQLAlchemy provides a built-in function text() that accepts query as input and supports parameterizations. Alternatively, you can write the parameters as f-strings in the query."
},
{
"code": null,
"e": 2393,
"s": 2186,
"text": "The second approach is to use the official Python Client for BigQuery. If you are running it locally and authenticated, you don’t need to define the credentials, and client=bigquery.Client() will just work."
},
{
"code": null,
"e": 2676,
"s": 2393,
"text": "The third approach is to use subprocess to run the bq command-line tool. The query command is bq query. We can pass in flags to the query to define the output format to be csv and specify the queries we want to run. Then we can use subprocess to run the command line code in Python."
},
{
"code": null,
"e": 3032,
"s": 2676,
"text": "bq command line tool supports query parameters. In the example below, we pass in the --parameter flag to define the name, type, and value information of the parameter. In the query itself we use @parameter_name to specify a parameter. Another thing to note is that if the output has too many rows, we can increase the --max_rows flag to be a large number."
},
{
"code": null,
"e": 3103,
"s": 3032,
"text": "In all, I quickly went through three ways to query BigQuery in Python."
},
{
"code": null,
"e": 3357,
"s": 3103,
"text": "The first approach, SQLAlchemy has many nice built-in functionalities and supports many different types of databases. For users who have used SQLAlchemy on other databases and liked its features, you might like the SQLAlchemy approach to query BigQuery."
},
{
"code": null,
"e": 3576,
"s": 3357,
"text": "The second approach is the official Python Client for Google BigQuery, which I personally find not quite as easy to use and the documentation could be better. I haven’t used it as much, so my impression could be wrong."
},
{
"code": null,
"e": 3822,
"s": 3576,
"text": "Finally, the bq command line tool is very powerful. It offers a broad set of functionality, not just querying data. I know a lot of people have concerns and prefer not to use subprocess. So it’s really up to your preferences on which one to use."
},
{
"code": null,
"e": 3841,
"s": 3822,
"text": "Happy BigQuerying!"
},
{
"code": null,
"e": 4092,
"s": 3841,
"text": "https://googleapis.dev/python/google-api-core/latest/auth.html https://github.com/googleapis/python-bigquery-sqlalchemy https://www.sqlalchemy.org/ https://github.com/googleapis/python-bigquery https://googleapis.dev/python/bigquery/latest/index.html"
}
] |
How to use variable number of arguments to function in JavaScript?
|
To use a variable number of arguments to function, use the arguments object.
You can try to run the following code to implement arguments to a function in JavaScript
Live Demo
<html>
<body>
<script>
function functionArgument(val1, val2, val3) {
var res = "";
res += "Expected Arguments: " + functionArgument.length;
res += "<br />";
res += "Current Arguments : " + arguments.length;
res += "<br />";
res += "Each argument = "
for (p = 0; p < arguments.length; p++) {
res += "<br />";
res += functionArgument.arguments[p];
res += " ";
}
document.write(res);
}
functionArgument(20, 50, 80, "Demo Text!","Hello World", new Date())
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To use a variable number of arguments to function, use the arguments object."
},
{
"code": null,
"e": 1228,
"s": 1139,
"text": "You can try to run the following code to implement arguments to a function in JavaScript"
},
{
"code": null,
"e": 1238,
"s": 1228,
"text": "Live Demo"
},
{
"code": null,
"e": 1917,
"s": 1238,
"text": "<html>\n <body>\n <script>\n function functionArgument(val1, val2, val3) {\n var res = \"\";\n res += \"Expected Arguments: \" + functionArgument.length;\n res += \"<br />\";\n res += \"Current Arguments : \" + arguments.length;\n\n res += \"<br />\";\n res += \"Each argument = \"\n\n for (p = 0; p < arguments.length; p++) {\n res += \"<br />\";\n res += functionArgument.arguments[p];\n res += \" \";\n }\n document.write(res);\n }\n functionArgument(20, 50, 80, \"Demo Text!\",\"Hello World\", new Date())\n </script>\n </body>\n</html>"
}
] |
C Program to Rotate bits of a number - GeeksforGeeks
|
11 Dec, 2021
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end.
Example: Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000...11100101) becomes 00..0011100101000. Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000...11100101) by 3 becomes 101000..0011100.
C
#include<stdio.h>#define INT_BITS 32 /*Function to left rotate n by d bits*/int leftRotate(int n, unsigned int d){ /* In n<<d, last d bits are 0. To put first 3 bits of n at last, do bitwise or of n<<d with n >>(INT_BITS - d) */ return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){ /* In n>>d, first d bits are 0. To put last 3 bits of at first, do bitwise or of n>>d with n <<(INT_BITS - d) */ return (n >> d)|(n << (INT_BITS - d));} /* Driver program to test above functions */int main(){ int n = 16; int d = 2; printf("Left Rotation of %d by %d is ", n, d); printf("%d", leftRotate(n, d)); printf("Right Rotation of %d by %d is ", n, d); printf("%d", rightRotate(n, d)); getchar();}
Output :
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
Please refer complete article on Rotate bits of a number for more details!
rotation
Bit Magic
C Programs
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Hamming code Implementation in C/C++
Write an Efficient Method to Check if a Number is Multiple of 3
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 24988,
"s": 24960,
"text": "\n11 Dec, 2021"
},
{
"code": null,
"e": 25305,
"s": 24988,
"text": "Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end. "
},
{
"code": null,
"e": 25824,
"s": 25305,
"text": "Example: Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000...11100101) becomes 00..0011100101000. Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000...11100101) by 3 becomes 101000..0011100. "
},
{
"code": null,
"e": 25826,
"s": 25824,
"text": "C"
},
{
"code": "#include<stdio.h>#define INT_BITS 32 /*Function to left rotate n by d bits*/int leftRotate(int n, unsigned int d){ /* In n<<d, last d bits are 0. To put first 3 bits of n at last, do bitwise or of n<<d with n >>(INT_BITS - d) */ return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){ /* In n>>d, first d bits are 0. To put last 3 bits of at first, do bitwise or of n>>d with n <<(INT_BITS - d) */ return (n >> d)|(n << (INT_BITS - d));} /* Driver program to test above functions */int main(){ int n = 16; int d = 2; printf(\"Left Rotation of %d by %d is \", n, d); printf(\"%d\", leftRotate(n, d)); printf(\"Right Rotation of %d by %d is \", n, d); printf(\"%d\", rightRotate(n, d)); getchar();} ",
"e": 26608,
"s": 25826,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26608,
"text": "Output : "
},
{
"code": null,
"e": 26680,
"s": 26618,
"text": "Left Rotation of 16 by 2 is 64\nRight Rotation of 16 by 2 is 4"
},
{
"code": null,
"e": 26755,
"s": 26680,
"text": "Please refer complete article on Rotate bits of a number for more details!"
},
{
"code": null,
"e": 26764,
"s": 26755,
"text": "rotation"
},
{
"code": null,
"e": 26774,
"s": 26764,
"text": "Bit Magic"
},
{
"code": null,
"e": 26785,
"s": 26774,
"text": "C Programs"
},
{
"code": null,
"e": 26795,
"s": 26785,
"text": "Bit Magic"
},
{
"code": null,
"e": 26893,
"s": 26795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26944,
"s": 26893,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 26981,
"s": 26944,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 27004,
"s": 26981,
"text": "Program to find parity"
},
{
"code": null,
"e": 27041,
"s": 27004,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 27105,
"s": 27041,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 27118,
"s": 27105,
"text": "Strings in C"
},
{
"code": null,
"e": 27159,
"s": 27118,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27197,
"s": 27159,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27238,
"s": 27197,
"text": "C Program to read contents of Whole File"
}
] |
How to calculate Execution Time of a Code Snippet in C++?
|
We can calculate the execution time of a code snippet by using following syntax −
auto start = high_resolution_clock::now(); // Start time
// Code snippet
auto stop = high_resolution_clock::now(); // Stop time
auto duration = duration_cast<microseconds>(stop - start); // Duration
The class high_resolution_clock is defined in “chrono” header file. The function now() is returning a value corresponding to the call’s point in time.
A header file is used to record the time taken by that particular code.
#include <chrono>
using namespace std::chrono;
The following is an example to calculate execution time of a code snippet.
Live Demo
#include <iostream>
#include <chrono>
using namespace std::chrono;
using namespace std;
int sum(int x, int y) {
int s = x + y;
cout << "The sum of numbers : " << s;
}
int main() {
auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "\nTime taken by function : "<< duration.count() << " microseconds";
return 0;
}
The sum of numbers : 36
Time taken by function : 42 microseconds
In the above program, a function sum() is defined to calculate the sum of numbers.
int sum(int x, int y) {
int s = x + y;
cout << "The sum of numbers : " << s;
}
In the main() function, we recorded the time taken by the function sum() by using some predefined functions and class “chrono”.
auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "We can calculate the execution time of a code snippet by using following syntax −"
},
{
"code": null,
"e": 1343,
"s": 1144,
"text": "auto start = high_resolution_clock::now(); // Start time\n// Code snippet\nauto stop = high_resolution_clock::now(); // Stop time\nauto duration = duration_cast<microseconds>(stop - start); // Duration"
},
{
"code": null,
"e": 1494,
"s": 1343,
"text": "The class high_resolution_clock is defined in “chrono” header file. The function now() is returning a value corresponding to the call’s point in time."
},
{
"code": null,
"e": 1566,
"s": 1494,
"text": "A header file is used to record the time taken by that particular code."
},
{
"code": null,
"e": 1613,
"s": 1566,
"text": "#include <chrono>\nusing namespace std::chrono;"
},
{
"code": null,
"e": 1688,
"s": 1613,
"text": "The following is an example to calculate execution time of a code snippet."
},
{
"code": null,
"e": 1699,
"s": 1688,
"text": " Live Demo"
},
{
"code": null,
"e": 2148,
"s": 1699,
"text": "#include <iostream>\n#include <chrono>\nusing namespace std::chrono;\nusing namespace std;\nint sum(int x, int y) {\n int s = x + y;\n cout << \"The sum of numbers : \" << s;\n}\nint main() {\n auto start = high_resolution_clock::now();\n sum(28, 8);\n auto stop = high_resolution_clock::now();\n auto duration = duration_cast<microseconds>(stop - start);\n cout << \"\\nTime taken by function : \"<< duration.count() << \" microseconds\";\n return 0;\n}"
},
{
"code": null,
"e": 2213,
"s": 2148,
"text": "The sum of numbers : 36\nTime taken by function : 42 microseconds"
},
{
"code": null,
"e": 2296,
"s": 2213,
"text": "In the above program, a function sum() is defined to calculate the sum of numbers."
},
{
"code": null,
"e": 2381,
"s": 2296,
"text": "int sum(int x, int y) {\n int s = x + y;\n cout << \"The sum of numbers : \" << s;\n}"
},
{
"code": null,
"e": 2509,
"s": 2381,
"text": "In the main() function, we recorded the time taken by the function sum() by using some predefined functions and class “chrono”."
},
{
"code": null,
"e": 2665,
"s": 2509,
"text": "auto start = high_resolution_clock::now();\nsum(28, 8);\nauto stop = high_resolution_clock::now();\nauto duration = duration_cast<microseconds>(stop - start);"
}
] |
Cypress - Working with XHR
|
XHR is XML HTTP Request. It is an Application Programming Interface (API) which is available as an object, whose methods send data between a web browser and server. An object in XHR can request data from a server in the form of a response.
Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response. An XHR details can be seen in the Network tab in the browser.
XHR response Header is as follows −
The response is as follows −
To make an XHR request, the cy.request() command is used. The method cy.intercept() is used to redirect the responses to the matching requests.
Given below is the command to explain the implementation of XHR request in Cypress −
cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
//aliasing request
cy.get('@c').should((response) => {
expect(response.body).to.have.length(100)
expect(response).to.have.property('headers')
})
73 Lectures
12 hours
Rahul Shetty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2737,
"s": 2497,
"text": "XHR is XML HTTP Request. It is an Application Programming Interface (API) which is available as an object, whose methods send data between a web browser and server. An object in XHR can request data from a server in the form of a response."
},
{
"code": null,
"e": 3013,
"s": 2737,
"text": "Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response. An XHR details can be seen in the Network tab in the browser."
},
{
"code": null,
"e": 3049,
"s": 3013,
"text": "XHR response Header is as follows −"
},
{
"code": null,
"e": 3078,
"s": 3049,
"text": "The response is as follows −"
},
{
"code": null,
"e": 3222,
"s": 3078,
"text": "To make an XHR request, the cy.request() command is used. The method cy.intercept() is used to redirect the responses to the matching requests."
},
{
"code": null,
"e": 3307,
"s": 3222,
"text": "Given below is the command to explain the implementation of XHR request in Cypress −"
},
{
"code": null,
"e": 3524,
"s": 3307,
"text": "cy.request('https://jsonplaceholder.cypress.io/comments').as('c')\n//aliasing request\ncy.get('@c').should((response) => {\n expect(response.body).to.have.length(100)\n expect(response).to.have.property('headers')\n})"
},
{
"code": null,
"e": 3558,
"s": 3524,
"text": "\n 73 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3572,
"s": 3558,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 3579,
"s": 3572,
"text": " Print"
},
{
"code": null,
"e": 3590,
"s": 3579,
"text": " Add Notes"
}
] |
TypeScript - Number toFixed()
|
This method formats a number with a specific number of digits to the right of the decimal.
number.toFixed( [digits] )
digits − The number of digits to appear after the decimal point.
A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place.
var num3 = 177.234
console.log("num3.toFixed() is "+num3.toFixed())
console.log("num3.toFixed(2) is "+num3.toFixed(2))
console.log("num3.toFixed(6) is "+num3.toFixed(6))
On compiling, it will generate the same code in JavaScript.
The code will produce the following output −
num3.toFixed() is 177
num3.toFixed(2) is 177.23
num3.toFixed(6) is 177.234000
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2139,
"s": 2048,
"text": "This method formats a number with a specific number of digits to the right of the decimal."
},
{
"code": null,
"e": 2167,
"s": 2139,
"text": "number.toFixed( [digits] )\n"
},
{
"code": null,
"e": 2232,
"s": 2167,
"text": "digits − The number of digits to appear after the decimal point."
},
{
"code": null,
"e": 2365,
"s": 2232,
"text": "A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place."
},
{
"code": null,
"e": 2539,
"s": 2365,
"text": "var num3 = 177.234 \nconsole.log(\"num3.toFixed() is \"+num3.toFixed()) \nconsole.log(\"num3.toFixed(2) is \"+num3.toFixed(2)) \nconsole.log(\"num3.toFixed(6) is \"+num3.toFixed(6))\n"
},
{
"code": null,
"e": 2599,
"s": 2539,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2644,
"s": 2599,
"text": "The code will produce the following output −"
},
{
"code": null,
"e": 2725,
"s": 2644,
"text": "num3.toFixed() is 177 \nnum3.toFixed(2) is 177.23 \nnum3.toFixed(6) is 177.234000\n"
},
{
"code": null,
"e": 2758,
"s": 2725,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2772,
"s": 2758,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2805,
"s": 2772,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2819,
"s": 2805,
"text": " Haider Malik"
},
{
"code": null,
"e": 2854,
"s": 2819,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2874,
"s": 2854,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2907,
"s": 2874,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2921,
"s": 2907,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2956,
"s": 2921,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2972,
"s": 2956,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3005,
"s": 2972,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3025,
"s": 3005,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3032,
"s": 3025,
"text": " Print"
},
{
"code": null,
"e": 3043,
"s": 3032,
"text": " Add Notes"
}
] |
KnockoutJS - Observables
|
KnockoutJS is build upon the following 3 important concepts.
Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking.
Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking.
Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept.
Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept.
Templating to create re-usable components - Templating provides a robust way to create complex web applications.
Templating to create re-usable components - Templating provides a robust way to create complex web applications.
We will study Observables in this chapter.
As the name specifies, when you declare a ViewModel data/property as Observable, any data modification each time automatically gets reflected at all places the data is used. This also includes refreshing the related dependencies. KO takes care of these things and there is no need to write extra code to achieve this.
Using Observable, it becomes very easy to make UI and ViewModel communicate dynamically.
You just need to declare ViewModel property with function ko.observable() to make it Observable.
this.property = ko.observable('value');
Let's take a look at the following example which demonstrates the use of Observable.
<!DOCTYPE html>
<head>
<title>KnockoutJS Observable Example</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<!-- This is called "view" of HTML markup that defines the appearance of UI -->
<p>Enter your name: <input data-bind = "value: yourName" /></p>
<p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>
<script>
<!-- This is called "viewmodel". This javascript section defines the data and behavior of UI -->
function AppViewModel() {
this.yourName = ko.observable("");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
The following line is for the input box. As can be seen, we have used data-bind attribute to bind yourName value to ViewModel.
<p>Enter your name: <input data-bind = "value: yourName" /> <p>
The following line just prints the value of yourName. Note, that here data-bind type is the text as we are simply reading the value.
<p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>
In the following line, ko.observable keeps an eye on yourName variable for any modification in data. Once there is a modification, the corresponding places also get updated with the modified value. When you run the following code, an input box will appear. As and when you update that input box, the new value will get reflected or refreshed in places wherever it is used.
this.yourName = ko.observable("");
Let's carry out the following steps to see how the above code works −
Save the above code in first_observable_pgm.htm file.
Save the above code in first_observable_pgm.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter the name as Scott and observe that the name is reflected in the output.
Enter the name as Scott and observe that the name is reflected in the output.
Enter your name:
Hi Good Morning!!!
Data modification can take place either from the UI or from ViewModel. Irrespective of from where the data is changed, the UI and ViewModel keeps synchronization among them. This makes it a two-way-binding mechanism. In the above example, when you change your name in the input box, ViewModel gets a new value. When you change yourName property from inside ViewModel, then the UI receives a new value.
Following table lists the read and write operations which can be performed on Observables.
Read
To read value just call Observable property without parameters like: AppViewModel.yourName();
Write
To write/update value in Observable property, just pass the desired value in parameter like: AppViewModel.yourName('Bob');
Write multiple
Multiple ViewModel properties can be updated in a single row with the help of chaining-syntax like: AppViewModel.yourName('Bob').yourAge(45);
Observable declaration takes care of data modifications of a single object. ObservableArray works with the collection of objects. This is a very useful feature when you are dealing with complex applications containing multiple type of values and changing their status frequently based on the user actions.
this.arrayName = ko.observableArray(); // It's an empty array
Observable array only tracks which objects in it are added or removed. It does not notify if the individual object's properties are modified.
You can initialize your array and at the same time you can declare it as Observable by passing the initial values to the constructor as follows.
this.arrayName = ko.observableArray(['scott','jack']);
You can access Observable array elements as follows.
alert('The second element is ' + arrayName()[1]);
KnockoutJS has its own set of Observable array functions. They are convenient because −
These functions work on all browsers.
These functions work on all browsers.
These functions will take care of dependency tracking automatically.
These functions will take care of dependency tracking automatically.
Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value').
Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value').
Following is the list of various Observable Array methods.
Inserts a new item at the end of array.
Removes the last item from the array and returns it.
Inserts a new value at the beginning of the array.
Removes the first item from the array and returns it.
Reverses the order of the array.
Sorts array items in an ascending order.
Accepts 2 parameters - start-index and end-index - removes items starting from start to end index and returns them as an array.
This function returns the index of the first occurrence of parameter provided.
This method slices out a piece of an array. Returns the items from start-index up to end-index.
Removes all items and returns them as an array.
Removes items that match the parameter and returns as an array.
Removes items which are satisfying the condition and returns them as an array.
Removes items that match with a given set of values.
destroyAll()
Marks all items in an array with property _destroy with value true.
destroy('value')
Searches for an item equal to the parameter and mark it with a special property _destroy with value true.
destroy(function(item) { condition})
Finds all items which are satisfying the condition, marks them with property _destroy with true value.
destroy([set of values])
Finds the items that match with a given set of values, marks them as _destroy with true value.
Note − Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on Rails' developers only.
When you use destroy method, the corresponding items are not really deleted from array at that moment but are made hidden by marking them with property _destroy with true value so that they can't be read by UI. Items marked as _destroy equal to true are deleted later while dealing with JSON object graph.
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1913,
"s": 1852,
"text": "KnockoutJS is build upon the following 3 important concepts."
},
{
"code": null,
"e": 2122,
"s": 1913,
"text": "Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking."
},
{
"code": null,
"e": 2331,
"s": 2122,
"text": "Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking."
},
{
"code": null,
"e": 2444,
"s": 2331,
"text": "Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept."
},
{
"code": null,
"e": 2557,
"s": 2444,
"text": "Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept."
},
{
"code": null,
"e": 2670,
"s": 2557,
"text": "Templating to create re-usable components - Templating provides a robust way to create complex web applications."
},
{
"code": null,
"e": 2783,
"s": 2670,
"text": "Templating to create re-usable components - Templating provides a robust way to create complex web applications."
},
{
"code": null,
"e": 2826,
"s": 2783,
"text": "We will study Observables in this chapter."
},
{
"code": null,
"e": 3144,
"s": 2826,
"text": "As the name specifies, when you declare a ViewModel data/property as Observable, any data modification each time automatically gets reflected at all places the data is used. This also includes refreshing the related dependencies. KO takes care of these things and there is no need to write extra code to achieve this."
},
{
"code": null,
"e": 3233,
"s": 3144,
"text": "Using Observable, it becomes very easy to make UI and ViewModel communicate dynamically."
},
{
"code": null,
"e": 3330,
"s": 3233,
"text": "You just need to declare ViewModel property with function ko.observable() to make it Observable."
},
{
"code": null,
"e": 3371,
"s": 3330,
"text": "this.property = ko.observable('value');\n"
},
{
"code": null,
"e": 3456,
"s": 3371,
"text": "Let's take a look at the following example which demonstrates the use of Observable."
},
{
"code": null,
"e": 4253,
"s": 3456,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Observable Example</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <!-- This is called \"view\" of HTML markup that defines the appearance of UI -->\n\n <p>Enter your name: <input data-bind = \"value: yourName\" /></p>\n <p>Hi <strong data-bind = \"text: yourName\"></strong> Good Morning!!!</p>\n\n <script>\n <!-- This is called \"viewmodel\". This javascript section defines the data and behavior of UI -->\n\n function AppViewModel() {\n this.yourName = ko.observable(\"\");\n }\n\n // Activates knockout.js\n ko.applyBindings(new AppViewModel());\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4380,
"s": 4253,
"text": "The following line is for the input box. As can be seen, we have used data-bind attribute to bind yourName value to ViewModel."
},
{
"code": null,
"e": 4444,
"s": 4380,
"text": "<p>Enter your name: <input data-bind = \"value: yourName\" /> <p>"
},
{
"code": null,
"e": 4577,
"s": 4444,
"text": "The following line just prints the value of yourName. Note, that here data-bind type is the text as we are simply reading the value."
},
{
"code": null,
"e": 4650,
"s": 4577,
"text": "<p>Hi <strong data-bind = \"text: yourName\"></strong> Good Morning!!!</p>"
},
{
"code": null,
"e": 5023,
"s": 4650,
"text": "In the following line, ko.observable keeps an eye on yourName variable for any modification in data. Once there is a modification, the corresponding places also get updated with the modified value. When you run the following code, an input box will appear. As and when you update that input box, the new value will get reflected or refreshed in places wherever it is used."
},
{
"code": null,
"e": 5058,
"s": 5023,
"text": "this.yourName = ko.observable(\"\");"
},
{
"code": null,
"e": 5128,
"s": 5058,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 5182,
"s": 5128,
"text": "Save the above code in first_observable_pgm.htm file."
},
{
"code": null,
"e": 5236,
"s": 5182,
"text": "Save the above code in first_observable_pgm.htm file."
},
{
"code": null,
"e": 5270,
"s": 5236,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5304,
"s": 5270,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5382,
"s": 5304,
"text": "Enter the name as Scott and observe that the name is reflected in the output."
},
{
"code": null,
"e": 5460,
"s": 5382,
"text": "Enter the name as Scott and observe that the name is reflected in the output."
},
{
"code": null,
"e": 5478,
"s": 5460,
"text": "Enter your name: "
},
{
"code": null,
"e": 5498,
"s": 5478,
"text": "Hi Good Morning!!!"
},
{
"code": null,
"e": 5900,
"s": 5498,
"text": "Data modification can take place either from the UI or from ViewModel. Irrespective of from where the data is changed, the UI and ViewModel keeps synchronization among them. This makes it a two-way-binding mechanism. In the above example, when you change your name in the input box, ViewModel gets a new value. When you change yourName property from inside ViewModel, then the UI receives a new value."
},
{
"code": null,
"e": 5991,
"s": 5900,
"text": "Following table lists the read and write operations which can be performed on Observables."
},
{
"code": null,
"e": 5996,
"s": 5991,
"text": "Read"
},
{
"code": null,
"e": 6091,
"s": 5996,
"text": "To read value just call Observable property without parameters like: AppViewModel.yourName();"
},
{
"code": null,
"e": 6097,
"s": 6091,
"text": "Write"
},
{
"code": null,
"e": 6221,
"s": 6097,
"text": "To write/update value in Observable property, just pass the desired value in parameter like: AppViewModel.yourName('Bob');"
},
{
"code": null,
"e": 6236,
"s": 6221,
"text": "Write multiple"
},
{
"code": null,
"e": 6379,
"s": 6236,
"text": "Multiple ViewModel properties can be updated in a single row with the help of chaining-syntax like: AppViewModel.yourName('Bob').yourAge(45);"
},
{
"code": null,
"e": 6685,
"s": 6379,
"text": "Observable declaration takes care of data modifications of a single object. ObservableArray works with the collection of objects. This is a very useful feature when you are dealing with complex applications containing multiple type of values and changing their status frequently based on the user actions."
},
{
"code": null,
"e": 6751,
"s": 6685,
"text": "this.arrayName = ko.observableArray(); // It's an empty array\n"
},
{
"code": null,
"e": 6893,
"s": 6751,
"text": "Observable array only tracks which objects in it are added or removed. It does not notify if the individual object's properties are modified."
},
{
"code": null,
"e": 7038,
"s": 6893,
"text": "You can initialize your array and at the same time you can declare it as Observable by passing the initial values to the constructor as follows."
},
{
"code": null,
"e": 7093,
"s": 7038,
"text": "this.arrayName = ko.observableArray(['scott','jack']);"
},
{
"code": null,
"e": 7146,
"s": 7093,
"text": "You can access Observable array elements as follows."
},
{
"code": null,
"e": 7196,
"s": 7146,
"text": "alert('The second element is ' + arrayName()[1]);"
},
{
"code": null,
"e": 7284,
"s": 7196,
"text": "KnockoutJS has its own set of Observable array functions. They are convenient because −"
},
{
"code": null,
"e": 7322,
"s": 7284,
"text": "These functions work on all browsers."
},
{
"code": null,
"e": 7360,
"s": 7322,
"text": "These functions work on all browsers."
},
{
"code": null,
"e": 7429,
"s": 7360,
"text": "These functions will take care of dependency tracking automatically."
},
{
"code": null,
"e": 7498,
"s": 7429,
"text": "These functions will take care of dependency tracking automatically."
},
{
"code": null,
"e": 7653,
"s": 7498,
"text": "Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value')."
},
{
"code": null,
"e": 7808,
"s": 7653,
"text": "Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value')."
},
{
"code": null,
"e": 7867,
"s": 7808,
"text": "Following is the list of various Observable Array methods."
},
{
"code": null,
"e": 7907,
"s": 7867,
"text": "Inserts a new item at the end of array."
},
{
"code": null,
"e": 7960,
"s": 7907,
"text": "Removes the last item from the array and returns it."
},
{
"code": null,
"e": 8011,
"s": 7960,
"text": "Inserts a new value at the beginning of the array."
},
{
"code": null,
"e": 8065,
"s": 8011,
"text": "Removes the first item from the array and returns it."
},
{
"code": null,
"e": 8098,
"s": 8065,
"text": "Reverses the order of the array."
},
{
"code": null,
"e": 8139,
"s": 8098,
"text": "Sorts array items in an ascending order."
},
{
"code": null,
"e": 8267,
"s": 8139,
"text": "Accepts 2 parameters - start-index and end-index - removes items starting from start to end index and returns them as an array."
},
{
"code": null,
"e": 8346,
"s": 8267,
"text": "This function returns the index of the first occurrence of parameter provided."
},
{
"code": null,
"e": 8442,
"s": 8346,
"text": "This method slices out a piece of an array. Returns the items from start-index up to end-index."
},
{
"code": null,
"e": 8490,
"s": 8442,
"text": "Removes all items and returns them as an array."
},
{
"code": null,
"e": 8554,
"s": 8490,
"text": "Removes items that match the parameter and returns as an array."
},
{
"code": null,
"e": 8633,
"s": 8554,
"text": "Removes items which are satisfying the condition and returns them as an array."
},
{
"code": null,
"e": 8686,
"s": 8633,
"text": "Removes items that match with a given set of values."
},
{
"code": null,
"e": 8699,
"s": 8686,
"text": "destroyAll()"
},
{
"code": null,
"e": 8767,
"s": 8699,
"text": "Marks all items in an array with property _destroy with value true."
},
{
"code": null,
"e": 8784,
"s": 8767,
"text": "destroy('value')"
},
{
"code": null,
"e": 8890,
"s": 8784,
"text": "Searches for an item equal to the parameter and mark it with a special property _destroy with value true."
},
{
"code": null,
"e": 8927,
"s": 8890,
"text": "destroy(function(item) { condition})"
},
{
"code": null,
"e": 9030,
"s": 8927,
"text": "Finds all items which are satisfying the condition, marks them with property _destroy with true value."
},
{
"code": null,
"e": 9055,
"s": 9030,
"text": "destroy([set of values])"
},
{
"code": null,
"e": 9150,
"s": 9055,
"text": "Finds the items that match with a given set of values, marks them as _destroy with true value."
},
{
"code": null,
"e": 9260,
"s": 9150,
"text": "Note − Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on Rails' developers only."
},
{
"code": null,
"e": 9566,
"s": 9260,
"text": "When you use destroy method, the corresponding items are not really deleted from array at that moment but are made hidden by marking them with property _destroy with true value so that they can't be read by UI. Items marked as _destroy equal to true are deleted later while dealing with JSON object graph."
},
{
"code": null,
"e": 9599,
"s": 9566,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9619,
"s": 9599,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 9626,
"s": 9619,
"text": " Print"
},
{
"code": null,
"e": 9637,
"s": 9626,
"text": " Add Notes"
}
] |
How to extract an HTML tag from a String using regex in Java?
|
The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −
compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern.
compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
The Matcher class of java.util.regex package is an engine that performs match operations. To find the matched value this you need to use two methods of this class namely −
find() − This method returns true if the match operation represented by the current object is successful else, it returns false.
find() − This method returns true if the match operation represented by the current object is successful else, it returns false.
group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation.
group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation.
Therefore, to find an HTML tag from a String −
Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class.
Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class.
Match it with the desired String using the matcher method() of the Pattern class.
Match it with the desired String using the matcher method() of the Pattern class.
Verify if a occurred using the find() method of the Matcher class.
Verify if a occurred using the find() method of the Matcher class.
In the case of a match, retrieve the matched String using the group() method of the Matcher class.
In the case of a match, retrieve the matched String using the group() method of the Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractHtmlTag {
public static void main(String[] args) {
String str = "Welcome to <b>Tutorialspoint<b>";
//Creating a pattern object
Pattern pattern = Pattern.compile("<b>(\\S+)</b>");
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
}
}
Tutorialspoint
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The java.util.regex package of java provides various classes to find particular patterns in character sequences."
},
{
"code": null,
"e": 1348,
"s": 1175,
"text": "The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −"
},
{
"code": null,
"e": 1467,
"s": 1348,
"text": "compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern."
},
{
"code": null,
"e": 1586,
"s": 1467,
"text": "compile() − This method accepts a String representing a regular expression and returns an object of the class Pattern."
},
{
"code": null,
"e": 1751,
"s": 1586,
"text": "matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object."
},
{
"code": null,
"e": 1916,
"s": 1751,
"text": "matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object."
},
{
"code": null,
"e": 2088,
"s": 1916,
"text": "The Matcher class of java.util.regex package is an engine that performs match operations. To find the matched value this you need to use two methods of this class namely −"
},
{
"code": null,
"e": 2217,
"s": 2088,
"text": "find() − This method returns true if the match operation represented by the current object is successful else, it returns false."
},
{
"code": null,
"e": 2346,
"s": 2217,
"text": "find() − This method returns true if the match operation represented by the current object is successful else, it returns false."
},
{
"code": null,
"e": 2506,
"s": 2346,
"text": "group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation."
},
{
"code": null,
"e": 2666,
"s": 2506,
"text": "group() − This method accepts an integer value representing a particular group and returns the sequence captured by the specified group in the match operation."
},
{
"code": null,
"e": 2713,
"s": 2666,
"text": "Therefore, to find an HTML tag from a String −"
},
{
"code": null,
"e": 2873,
"s": 2713,
"text": "Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class."
},
{
"code": null,
"e": 3033,
"s": 2873,
"text": "Create a Pattern object by passing the regular expression representing the required HTML tag to it as a parameter to the compile() method of the Pattern class."
},
{
"code": null,
"e": 3115,
"s": 3033,
"text": "Match it with the desired String using the matcher method() of the Pattern class."
},
{
"code": null,
"e": 3197,
"s": 3115,
"text": "Match it with the desired String using the matcher method() of the Pattern class."
},
{
"code": null,
"e": 3264,
"s": 3197,
"text": "Verify if a occurred using the find() method of the Matcher class."
},
{
"code": null,
"e": 3331,
"s": 3264,
"text": "Verify if a occurred using the find() method of the Matcher class."
},
{
"code": null,
"e": 3430,
"s": 3331,
"text": "In the case of a match, retrieve the matched String using the group() method of the Matcher class."
},
{
"code": null,
"e": 3529,
"s": 3430,
"text": "In the case of a match, retrieve the matched String using the group() method of the Matcher class."
},
{
"code": null,
"e": 4034,
"s": 3529,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ExtractHtmlTag {\n public static void main(String[] args) {\n String str = \"Welcome to <b>Tutorialspoint<b>\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(\"<b>(\\\\S+)</b>\");\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(str);\n if (matcher.find()) {\n String result = matcher.group(1);\n System.out.println(result);\n }\n }\n}"
},
{
"code": null,
"e": 4049,
"s": 4034,
"text": "Tutorialspoint"
}
] |
Python - Split Strings on Prefix Occurrence - GeeksforGeeks
|
30 Sep, 2021
Given a list of Strings, perform string split on the occurrence of prefix.
Input : test_list = [“geeksforgeeks”, “best”, “geeks”, “and”], pref = “geek” Output : [[‘geeksforgeeks’, ‘best’], [‘geeks’, ‘and’]] Explanation : At occurrence of string “geeks” split is performed.
Input : test_list = [“good”, “fruits”, “goodness”, “spreading”], pref = “good” Output : [[‘good’, ‘fruits’], [‘goodness’, ‘spreading’]] Explanation : At occurrence of string “good” split is performed.
Method #1 : Using loop + startswith()
In this, we iterate each element of List, and check if new list has to be changed using startswith() by checking for prefix, and create new list if prefix is encountered.
Python3
# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + startswith() # initializing listtest_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing prefixpref = "geek" res = []for val in test_list: # checking for prefix if val.startswith(pref): # if pref found, start new list res.append([val]) else: # else append in current list res[-1].append(val) # printing resultprint("Prefix Split List : " + str(res))
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
Method #2 : Using loop + zip_longest() + startswith()
In this, we zip all the elements with their subsequent element sublist and check for prefix using startswith(), if found, result is appended.
Python3
# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + zip_longest() + startswith()from itertools import zip_longest # initializing listtest_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing prefixpref = "geek" res, temp = [], [] for x, y in zip_longest(test_list, test_list[1:]): temp.append(x) # if prefix is found, split and start new list if y and y.startswith(pref): res.append(temp) temp = []res.append(temp) # printing resultprint("Prefix Split List : " + str(res))
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]
surindertarika1234
kashishsoda
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 23976,
"s": 23901,
"text": "Given a list of Strings, perform string split on the occurrence of prefix."
},
{
"code": null,
"e": 24174,
"s": 23976,
"text": "Input : test_list = [“geeksforgeeks”, “best”, “geeks”, “and”], pref = “geek” Output : [[‘geeksforgeeks’, ‘best’], [‘geeks’, ‘and’]] Explanation : At occurrence of string “geeks” split is performed."
},
{
"code": null,
"e": 24377,
"s": 24174,
"text": "Input : test_list = [“good”, “fruits”, “goodness”, “spreading”], pref = “good” Output : [[‘good’, ‘fruits’], [‘goodness’, ‘spreading’]] Explanation : At occurrence of string “good” split is performed. "
},
{
"code": null,
"e": 24415,
"s": 24377,
"text": "Method #1 : Using loop + startswith()"
},
{
"code": null,
"e": 24586,
"s": 24415,
"text": "In this, we iterate each element of List, and check if new list has to be changed using startswith() by checking for prefix, and create new list if prefix is encountered."
},
{
"code": null,
"e": 24594,
"s": 24586,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + startswith() # initializing listtest_list = [\"geeksforgeeks\", \"best\", \"geeks\", \"and\", \"geeks\", \"love\", \"CS\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing prefixpref = \"geek\" res = []for val in test_list: # checking for prefix if val.startswith(pref): # if pref found, start new list res.append([val]) else: # else append in current list res[-1].append(val) # printing resultprint(\"Prefix Split List : \" + str(res))",
"e": 25205,
"s": 24594,
"text": null
},
{
"code": null,
"e": 25384,
"s": 25205,
"text": "The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']\nPrefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]"
},
{
"code": null,
"e": 25438,
"s": 25384,
"text": "Method #2 : Using loop + zip_longest() + startswith()"
},
{
"code": null,
"e": 25581,
"s": 25438,
"text": "In this, we zip all the elements with their subsequent element sublist and check for prefix using startswith(), if found, result is appended. "
},
{
"code": null,
"e": 25589,
"s": 25581,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split Strings on Prefix Occurrence# Using loop + zip_longest() + startswith()from itertools import zip_longest # initializing listtest_list = [\"geeksforgeeks\", \"best\", \"geeks\", \"and\", \"geeks\", \"love\", \"CS\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing prefixpref = \"geek\" res, temp = [], [] for x, y in zip_longest(test_list, test_list[1:]): temp.append(x) # if prefix is found, split and start new list if y and y.startswith(pref): res.append(temp) temp = []res.append(temp) # printing resultprint(\"Prefix Split List : \" + str(res))",
"e": 26238,
"s": 25589,
"text": null
},
{
"code": null,
"e": 26417,
"s": 26238,
"text": "The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']\nPrefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]"
},
{
"code": null,
"e": 26436,
"s": 26417,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26448,
"s": 26436,
"text": "kashishsoda"
},
{
"code": null,
"e": 26469,
"s": 26448,
"text": "Python list-programs"
},
{
"code": null,
"e": 26476,
"s": 26469,
"text": "Python"
},
{
"code": null,
"e": 26492,
"s": 26476,
"text": "Python Programs"
},
{
"code": null,
"e": 26590,
"s": 26492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26599,
"s": 26590,
"text": "Comments"
},
{
"code": null,
"e": 26612,
"s": 26599,
"text": "Old Comments"
},
{
"code": null,
"e": 26644,
"s": 26612,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26700,
"s": 26644,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26742,
"s": 26700,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26784,
"s": 26742,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26820,
"s": 26784,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26842,
"s": 26820,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26881,
"s": 26842,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26927,
"s": 26881,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26965,
"s": 26927,
"text": "Python | Convert a list to dictionary"
}
] |
Analysis of Duterte’s Speeches using NLP | by Daniel Del Rio | Towards Data Science
|
Given the present situation of the COVID-19 across different countries, the urgency for their governments to step up and address the pandemic has elevated even further. The story isn’t any different here in the Philippines, as the frequency of President Rodrigo Duterte’s press conferences addressed to the Filipino people has risen. This inspired me to work on a personal project that will analyze his speeches throughout the years using Natural Language Processing (NLP).
Of course, before I can analyze his speeches, I need to actually collect them first. This is Part 1 of the Duterte Speech Analysis, which will focus on scraping Duterte’s speeches. The succeeding articles of this series will then be centered on analyzing them using NLP. For the code I made, check out my GitHub repository — though I admit my code’s kind of messy here — and leave comments or suggestions if you have any. I’ll also eventually update my README with instructions on how to run the Python programs.
Luckily for me, the country’s Presidential Communications Operations Office (PCOO) publishes his speeches in their website, at least up until a certain point (the page shows that it has 31 pages but if you navigate beyond a certain page number, it returns a “page can’t be found” error). Hence, the speeches I gathered were only from 2020 until 2018.
For the scraping of the speeches, I primarily used theBeautifulSoup4 and requests Python libraries, while also using pandas for structuring the dataset, python-dotenv for the environment variables, and a bunch of libraries for extracting texts from PDFs.
Initially, when I tried using the requests library to make a GET request to the PCOO website, I kept getting a connection error for some reason. Upon further research, I found out that it’s because some websites, including PCOO’s, generally dislike robots crawling all over them. You can see this by going to their robots.txt, showing the following settings aimed for disallowing robots.
User-Agent: *Disallow:
Hence, I had to perform several extra steps as a measure to overcome the settings against robots and as a precaution in order to prevent my IP address from being blacklisted. Firstly, I had to disguise my robot program as a human by attaching a user agent to my every request, which I stored in my .env file (hence why I installed python-dotenv). Secondly, it would be way too obvious if one IP address made GET requests to a website at a rapid-fire pace, so I spread out each request by 15 seconds using time.sleep to make it look more human. Admittedly, this increased the scraping time by a lot, but later I will explain how I was able to vastly speed up the process.
The above snippet shows part of the main program found in the 01_scraper.py file, which scrapes the speeches per page of the website. Each page contains 20 speeches, each of which I refer to as row in my program. Each speech takes you to the speech detail page (example) containing the audio, full transcript, and possibly the video of the press conference. The full transcript redirects you to a PDF of the transcript of the speech (example).
I made a function called extract_page in my scraper_functions.py that processes each row using the above procedure and returns a dictionary containing the title, date of speech, and the extracted text.
The next question then is, how do I extract the text from the PDFs?
To reduce scraping time in case I wanted to try more PDF libraries, I saved the PDFs in my repository. This way, I didn’t have to scrape through the PCOO website again. After that, I found four Python libraries for extracting text from PDFs:
PyPDF2slate3ktikaPDFPlumber
PyPDF2
slate3k
tika
PDFPlumber
Initially, I used PyPDF2, but for some speeches it was only able to extract empty new lines, so it would end up with something like \n\n\n\n\n\n\n\n. As a result, I made a function for to check whether the extracted text returned a string with no words using regex. If the function returned True, then I use slate3k to extract for that speech instead. Still, the library sometimes had faulty results, such as totally missing parts of the speech and weirdly spacing out each letter of the text for some speeches (l i k e t h i s). Nevertheless, I compiled all the results using PyPDF2 and slate3k into one csv.
Next, I tried out tika because I was too frustrated with the previous results while I was trying to analyze, and it worked beautifully. So beautifully in fact that I didn’t get to try out PDFPlumber (so if you’ve used it before, do let me know whether it’s as functional!). No errors were caught while extracting everything, so it was pretty much a smooth process using that library. I’ve decided that I’ll use the tika results instead of the other three packages for my analysis.
I mentioned above that there were two stages of scraping for each speech: the speech detail page and the PDF transcript page, amounting to more than 30 seconds of scraping per speech. Given that there are 20 speeches per page, it takes us more than 10 minutes (plus an additional 15 seconds for scraping the page itself) to extract all the speeches in one page. There were about 21 valid pages, so overall it should theoretically take 210 minutes or about 3.5 hours to extract all of them. However, in reality it took me about a week to finish the scraping because of the numerous errors that popped up while using PyPDF2 and slate3k.
This led me to explore multiprocessing to speed up the whole process using tika instead as my PDF extractor, and it worked wonders.
Since I wasn’t able to save the PDFs locally during my first trial run, I had to restart the whole process of scraping. But with multiprocessing, I could have multiple workers process the same set of data (in this case, the 20 speeches per page) concurrently instead of having to process each speech sequentially.
Using the Pool object representing the pool of worker processes, I was able to map the data (the 20 rows of data per page) to the worker processes, and the workers ran the extract_page function concurrently. After all the workers are done, the list of 20 dictionaries returned by the function was appended to the working pandas DataFrame. I also included a text file for logging each speech as I processed them (which I had also done for the first trial run).
I compared the total time it took to scrape one whole page for the first and second trial runs using my scrape_logs.txt, and the difference was apparent. For the first trial run, it took 13–20 minutes to complete one whole page, while it took only 4–5 minutes for my second trial run involving multiprocessing. This is also thanks to the smooth sailing of the tika library, where I encountered no errors in extracting the text (though I did encounter this weird recursion limit error related to the multiprocessing, which I remedied by adding the sys.recursionlimit(10000)). Overall, the multiprocessing trial run lasted only about 1.5 hrs!
I was also satisfied with the PDF extraction itself, seeing that there were only negligible errors in the texts obtained using tika. Hence, I opted not to proceed with the PDFPlumber anymore.
Overall, I successfully scraped the PCOO website in order to collect Duterte’s speeches and to compile them into one csv file, further speeding up the whole process by incorporating multiprocessing.
For Part 2 (and possibly Part 3), I will attempt to analyze this data that I gathered using NLP tools such as NLTK and TF-IDF/N-gram. Again, please feel free to go through my Github repository and leave comments or suggestions below if you have any! I will very much appreciate it.
|
[
{
"code": null,
"e": 646,
"s": 172,
"text": "Given the present situation of the COVID-19 across different countries, the urgency for their governments to step up and address the pandemic has elevated even further. The story isn’t any different here in the Philippines, as the frequency of President Rodrigo Duterte’s press conferences addressed to the Filipino people has risen. This inspired me to work on a personal project that will analyze his speeches throughout the years using Natural Language Processing (NLP)."
},
{
"code": null,
"e": 1159,
"s": 646,
"text": "Of course, before I can analyze his speeches, I need to actually collect them first. This is Part 1 of the Duterte Speech Analysis, which will focus on scraping Duterte’s speeches. The succeeding articles of this series will then be centered on analyzing them using NLP. For the code I made, check out my GitHub repository — though I admit my code’s kind of messy here — and leave comments or suggestions if you have any. I’ll also eventually update my README with instructions on how to run the Python programs."
},
{
"code": null,
"e": 1510,
"s": 1159,
"text": "Luckily for me, the country’s Presidential Communications Operations Office (PCOO) publishes his speeches in their website, at least up until a certain point (the page shows that it has 31 pages but if you navigate beyond a certain page number, it returns a “page can’t be found” error). Hence, the speeches I gathered were only from 2020 until 2018."
},
{
"code": null,
"e": 1765,
"s": 1510,
"text": "For the scraping of the speeches, I primarily used theBeautifulSoup4 and requests Python libraries, while also using pandas for structuring the dataset, python-dotenv for the environment variables, and a bunch of libraries for extracting texts from PDFs."
},
{
"code": null,
"e": 2153,
"s": 1765,
"text": "Initially, when I tried using the requests library to make a GET request to the PCOO website, I kept getting a connection error for some reason. Upon further research, I found out that it’s because some websites, including PCOO’s, generally dislike robots crawling all over them. You can see this by going to their robots.txt, showing the following settings aimed for disallowing robots."
},
{
"code": null,
"e": 2176,
"s": 2153,
"text": "User-Agent: *Disallow:"
},
{
"code": null,
"e": 2847,
"s": 2176,
"text": "Hence, I had to perform several extra steps as a measure to overcome the settings against robots and as a precaution in order to prevent my IP address from being blacklisted. Firstly, I had to disguise my robot program as a human by attaching a user agent to my every request, which I stored in my .env file (hence why I installed python-dotenv). Secondly, it would be way too obvious if one IP address made GET requests to a website at a rapid-fire pace, so I spread out each request by 15 seconds using time.sleep to make it look more human. Admittedly, this increased the scraping time by a lot, but later I will explain how I was able to vastly speed up the process."
},
{
"code": null,
"e": 3291,
"s": 2847,
"text": "The above snippet shows part of the main program found in the 01_scraper.py file, which scrapes the speeches per page of the website. Each page contains 20 speeches, each of which I refer to as row in my program. Each speech takes you to the speech detail page (example) containing the audio, full transcript, and possibly the video of the press conference. The full transcript redirects you to a PDF of the transcript of the speech (example)."
},
{
"code": null,
"e": 3493,
"s": 3291,
"text": "I made a function called extract_page in my scraper_functions.py that processes each row using the above procedure and returns a dictionary containing the title, date of speech, and the extracted text."
},
{
"code": null,
"e": 3561,
"s": 3493,
"text": "The next question then is, how do I extract the text from the PDFs?"
},
{
"code": null,
"e": 3803,
"s": 3561,
"text": "To reduce scraping time in case I wanted to try more PDF libraries, I saved the PDFs in my repository. This way, I didn’t have to scrape through the PCOO website again. After that, I found four Python libraries for extracting text from PDFs:"
},
{
"code": null,
"e": 3831,
"s": 3803,
"text": "PyPDF2slate3ktikaPDFPlumber"
},
{
"code": null,
"e": 3838,
"s": 3831,
"text": "PyPDF2"
},
{
"code": null,
"e": 3846,
"s": 3838,
"text": "slate3k"
},
{
"code": null,
"e": 3851,
"s": 3846,
"text": "tika"
},
{
"code": null,
"e": 3862,
"s": 3851,
"text": "PDFPlumber"
},
{
"code": null,
"e": 4472,
"s": 3862,
"text": "Initially, I used PyPDF2, but for some speeches it was only able to extract empty new lines, so it would end up with something like \\n\\n\\n\\n\\n\\n\\n\\n. As a result, I made a function for to check whether the extracted text returned a string with no words using regex. If the function returned True, then I use slate3k to extract for that speech instead. Still, the library sometimes had faulty results, such as totally missing parts of the speech and weirdly spacing out each letter of the text for some speeches (l i k e t h i s). Nevertheless, I compiled all the results using PyPDF2 and slate3k into one csv."
},
{
"code": null,
"e": 4953,
"s": 4472,
"text": "Next, I tried out tika because I was too frustrated with the previous results while I was trying to analyze, and it worked beautifully. So beautifully in fact that I didn’t get to try out PDFPlumber (so if you’ve used it before, do let me know whether it’s as functional!). No errors were caught while extracting everything, so it was pretty much a smooth process using that library. I’ve decided that I’ll use the tika results instead of the other three packages for my analysis."
},
{
"code": null,
"e": 5588,
"s": 4953,
"text": "I mentioned above that there were two stages of scraping for each speech: the speech detail page and the PDF transcript page, amounting to more than 30 seconds of scraping per speech. Given that there are 20 speeches per page, it takes us more than 10 minutes (plus an additional 15 seconds for scraping the page itself) to extract all the speeches in one page. There were about 21 valid pages, so overall it should theoretically take 210 minutes or about 3.5 hours to extract all of them. However, in reality it took me about a week to finish the scraping because of the numerous errors that popped up while using PyPDF2 and slate3k."
},
{
"code": null,
"e": 5720,
"s": 5588,
"text": "This led me to explore multiprocessing to speed up the whole process using tika instead as my PDF extractor, and it worked wonders."
},
{
"code": null,
"e": 6034,
"s": 5720,
"text": "Since I wasn’t able to save the PDFs locally during my first trial run, I had to restart the whole process of scraping. But with multiprocessing, I could have multiple workers process the same set of data (in this case, the 20 speeches per page) concurrently instead of having to process each speech sequentially."
},
{
"code": null,
"e": 6494,
"s": 6034,
"text": "Using the Pool object representing the pool of worker processes, I was able to map the data (the 20 rows of data per page) to the worker processes, and the workers ran the extract_page function concurrently. After all the workers are done, the list of 20 dictionaries returned by the function was appended to the working pandas DataFrame. I also included a text file for logging each speech as I processed them (which I had also done for the first trial run)."
},
{
"code": null,
"e": 7135,
"s": 6494,
"text": "I compared the total time it took to scrape one whole page for the first and second trial runs using my scrape_logs.txt, and the difference was apparent. For the first trial run, it took 13–20 minutes to complete one whole page, while it took only 4–5 minutes for my second trial run involving multiprocessing. This is also thanks to the smooth sailing of the tika library, where I encountered no errors in extracting the text (though I did encounter this weird recursion limit error related to the multiprocessing, which I remedied by adding the sys.recursionlimit(10000)). Overall, the multiprocessing trial run lasted only about 1.5 hrs!"
},
{
"code": null,
"e": 7327,
"s": 7135,
"text": "I was also satisfied with the PDF extraction itself, seeing that there were only negligible errors in the texts obtained using tika. Hence, I opted not to proceed with the PDFPlumber anymore."
},
{
"code": null,
"e": 7526,
"s": 7327,
"text": "Overall, I successfully scraped the PCOO website in order to collect Duterte’s speeches and to compile them into one csv file, further speeding up the whole process by incorporating multiprocessing."
}
] |
An Introduction to Optical Character Recognition for Beginners | by Renu Khandelwal | Towards Data Science
|
In this article, you will learn
What is Optical Character Recognition(OCR)?
Usage of OCR
Simple code to read text from PDF files and images
You have scanned copies of several documents like certificates of courses candidates have taken. The course certificate could be a PDF or a JPEG or a PNG file. How can you extract vital information like the name of the candidate, name of the course completed, and the date when the course was taken?
OCR is a technology to convert handwritten, typed, scanned text, or text inside images to machine-readable text.
You can use OCR on any image files containing text or a PDF document or any scanned document, printed document, or handwritten document that is legible to extract text.
Some of the common usages of OCR are
Create automated workflows by digitizing PDF documents across different business units
Eliminating manual data entry by digitizing printed documents like reading passports, invoices, bank statements, etc.
Create secure access to sensitive information by digitizing Id cards, credit cards, etc.
Digitizing printed books like the Gutenberg project
Here you will read the contents of a PDF file. You need to install pypdf2 library which is built on python for handling different pdf functionalities like
Extracting document information like title, author, etc
Splitting documents page by page
Encrypting and decrypting PDF files
!pip install pypdf2
You can download a sample W4 form as a PDF
Importing the library
import PyPDF2
Extract the number of pages and PDF file information
Open the PDF file to be read in binary mode using mode as ‘rb’. Pass the pdfFileObj to the PdfFileReader() to read the file stream. numPages will get the total number of pages in the PDF file. Use getDocumentInfo() to extract the PDF file’s information like author, creator, producer, subject, title in a dictionary
filename=r'\PDFfiles\W4.pdf'pdfFileObj = open(filename,'rb')pdfReader = PyPDF2.PdfFileReader(pdfFileObj)num_pages = pdfReader.numPagesinfo=pdfReader.getDocumentInfo()print("No. of Pages: ", num_pages)print("Titel: ", info.title)print("Author: ",info.author)print("Subject: ",info.subject)print("Creator: ",info.creator)print("Producer: ",info.producer)
Retrieve the text from all the pages in the PDF file
Iterate through all the pages in the PDF file and then use getPage(), which will retrieve a page by a number from the PDF file. You can now extract the text from PDF file using extractText(). In the end, close the file using close()
count = 0text = “”#The while loop will read each page.while count < num_pages: pageObj = pdfReader.getPage(count) count +=1 text += pageObj.extractText() print(“Page Number”,count) print(“Content”,text)pdfFileObj.close()
A word of caution: Text extracted using extractText() is not always in the right order, and the spacing also can be slightly different.
You will use pytesseract, which a python wrapper for Google’s tesseract for optical character recognition (OCR), to read the text embedded in images.
You will need to understand some of the configuration options that can be applied using pytesseract
Page segmentation modes(psm)
OCR engine modes(oem)
Language(l)
Page Segmentation Method(psm)
psm defines how tesseract splits or segments image into lines of text or words
options for page segmentation modes(psm):
0: Orientation and script detection (OSD) only. 1: Automatic page segmentation with OSD. 2: Automatic page segmentation, but no OSD, or OCR.3: Fully automatic page segmentation, but no OSD. (Default)4: Assume a single column of text of variable sizes. 5: Assume a single uniform block of vertically aligned text. 6: Assume a single uniform block of text. 7: Treat the image as a single text line. 8: Treat the image as a single word. 9: Treat the image as a single word in a circle. 10: Treat the image as a single character. 11: Sparse text. Find as much text as possible in no particular order. 12: Sparse text with OSD. 13: Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific.
OCR Engine Mode(oem)
Tesseract has different engine modes for speed and performance
0: Legacy engine only.1: Neural nets LSTM engine only.2: Legacy + LSTM engines.3: Default, based on what is available.
Language(l)
Pytessercat supports multiple languages, and you can specify the languages you intend to work with while installing pytesseract, and it will download the language package. By default, eng is the default language
Importing required libraries
import pytesseractimport cv2
Read the image file using openCV. Applying configuration option for pytesseract to read the text from images. You can try different options for psm and oem and checkout the difference sin output
image_Filename=r'\Apparel_tag.jpg'# Read the file using opencv and show the imageimg=cv2.imread(image_Filename)cv2.imshow("Apparel Tag", img)cv2.waitKey(0)#set the configuration for redaing text from image using pytesseractcustom_config = r'--oem 1 --psm 8 -l eng'text=pytesseract.image_to_string(img, config=custom_config)print(text)
Try a different combination of configurations for pytesseract to get the best results for your use case
The text should not be skewed, leave some white space around the text for better results and ensure better illumination of the image to remove dark borders
300- 600 DPI at a minimum works great
The font size of 12 pt. or more gives better results
Applying different pre-processing techniques like binarizing, de-noising the image, rotating the image to deskew it, increase the sharpness of the image, etc.
OCR results depend on the input data quality. A clean segmentation of the text and no noise in the background gives better results. In the real world, this is not always possible, so we need to apply multiple pre-processing techniques for OCR to give better results.
|
[
{
"code": null,
"e": 204,
"s": 172,
"text": "In this article, you will learn"
},
{
"code": null,
"e": 248,
"s": 204,
"text": "What is Optical Character Recognition(OCR)?"
},
{
"code": null,
"e": 261,
"s": 248,
"text": "Usage of OCR"
},
{
"code": null,
"e": 312,
"s": 261,
"text": "Simple code to read text from PDF files and images"
},
{
"code": null,
"e": 612,
"s": 312,
"text": "You have scanned copies of several documents like certificates of courses candidates have taken. The course certificate could be a PDF or a JPEG or a PNG file. How can you extract vital information like the name of the candidate, name of the course completed, and the date when the course was taken?"
},
{
"code": null,
"e": 725,
"s": 612,
"text": "OCR is a technology to convert handwritten, typed, scanned text, or text inside images to machine-readable text."
},
{
"code": null,
"e": 894,
"s": 725,
"text": "You can use OCR on any image files containing text or a PDF document or any scanned document, printed document, or handwritten document that is legible to extract text."
},
{
"code": null,
"e": 931,
"s": 894,
"text": "Some of the common usages of OCR are"
},
{
"code": null,
"e": 1018,
"s": 931,
"text": "Create automated workflows by digitizing PDF documents across different business units"
},
{
"code": null,
"e": 1136,
"s": 1018,
"text": "Eliminating manual data entry by digitizing printed documents like reading passports, invoices, bank statements, etc."
},
{
"code": null,
"e": 1225,
"s": 1136,
"text": "Create secure access to sensitive information by digitizing Id cards, credit cards, etc."
},
{
"code": null,
"e": 1277,
"s": 1225,
"text": "Digitizing printed books like the Gutenberg project"
},
{
"code": null,
"e": 1432,
"s": 1277,
"text": "Here you will read the contents of a PDF file. You need to install pypdf2 library which is built on python for handling different pdf functionalities like"
},
{
"code": null,
"e": 1488,
"s": 1432,
"text": "Extracting document information like title, author, etc"
},
{
"code": null,
"e": 1521,
"s": 1488,
"text": "Splitting documents page by page"
},
{
"code": null,
"e": 1557,
"s": 1521,
"text": "Encrypting and decrypting PDF files"
},
{
"code": null,
"e": 1577,
"s": 1557,
"text": "!pip install pypdf2"
},
{
"code": null,
"e": 1620,
"s": 1577,
"text": "You can download a sample W4 form as a PDF"
},
{
"code": null,
"e": 1642,
"s": 1620,
"text": "Importing the library"
},
{
"code": null,
"e": 1656,
"s": 1642,
"text": "import PyPDF2"
},
{
"code": null,
"e": 1709,
"s": 1656,
"text": "Extract the number of pages and PDF file information"
},
{
"code": null,
"e": 2025,
"s": 1709,
"text": "Open the PDF file to be read in binary mode using mode as ‘rb’. Pass the pdfFileObj to the PdfFileReader() to read the file stream. numPages will get the total number of pages in the PDF file. Use getDocumentInfo() to extract the PDF file’s information like author, creator, producer, subject, title in a dictionary"
},
{
"code": null,
"e": 2378,
"s": 2025,
"text": "filename=r'\\PDFfiles\\W4.pdf'pdfFileObj = open(filename,'rb')pdfReader = PyPDF2.PdfFileReader(pdfFileObj)num_pages = pdfReader.numPagesinfo=pdfReader.getDocumentInfo()print(\"No. of Pages: \", num_pages)print(\"Titel: \", info.title)print(\"Author: \",info.author)print(\"Subject: \",info.subject)print(\"Creator: \",info.creator)print(\"Producer: \",info.producer)"
},
{
"code": null,
"e": 2431,
"s": 2378,
"text": "Retrieve the text from all the pages in the PDF file"
},
{
"code": null,
"e": 2664,
"s": 2431,
"text": "Iterate through all the pages in the PDF file and then use getPage(), which will retrieve a page by a number from the PDF file. You can now extract the text from PDF file using extractText(). In the end, close the file using close()"
},
{
"code": null,
"e": 2885,
"s": 2664,
"text": "count = 0text = “”#The while loop will read each page.while count < num_pages: pageObj = pdfReader.getPage(count) count +=1 text += pageObj.extractText() print(“Page Number”,count) print(“Content”,text)pdfFileObj.close()"
},
{
"code": null,
"e": 3021,
"s": 2885,
"text": "A word of caution: Text extracted using extractText() is not always in the right order, and the spacing also can be slightly different."
},
{
"code": null,
"e": 3171,
"s": 3021,
"text": "You will use pytesseract, which a python wrapper for Google’s tesseract for optical character recognition (OCR), to read the text embedded in images."
},
{
"code": null,
"e": 3271,
"s": 3171,
"text": "You will need to understand some of the configuration options that can be applied using pytesseract"
},
{
"code": null,
"e": 3300,
"s": 3271,
"text": "Page segmentation modes(psm)"
},
{
"code": null,
"e": 3322,
"s": 3300,
"text": "OCR engine modes(oem)"
},
{
"code": null,
"e": 3334,
"s": 3322,
"text": "Language(l)"
},
{
"code": null,
"e": 3364,
"s": 3334,
"text": "Page Segmentation Method(psm)"
},
{
"code": null,
"e": 3443,
"s": 3364,
"text": "psm defines how tesseract splits or segments image into lines of text or words"
},
{
"code": null,
"e": 3485,
"s": 3443,
"text": "options for page segmentation modes(psm):"
},
{
"code": null,
"e": 4206,
"s": 3485,
"text": "0: Orientation and script detection (OSD) only. 1: Automatic page segmentation with OSD. 2: Automatic page segmentation, but no OSD, or OCR.3: Fully automatic page segmentation, but no OSD. (Default)4: Assume a single column of text of variable sizes. 5: Assume a single uniform block of vertically aligned text. 6: Assume a single uniform block of text. 7: Treat the image as a single text line. 8: Treat the image as a single word. 9: Treat the image as a single word in a circle. 10: Treat the image as a single character. 11: Sparse text. Find as much text as possible in no particular order. 12: Sparse text with OSD. 13: Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific."
},
{
"code": null,
"e": 4227,
"s": 4206,
"text": "OCR Engine Mode(oem)"
},
{
"code": null,
"e": 4290,
"s": 4227,
"text": "Tesseract has different engine modes for speed and performance"
},
{
"code": null,
"e": 4409,
"s": 4290,
"text": "0: Legacy engine only.1: Neural nets LSTM engine only.2: Legacy + LSTM engines.3: Default, based on what is available."
},
{
"code": null,
"e": 4421,
"s": 4409,
"text": "Language(l)"
},
{
"code": null,
"e": 4633,
"s": 4421,
"text": "Pytessercat supports multiple languages, and you can specify the languages you intend to work with while installing pytesseract, and it will download the language package. By default, eng is the default language"
},
{
"code": null,
"e": 4662,
"s": 4633,
"text": "Importing required libraries"
},
{
"code": null,
"e": 4691,
"s": 4662,
"text": "import pytesseractimport cv2"
},
{
"code": null,
"e": 4886,
"s": 4691,
"text": "Read the image file using openCV. Applying configuration option for pytesseract to read the text from images. You can try different options for psm and oem and checkout the difference sin output"
},
{
"code": null,
"e": 5222,
"s": 4886,
"text": "image_Filename=r'\\Apparel_tag.jpg'# Read the file using opencv and show the imageimg=cv2.imread(image_Filename)cv2.imshow(\"Apparel Tag\", img)cv2.waitKey(0)#set the configuration for redaing text from image using pytesseractcustom_config = r'--oem 1 --psm 8 -l eng'text=pytesseract.image_to_string(img, config=custom_config)print(text)"
},
{
"code": null,
"e": 5326,
"s": 5222,
"text": "Try a different combination of configurations for pytesseract to get the best results for your use case"
},
{
"code": null,
"e": 5482,
"s": 5326,
"text": "The text should not be skewed, leave some white space around the text for better results and ensure better illumination of the image to remove dark borders"
},
{
"code": null,
"e": 5520,
"s": 5482,
"text": "300- 600 DPI at a minimum works great"
},
{
"code": null,
"e": 5573,
"s": 5520,
"text": "The font size of 12 pt. or more gives better results"
},
{
"code": null,
"e": 5732,
"s": 5573,
"text": "Applying different pre-processing techniques like binarizing, de-noising the image, rotating the image to deskew it, increase the sharpness of the image, etc."
}
] |
Natural Language Processing with PySpark and Spark-NLP | by Allison Stafford | Towards Data Science
|
The question: what words (from complaints) are distinctly Equifax-y?
Today we’re diving deeper into the US Consumer Financial Protection Bureau’s Financial Services Consumer Complaint database to look at the text of the complaints filed against companies. The question: what words (from complaints) are distinctly Equifax-y? We’re going to be looking at text cleaning, tokenization, and lemming with Spark-NLP, counting with PySpark, and tf-idf (term frequency-inverse document frequency) analysis.
I used John Snow LABS’ Spark-NLP library. You can learn more from them, or wikipedia (probably also written by them, but in a different style).
John Snow LABS provides a couple of different quick start guides — here and here — that I found useful together.
If you haven’t already installed PySpark (note: PySpark version 2.4.4 is the only supported version):
$ conda install pyspark==2.4.4$ conda install -c johnsnowlabs spark-nlp
If you already have PySpark, make sure to install spark-nlp in the same channel as PySpark (you can check the channel from conda list). In my case, PySpark is installed on my conda-forge channel, so I used
$ conda install -c johnsnowlabs spark-nlp — channel conda-forge
I already had PySpark installed and set up for use with Jupyter notebooks, but if you don’t, you may need to set some additional environment variables in the terminal (as mentioned in the second quick start guide, but not the first, so ...)
$ export SPARK_HOME=/path/to/your/spark/folder$ export PYSPARK_PYTHON=python3$ export PYSPARK_DRIVER_PYTHON=jupyter$ export PYSPARK_DRIVER_PYTHON_OPTS=notebook
If you are looking to play around with pre-installed data sets, and therefore don’t need to access the spark session, you can get started with the following two lines:
import sparknlpsparknlp.start()
In my case, I need the SparkSession to load my data from the parquet file, so I’ll add .config(“spark.jars.packages”, “com.johnsnowlabs.nlp:spark-nlp_2.11:2.3.5”) to my SparkSession.builder
from pyspark.sql import SparkSession# start spark session configured for spark nlpspark = SparkSession.builder \ .master('local[*]') \ .appName('Spark NLP') \ .config('spark.jars.packages', 'com.johnsnowlabs.nlp:spark-nlp_2.11:2.3.5') \ .getOrCreate()
That’s it! You’re up and going!
Spark-NLP does not come with a built-in stop words dictionary, so I chose to use the NLTK English Language stop words, as well as the ‘xxxx’ redacting string found in my data set.
from nltk.corpus import stopwordseng_stopwords = stopwords.words('english')eng_stopwords.append('xxxx')
To start, import your tools:
from sparknlp.base import Finisher, DocumentAssemblerfrom sparknlp.annotator import (Tokenizer, Normalizer, LemmatizerModel, StopWordsCleaner)from pyspark.ml import Pipeline
Most projects are going to need DocumentAssembler to convert the text into a Spark-NLP annotator-ready form at the beginning, and Finisher to convert back to human-readable form at the end. You can select the annotators you need from the annotator docs.
Before you set up the pipeline, we need to initialize the annotators with the proper inputs. We’ll use the typical Spark ML format of .setInputCols(list of columns) and .setOutputCol(output column name), along with other functions specific to the annotator (see docs). Each output column will be the input column for the following annotator.
documentAssembler = DocumentAssembler() \ .setInputCol('consumer_complaint_narrative') \ .setOutputCol('document')tokenizer = Tokenizer() \ .setInputCols(['document']) \ .setOutputCol('token')# note normalizer defaults to changing all words to lowercase.# Use .setLowercase(False) to maintain input case.normalizer = Normalizer() \ .setInputCols(['token']) \ .setOutputCol('normalized') \ .setLowercase(True)# note that lemmatizer needs a dictionary. So I used the pre-trained# model (note that it defaults to english)lemmatizer = LemmatizerModel.pretrained() \ .setInputCols(['normalized']) \ .setOutputCol('lemma')stopwords_cleaner = StopWordsCleaner() \ .setInputCols(['lemma']) \ .setOutputCol('clean_lemma') \ .setCaseSensitive(False) \ .setStopWords(eng_stopwords)# finisher converts tokens to human-readable outputfinisher = Finisher() \ .setInputCols(['clean_lemma']) \ .setCleanAnnotations(False)
Now we’re ready to define the pipeline:
pipeline = Pipeline() \ .setStages([ documentAssembler, tokenizer, normalizer, lemmatizer, stopwords_cleaner, finisher ])
I import and select my data, and then use pipeline.fit(data).transform(data). For example:
# import datadf = spark.read.load('../data/consumer_complaints.parquet', inferSchema='true', header='true')# select equifax text data as testdata = df.filter((df['company'] == 'EQUIFAX, INC.') & (df['consumer_complaint_narrative'].isNull() == False))data = data.select('consumer_complaint_narrative')# transform text with the pipelineequifax = pipeline.fit(data).transform(data)
This returns a DataFrame with the added columns specified in the pipeline’s annotators. So equifax.columns returns:
['consumer_complaint_narrative', 'document', 'token', 'normalized', 'lemma', 'clean_lemma', 'finished_clean_lemma']
When we look more closely at the output of the finisher, in this case the “finished_clean_lemma”, we see that each record is a list of words — eg. [address, never, ...], [pay, satisfied, ...].
In order to get each word on the same level, I used the pyspark.sql explode function.
from pyspark.sql.functions import explode, colequifax_words = equifax_words.withColumn('exploded_text', explode(col('finished_clean_lemma')))
Now the text is ready to .groupby().count() to get the count for each word.
I then converted the result to pandas and used a dictionary comprehension to convert the table into a dictionary (this may not be the most elegant strategy).
counts = equifax_words.groupby('exploded_text').count()counts_pd = counts.toPandas()equifax_dict = {counts_pd.loc[i, 'exploded_text']: counts_pd.loc[i, 'count'] for i in range(counts_pd.shape[0])}
Full disclosure: even using Spark running on all four cores, doing this for the top 20 complaint earners took a significant amount of time — this is a lot of computation!
Now that I have the text from each company’s complaints count vectorized (aka converted into a dictionary of {word1: count1, word2: count2...}), I am ready to get the tf-idf for each word in each company’s word set.
Helper functions:
def term_frequency(BoW_dict): tot_words = sum(BoW_dict.values()) freq_dict = {word: BoW_dict[word]/tot_words for word in BoW_dict.keys()} return freq_dictfrom math import logdef inverse_document_frequency(list_of_dicts): tot_docs = len(list_of_dicts) words = set([w for w_dict in list_of_dicts for w in w_dict.keys()]) idf_dict = {word: log(float(tot_docs)/ (1.0 + sum([1 for w_dict in list_of_dicts if word in w_dict.keys()]))) for word in words} return idf_dictdef tf_idf(list_of_dicts): words = set([w for w_dict in list_of_dicts for w in w_dict.keys()]) tf_idf_dicts = [] idfs = inverse_document_frequency(list_of_dicts) for i, w_dict in enumerate(list_of_dicts): w_dict.update({word: 0 for word in words if word not in w_dict.keys()}) tf = term_frequency(w_dict) tf_idf_dicts.append({word: tf[word]*idfs[word] for word in words}) return tf_idf_dicts
Putting it together:
list_of_word_dicts = [company_complaint_word_counts_dict[company] for company in companies]tf_idf_by_company_list = tf_idf(list_of_word_dicts)tf_idf_by_company_dict = {c: tf_dict for c, tf_dict in zip(companies, tf_idf_by_company_list)}
To find the words that set each company apart, I found the words with the top tf-idf scores for my companies of interest.
Unfortunately, this revealed that I hadn’t done enough to clean my data. All of the highest tf-idf score words were typos or sets of words smashed together (eg. ‘tobe’, ‘calledthem’, etc.). Sometimes 1000 character strings without spaces. So here, I added a filter based on the nltk.corpus words.words() list. Unfortunately tobe is actually a word, so it still shows up in some of the top results. Given the issue with missing spaces in the dataset, I doubt that people were talking about “an outer garment traditionally word in some parts of north and central Africa, consisting of a length of cloth that is sewn into a long loose skirt or is draped around the body and fastened over one shoulder” (Collins Dictionary).
Let’s take a look at some of the top tf-idf scoring words for our top ten companies:
Equifax: reseller, accuser, reinsertion, certifiably, certifiable, runner
Experian: reseller, accuser, certifiably, certifiable, runner, reinsertion
Transunion: reseller, accuser, certifiably, certifiable, compliantly, reinsertion
BofA: merchant, foreclose, teller, platinum, mellon(?), firearm, mesne
Wells Fargo: preservation, foreclose, appraisal, preservationist, teller, dealer
JP Morgan Chase: sapphire, southwest, merchant, airway, explorer, teller
CitiBank: depot, promotional, goodyear, prestige, merchant, dividend
Capital One: kohl, quicksilver, savor, orchard, merchant, venture, rebill
Navient Solutions: pioneer, mae, unsubsidized, diploma, recertify, graduation
Ocwen Financial: homeward, foreclose, suspense, hooligan, duplex
We have do see the different categories of financial institutions, with the financial bureaus producing different results from the banks that do more mortgage lending and storefront banking, and from the U.S. Department of Education loan servicer Navient.
At the same time, this result is pretty disheartening. These most important words don’t feel super insightful. I’m thinking:
Maybe we need to look at more than these top words, like the top 100?Alternatively, tf-idf might no be the right tool for this job. With SO many complaints for these companies, many words appear at least once in all or nearly all of the companies’ “corpus” of complaints. This factor, the inverse document frequency, is overpowering the text frequency. I wonder how the results would vary if I used all of the companies, instead of just the top 20.
Maybe we need to look at more than these top words, like the top 100?
Alternatively, tf-idf might no be the right tool for this job. With SO many complaints for these companies, many words appear at least once in all or nearly all of the companies’ “corpus” of complaints. This factor, the inverse document frequency, is overpowering the text frequency. I wonder how the results would vary if I used all of the companies, instead of just the top 20.
As always, find more (code) in the GitHub repo.
|
[
{
"code": null,
"e": 240,
"s": 171,
"text": "The question: what words (from complaints) are distinctly Equifax-y?"
},
{
"code": null,
"e": 670,
"s": 240,
"text": "Today we’re diving deeper into the US Consumer Financial Protection Bureau’s Financial Services Consumer Complaint database to look at the text of the complaints filed against companies. The question: what words (from complaints) are distinctly Equifax-y? We’re going to be looking at text cleaning, tokenization, and lemming with Spark-NLP, counting with PySpark, and tf-idf (term frequency-inverse document frequency) analysis."
},
{
"code": null,
"e": 814,
"s": 670,
"text": "I used John Snow LABS’ Spark-NLP library. You can learn more from them, or wikipedia (probably also written by them, but in a different style)."
},
{
"code": null,
"e": 927,
"s": 814,
"text": "John Snow LABS provides a couple of different quick start guides — here and here — that I found useful together."
},
{
"code": null,
"e": 1029,
"s": 927,
"text": "If you haven’t already installed PySpark (note: PySpark version 2.4.4 is the only supported version):"
},
{
"code": null,
"e": 1101,
"s": 1029,
"text": "$ conda install pyspark==2.4.4$ conda install -c johnsnowlabs spark-nlp"
},
{
"code": null,
"e": 1307,
"s": 1101,
"text": "If you already have PySpark, make sure to install spark-nlp in the same channel as PySpark (you can check the channel from conda list). In my case, PySpark is installed on my conda-forge channel, so I used"
},
{
"code": null,
"e": 1371,
"s": 1307,
"text": "$ conda install -c johnsnowlabs spark-nlp — channel conda-forge"
},
{
"code": null,
"e": 1612,
"s": 1371,
"text": "I already had PySpark installed and set up for use with Jupyter notebooks, but if you don’t, you may need to set some additional environment variables in the terminal (as mentioned in the second quick start guide, but not the first, so ...)"
},
{
"code": null,
"e": 1772,
"s": 1612,
"text": "$ export SPARK_HOME=/path/to/your/spark/folder$ export PYSPARK_PYTHON=python3$ export PYSPARK_DRIVER_PYTHON=jupyter$ export PYSPARK_DRIVER_PYTHON_OPTS=notebook"
},
{
"code": null,
"e": 1940,
"s": 1772,
"text": "If you are looking to play around with pre-installed data sets, and therefore don’t need to access the spark session, you can get started with the following two lines:"
},
{
"code": null,
"e": 1972,
"s": 1940,
"text": "import sparknlpsparknlp.start()"
},
{
"code": null,
"e": 2162,
"s": 1972,
"text": "In my case, I need the SparkSession to load my data from the parquet file, so I’ll add .config(“spark.jars.packages”, “com.johnsnowlabs.nlp:spark-nlp_2.11:2.3.5”) to my SparkSession.builder"
},
{
"code": null,
"e": 2443,
"s": 2162,
"text": "from pyspark.sql import SparkSession# start spark session configured for spark nlpspark = SparkSession.builder \\ .master('local[*]') \\ .appName('Spark NLP') \\ .config('spark.jars.packages', 'com.johnsnowlabs.nlp:spark-nlp_2.11:2.3.5') \\ .getOrCreate()"
},
{
"code": null,
"e": 2475,
"s": 2443,
"text": "That’s it! You’re up and going!"
},
{
"code": null,
"e": 2655,
"s": 2475,
"text": "Spark-NLP does not come with a built-in stop words dictionary, so I chose to use the NLTK English Language stop words, as well as the ‘xxxx’ redacting string found in my data set."
},
{
"code": null,
"e": 2759,
"s": 2655,
"text": "from nltk.corpus import stopwordseng_stopwords = stopwords.words('english')eng_stopwords.append('xxxx')"
},
{
"code": null,
"e": 2788,
"s": 2759,
"text": "To start, import your tools:"
},
{
"code": null,
"e": 2993,
"s": 2788,
"text": "from sparknlp.base import Finisher, DocumentAssemblerfrom sparknlp.annotator import (Tokenizer, Normalizer, LemmatizerModel, StopWordsCleaner)from pyspark.ml import Pipeline"
},
{
"code": null,
"e": 3247,
"s": 2993,
"text": "Most projects are going to need DocumentAssembler to convert the text into a Spark-NLP annotator-ready form at the beginning, and Finisher to convert back to human-readable form at the end. You can select the annotators you need from the annotator docs."
},
{
"code": null,
"e": 3589,
"s": 3247,
"text": "Before you set up the pipeline, we need to initialize the annotators with the proper inputs. We’ll use the typical Spark ML format of .setInputCols(list of columns) and .setOutputCol(output column name), along with other functions specific to the annotator (see docs). Each output column will be the input column for the following annotator."
},
{
"code": null,
"e": 4555,
"s": 3589,
"text": "documentAssembler = DocumentAssembler() \\ .setInputCol('consumer_complaint_narrative') \\ .setOutputCol('document')tokenizer = Tokenizer() \\ .setInputCols(['document']) \\ .setOutputCol('token')# note normalizer defaults to changing all words to lowercase.# Use .setLowercase(False) to maintain input case.normalizer = Normalizer() \\ .setInputCols(['token']) \\ .setOutputCol('normalized') \\ .setLowercase(True)# note that lemmatizer needs a dictionary. So I used the pre-trained# model (note that it defaults to english)lemmatizer = LemmatizerModel.pretrained() \\ .setInputCols(['normalized']) \\ .setOutputCol('lemma')stopwords_cleaner = StopWordsCleaner() \\ .setInputCols(['lemma']) \\ .setOutputCol('clean_lemma') \\ .setCaseSensitive(False) \\ .setStopWords(eng_stopwords)# finisher converts tokens to human-readable outputfinisher = Finisher() \\ .setInputCols(['clean_lemma']) \\ .setCleanAnnotations(False)"
},
{
"code": null,
"e": 4595,
"s": 4555,
"text": "Now we’re ready to define the pipeline:"
},
{
"code": null,
"e": 4785,
"s": 4595,
"text": "pipeline = Pipeline() \\ .setStages([ documentAssembler, tokenizer, normalizer, lemmatizer, stopwords_cleaner, finisher ])"
},
{
"code": null,
"e": 4876,
"s": 4785,
"text": "I import and select my data, and then use pipeline.fit(data).transform(data). For example:"
},
{
"code": null,
"e": 5285,
"s": 4876,
"text": "# import datadf = spark.read.load('../data/consumer_complaints.parquet', inferSchema='true', header='true')# select equifax text data as testdata = df.filter((df['company'] == 'EQUIFAX, INC.') & (df['consumer_complaint_narrative'].isNull() == False))data = data.select('consumer_complaint_narrative')# transform text with the pipelineequifax = pipeline.fit(data).transform(data)"
},
{
"code": null,
"e": 5401,
"s": 5285,
"text": "This returns a DataFrame with the added columns specified in the pipeline’s annotators. So equifax.columns returns:"
},
{
"code": null,
"e": 5517,
"s": 5401,
"text": "['consumer_complaint_narrative', 'document', 'token', 'normalized', 'lemma', 'clean_lemma', 'finished_clean_lemma']"
},
{
"code": null,
"e": 5710,
"s": 5517,
"text": "When we look more closely at the output of the finisher, in this case the “finished_clean_lemma”, we see that each record is a list of words — eg. [address, never, ...], [pay, satisfied, ...]."
},
{
"code": null,
"e": 5796,
"s": 5710,
"text": "In order to get each word on the same level, I used the pyspark.sql explode function."
},
{
"code": null,
"e": 5969,
"s": 5796,
"text": "from pyspark.sql.functions import explode, colequifax_words = equifax_words.withColumn('exploded_text', explode(col('finished_clean_lemma')))"
},
{
"code": null,
"e": 6045,
"s": 5969,
"text": "Now the text is ready to .groupby().count() to get the count for each word."
},
{
"code": null,
"e": 6203,
"s": 6045,
"text": "I then converted the result to pandas and used a dictionary comprehension to convert the table into a dictionary (this may not be the most elegant strategy)."
},
{
"code": null,
"e": 6432,
"s": 6203,
"text": "counts = equifax_words.groupby('exploded_text').count()counts_pd = counts.toPandas()equifax_dict = {counts_pd.loc[i, 'exploded_text']: counts_pd.loc[i, 'count'] for i in range(counts_pd.shape[0])}"
},
{
"code": null,
"e": 6603,
"s": 6432,
"text": "Full disclosure: even using Spark running on all four cores, doing this for the top 20 complaint earners took a significant amount of time — this is a lot of computation!"
},
{
"code": null,
"e": 6819,
"s": 6603,
"text": "Now that I have the text from each company’s complaints count vectorized (aka converted into a dictionary of {word1: count1, word2: count2...}), I am ready to get the tf-idf for each word in each company’s word set."
},
{
"code": null,
"e": 6837,
"s": 6819,
"text": "Helper functions:"
},
{
"code": null,
"e": 7945,
"s": 6837,
"text": "def term_frequency(BoW_dict): tot_words = sum(BoW_dict.values()) freq_dict = {word: BoW_dict[word]/tot_words for word in BoW_dict.keys()} return freq_dictfrom math import logdef inverse_document_frequency(list_of_dicts): tot_docs = len(list_of_dicts) words = set([w for w_dict in list_of_dicts for w in w_dict.keys()]) idf_dict = {word: log(float(tot_docs)/ (1.0 + sum([1 for w_dict in list_of_dicts if word in w_dict.keys()]))) for word in words} return idf_dictdef tf_idf(list_of_dicts): words = set([w for w_dict in list_of_dicts for w in w_dict.keys()]) tf_idf_dicts = [] idfs = inverse_document_frequency(list_of_dicts) for i, w_dict in enumerate(list_of_dicts): w_dict.update({word: 0 for word in words if word not in w_dict.keys()}) tf = term_frequency(w_dict) tf_idf_dicts.append({word: tf[word]*idfs[word] for word in words}) return tf_idf_dicts"
},
{
"code": null,
"e": 7966,
"s": 7945,
"text": "Putting it together:"
},
{
"code": null,
"e": 8236,
"s": 7966,
"text": "list_of_word_dicts = [company_complaint_word_counts_dict[company] for company in companies]tf_idf_by_company_list = tf_idf(list_of_word_dicts)tf_idf_by_company_dict = {c: tf_dict for c, tf_dict in zip(companies, tf_idf_by_company_list)}"
},
{
"code": null,
"e": 8358,
"s": 8236,
"text": "To find the words that set each company apart, I found the words with the top tf-idf scores for my companies of interest."
},
{
"code": null,
"e": 9079,
"s": 8358,
"text": "Unfortunately, this revealed that I hadn’t done enough to clean my data. All of the highest tf-idf score words were typos or sets of words smashed together (eg. ‘tobe’, ‘calledthem’, etc.). Sometimes 1000 character strings without spaces. So here, I added a filter based on the nltk.corpus words.words() list. Unfortunately tobe is actually a word, so it still shows up in some of the top results. Given the issue with missing spaces in the dataset, I doubt that people were talking about “an outer garment traditionally word in some parts of north and central Africa, consisting of a length of cloth that is sewn into a long loose skirt or is draped around the body and fastened over one shoulder” (Collins Dictionary)."
},
{
"code": null,
"e": 9164,
"s": 9079,
"text": "Let’s take a look at some of the top tf-idf scoring words for our top ten companies:"
},
{
"code": null,
"e": 9238,
"s": 9164,
"text": "Equifax: reseller, accuser, reinsertion, certifiably, certifiable, runner"
},
{
"code": null,
"e": 9313,
"s": 9238,
"text": "Experian: reseller, accuser, certifiably, certifiable, runner, reinsertion"
},
{
"code": null,
"e": 9395,
"s": 9313,
"text": "Transunion: reseller, accuser, certifiably, certifiable, compliantly, reinsertion"
},
{
"code": null,
"e": 9466,
"s": 9395,
"text": "BofA: merchant, foreclose, teller, platinum, mellon(?), firearm, mesne"
},
{
"code": null,
"e": 9547,
"s": 9466,
"text": "Wells Fargo: preservation, foreclose, appraisal, preservationist, teller, dealer"
},
{
"code": null,
"e": 9620,
"s": 9547,
"text": "JP Morgan Chase: sapphire, southwest, merchant, airway, explorer, teller"
},
{
"code": null,
"e": 9689,
"s": 9620,
"text": "CitiBank: depot, promotional, goodyear, prestige, merchant, dividend"
},
{
"code": null,
"e": 9763,
"s": 9689,
"text": "Capital One: kohl, quicksilver, savor, orchard, merchant, venture, rebill"
},
{
"code": null,
"e": 9841,
"s": 9763,
"text": "Navient Solutions: pioneer, mae, unsubsidized, diploma, recertify, graduation"
},
{
"code": null,
"e": 9906,
"s": 9841,
"text": "Ocwen Financial: homeward, foreclose, suspense, hooligan, duplex"
},
{
"code": null,
"e": 10162,
"s": 9906,
"text": "We have do see the different categories of financial institutions, with the financial bureaus producing different results from the banks that do more mortgage lending and storefront banking, and from the U.S. Department of Education loan servicer Navient."
},
{
"code": null,
"e": 10287,
"s": 10162,
"text": "At the same time, this result is pretty disheartening. These most important words don’t feel super insightful. I’m thinking:"
},
{
"code": null,
"e": 10736,
"s": 10287,
"text": "Maybe we need to look at more than these top words, like the top 100?Alternatively, tf-idf might no be the right tool for this job. With SO many complaints for these companies, many words appear at least once in all or nearly all of the companies’ “corpus” of complaints. This factor, the inverse document frequency, is overpowering the text frequency. I wonder how the results would vary if I used all of the companies, instead of just the top 20."
},
{
"code": null,
"e": 10806,
"s": 10736,
"text": "Maybe we need to look at more than these top words, like the top 100?"
},
{
"code": null,
"e": 11186,
"s": 10806,
"text": "Alternatively, tf-idf might no be the right tool for this job. With SO many complaints for these companies, many words appear at least once in all or nearly all of the companies’ “corpus” of complaints. This factor, the inverse document frequency, is overpowering the text frequency. I wonder how the results would vary if I used all of the companies, instead of just the top 20."
}
] |
How to close a browser session in Selenium with python?
|
We can close a browser session in Selenium by the following ways −
Using the close() method.
Using the close() method.
Using the quit() method.
Using the quit() method.
Both these methods close the browser, but close() the browser in focus and quit() ends the driver session.
Code Implementation with close().
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close()
Code Implementation with quit().
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to end the driver session
driver.quit()
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "We can close a browser session in Selenium by the following ways −"
},
{
"code": null,
"e": 1155,
"s": 1129,
"text": "Using the close() method."
},
{
"code": null,
"e": 1181,
"s": 1155,
"text": "Using the close() method."
},
{
"code": null,
"e": 1206,
"s": 1181,
"text": "Using the quit() method."
},
{
"code": null,
"e": 1231,
"s": 1206,
"text": "Using the quit() method."
},
{
"code": null,
"e": 1338,
"s": 1231,
"text": "Both these methods close the browser, but close() the browser in focus and quit() ends the driver session."
},
{
"code": null,
"e": 1372,
"s": 1338,
"text": "Code Implementation with close()."
},
{
"code": null,
"e": 1823,
"s": 1372,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()"
},
{
"code": null,
"e": 1856,
"s": 1823,
"text": "Code Implementation with quit()."
},
{
"code": null,
"e": 2311,
"s": 1856,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to end the driver session\ndriver.quit()"
}
] |
Split the string into minimum parts such that each part is in the another string - GeeksforGeeks
|
09 Sep, 2021
Given two strings A and B, the task is to split the string A into the minimum number of substrings such that each substring is in the string B.
Note: If there is no way to split the string, then print -1
Examples:
Input: A = “abcdab”, B = “dabc” Output: 2 Explanation: The two substrings of A which is also present in B are – {“abc”, “dab”}
Input: A = “abcde”, B = “edcb” Output: -1 Explanation: There is no way to split the string A into substring Such that each string is also present in the B.
Approach:
Construct a trie of every substring of B.
After that, we’ll use Dynamic programming to find the minimum number of parts to break the string A such that every part is a substring of B.
Recurrence Relation in Dynamic Programming:
dp[i] = minimum number of parts to break the string A up to ith prefix.
dp[0] = 0
for i in {0, S1.length}
for j in {i, S1.length}
if(S1[i, ... j] is found in trie
dp[j] = min(dp[j], dp[i] + 1);
else
break;
dp[S1.length] is the
minimum number of parts.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to split the// string into minimum number of// parts such that each part is also// present in the another string #include <bits/stdc++.h>using namespace std; const int INF = 1e9 + 9; // Node of Triestruct TrieNode { TrieNode* child[26] = { NULL };}; // Function to insert a node in the// Trie Data Structurevoid insert(int idx, string& s, TrieNode* root){ TrieNode* temp = root; for (int i = idx; i < s.length(); i++) { // Inserting every character from idx // till end to string into trie if (temp->child[s[i] - 'a'] == NULL) // if there is no edge corresponding // to the ith character, // then make a new node temp->child[s[i] - 'a'] = new TrieNode; temp = temp->child[s[i] - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another stringint minCuts(string S1, string S2){ int n1 = S1.length(); int n2 = S2.length(); // Making a new trie TrieNode* root = new TrieNode; for (int i = 0; i < n2; i++) { // Inserting every substring // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity vector<int> dp(n1 + 1, INF); // Base Case dp[0] = 0; for (int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the substring // [i, j) is present in trie of not TrieNode* temp = root; for (int j = i + 1; j <= n1; j++) { if (temp->child[S1[j - 1] - 'a'] == NULL) // if the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp->child[S1[j - 1] - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codeint main(){ string S1 = "abcdab"; string S2 = "dabc"; cout << minCuts(S1, S2);}
// Java implementation to split the// String into minimum number of// parts such that each part is also// present in the another Stringimport java.util.*; class GFG{ static int INF = (int)(1e9 + 9); // Node of Triestatic class TrieNode{ TrieNode []child = new TrieNode[26];}; // Function to insert a node in the// Trie Data Structurestatic void insert(int idx, String s, TrieNode root){ TrieNode temp = root; for(int i = idx; i < s.length(); i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s.charAt(i) - 'a'] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s.charAt(i) - 'a'] = new TrieNode(); temp = temp.child[s.charAt(i) - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another Stringstatic int minCuts(String S1, String S2){ int n1 = S1.length(); int n2 = S2.length(); // Making a new trie TrieNode root = new TrieNode(); for(int i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity int []dp = new int[n1 + 1]; Arrays.fill(dp, INF); // Base Case dp[0] = 0; for(int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not TrieNode temp = root; for(int j = i + 1; j <= n1; j++) { if (temp.child[S1.charAt(j - 1) - 'a'] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1.charAt(j - 1) - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codepublic static void main(String[] args){ String S1 = "abcdab"; String S2 = "dabc"; System.out.print(minCuts(S1, S2));}} // This code is contributed by Rajput-Ji
# Python3 implementation to split the# string into minimum number of# parts such that each part is also# present in the another stringINF = 1e9 + 9 # Node of Trieclass TrieNode(): def __init__(self): self.child = [None] * 26 # Function to insert a node in the# Trie Data Structuredef insert(idx, s, root): temp = root for i in range(idx, len(s)): # Inserting every character from idx # till end to string into trie if temp.child[ord(s[i]) - ord('a')] == None: # If there is no edge corresponding # to the ith character, # then make a new node temp.child[ord(s[i]) - ord('a')] = TrieNode() temp = temp.child[ord(s[i]) - ord('a')] # Function to find the minimum# number of parts such that each# part is present into another stringdef minCuts(S1, S2): n1 = len(S1) n2 = len(S2) # Making a new trie root = TrieNode() for i in range(n2): # Inserting every substring # of S2 in trie insert(i, S2, root) # Creating dp array and # init it with infinity dp = [INF] * (n1 + 1) # Base Case dp[0] = 0 for i in range(n1): # Starting the cut from ith character # taking temporary node pointer # for checking whether the substring # [i, j) is present in trie of not temp = root for j in range(i + 1, n1 + 1): if temp.child[ord(S1[j - 1]) - ord('a')] == None: # If the jth character is not # in trie we'll break break # Updating the the ending of # jth character with dp[i] + 1 dp[j] = min(dp[j], dp[i] + 1) # Descending the trie pointer temp = temp.child[ord(S1[j - 1]) - ord('a')] # Answer not possible if dp[n1] >= INF: return -1 else: return dp[n1] # Driver CodeS1 = "abcdab"S2 = "dabc" print(minCuts(S1, S2)) # This code is contributed by Shivam Singh
// C# implementation to split the// String into minimum number of// parts such that each part is also// present in the another Stringusing System;class GFG{ static int INF = (int)(1e9 + 9); // Node of Trieclass TrieNode{ public TrieNode []child = new TrieNode[26];}; // Function to insert a node in the// Trie Data Structurestatic void insert(int idx, String s, TrieNode root){ TrieNode temp = root; for(int i = idx; i < s.Length; i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s[i] - 'a'] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s[i] - 'a'] = new TrieNode(); temp = temp.child[s[i] - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another Stringstatic int minCuts(String S1, String S2){ int n1 = S1.Length; int n2 = S2.Length; // Making a new trie TrieNode root = new TrieNode(); for(int i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity int []dp = new int[n1 + 1]; for(int i = 0; i <= n1; i++) dp[i] = INF; // Base Case dp[0] = 0; for(int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not TrieNode temp = root; for(int j = i + 1; j <= n1; j++) { if (temp.child[S1[j-1] - 'a'] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.Min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1[j - 1] - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codepublic static void Main(String[] args){ String S1 = "abcdab"; String S2 = "dabc"; Console.Write(minCuts(S1, S2));}}// This code is contributed by shikhasingrajput
<script> // Javascript implementation to split the // String into minimum number of // parts such that each part is also // present in the another String let INF = (1e9 + 9); // Node of Trie class Node { constructor() { } } function TrieNode() { let temp = new Node(); temp.child = new Node(26); for(let i = 0; i < 26; i++) { temp.child[i] = null; } return temp; } // Function to insert a node in the // Trie Data Structure function insert(idx, s, root) { let temp = root; for(let i = idx; i < s.length; i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s[i].charCodeAt() - 'a'.charCodeAt()] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s[i].charCodeAt() - 'a'.charCodeAt()] = new TrieNode(); temp = temp.child[s[i].charCodeAt() - 'a'.charCodeAt()]; } } // Function to find the minimum // number of parts such that each // part is present into another String function minCuts(S1, S2) { let n1 = S1.length; let n2 = S2.length; // Making a new trie let root = new TrieNode(); for(let i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity let dp = new Array(n1 + 1); dp.fill(INF); // Base Case dp[0] = 0; for(let i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not let temp = root; for(let j = i + 1; j <= n1; j++) { if (temp.child[S1[j - 1].charCodeAt() - 'a'.charCodeAt()] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1[j - 1].charCodeAt() - 'a'.charCodeAt()]; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1]; } let S1 = "abcdab"; let S2 = "dabc"; document.write(minCuts(S1, S2)); // This code is contributed by mukesh07.</script>
2
Time Complexity :
Space Complexity :
SHIVAMSINGH67
Rajput-Ji
shikhasingrajput
mukesh07
sweetyty
Competitive Programming
Dynamic Programming
Strings
Tree
Strings
Dynamic Programming
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Breadth First Traversal ( BFS ) on a 2D array
Runtime Errors
Multistage Graph (Shortest Path)
Most important type of Algorithms
Shortest path in a directed graph by Dijkstra’s algorithm
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
|
[
{
"code": null,
"e": 24711,
"s": 24683,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24855,
"s": 24711,
"text": "Given two strings A and B, the task is to split the string A into the minimum number of substrings such that each substring is in the string B."
},
{
"code": null,
"e": 24916,
"s": 24855,
"text": "Note: If there is no way to split the string, then print -1 "
},
{
"code": null,
"e": 24926,
"s": 24916,
"text": "Examples:"
},
{
"code": null,
"e": 25053,
"s": 24926,
"text": "Input: A = “abcdab”, B = “dabc” Output: 2 Explanation: The two substrings of A which is also present in B are – {“abc”, “dab”}"
},
{
"code": null,
"e": 25209,
"s": 25053,
"text": "Input: A = “abcde”, B = “edcb” Output: -1 Explanation: There is no way to split the string A into substring Such that each string is also present in the B."
},
{
"code": null,
"e": 25219,
"s": 25209,
"text": "Approach:"
},
{
"code": null,
"e": 25261,
"s": 25219,
"text": "Construct a trie of every substring of B."
},
{
"code": null,
"e": 25403,
"s": 25261,
"text": "After that, we’ll use Dynamic programming to find the minimum number of parts to break the string A such that every part is a substring of B."
},
{
"code": null,
"e": 25447,
"s": 25403,
"text": "Recurrence Relation in Dynamic Programming:"
},
{
"code": null,
"e": 25519,
"s": 25447,
"text": "dp[i] = minimum number of parts to break the string A up to ith prefix."
},
{
"code": null,
"e": 25744,
"s": 25519,
"text": "dp[0] = 0\nfor i in {0, S1.length}\n for j in {i, S1.length}\n if(S1[i, ... j] is found in trie\n dp[j] = min(dp[j], dp[i] + 1);\n else\n break;\n\ndp[S1.length] is the\nminimum number of parts."
},
{
"code": null,
"e": 25795,
"s": 25744,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25799,
"s": 25795,
"text": "C++"
},
{
"code": null,
"e": 25804,
"s": 25799,
"text": "Java"
},
{
"code": null,
"e": 25812,
"s": 25804,
"text": "Python3"
},
{
"code": null,
"e": 25815,
"s": 25812,
"text": "C#"
},
{
"code": null,
"e": 25826,
"s": 25815,
"text": "Javascript"
},
{
"code": "// C++ implementation to split the// string into minimum number of// parts such that each part is also// present in the another string #include <bits/stdc++.h>using namespace std; const int INF = 1e9 + 9; // Node of Triestruct TrieNode { TrieNode* child[26] = { NULL };}; // Function to insert a node in the// Trie Data Structurevoid insert(int idx, string& s, TrieNode* root){ TrieNode* temp = root; for (int i = idx; i < s.length(); i++) { // Inserting every character from idx // till end to string into trie if (temp->child[s[i] - 'a'] == NULL) // if there is no edge corresponding // to the ith character, // then make a new node temp->child[s[i] - 'a'] = new TrieNode; temp = temp->child[s[i] - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another stringint minCuts(string S1, string S2){ int n1 = S1.length(); int n2 = S2.length(); // Making a new trie TrieNode* root = new TrieNode; for (int i = 0; i < n2; i++) { // Inserting every substring // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity vector<int> dp(n1 + 1, INF); // Base Case dp[0] = 0; for (int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the substring // [i, j) is present in trie of not TrieNode* temp = root; for (int j = i + 1; j <= n1; j++) { if (temp->child[S1[j - 1] - 'a'] == NULL) // if the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp->child[S1[j - 1] - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codeint main(){ string S1 = \"abcdab\"; string S2 = \"dabc\"; cout << minCuts(S1, S2);}",
"e": 28005,
"s": 25826,
"text": null
},
{
"code": "// Java implementation to split the// String into minimum number of// parts such that each part is also// present in the another Stringimport java.util.*; class GFG{ static int INF = (int)(1e9 + 9); // Node of Triestatic class TrieNode{ TrieNode []child = new TrieNode[26];}; // Function to insert a node in the// Trie Data Structurestatic void insert(int idx, String s, TrieNode root){ TrieNode temp = root; for(int i = idx; i < s.length(); i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s.charAt(i) - 'a'] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s.charAt(i) - 'a'] = new TrieNode(); temp = temp.child[s.charAt(i) - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another Stringstatic int minCuts(String S1, String S2){ int n1 = S1.length(); int n2 = S2.length(); // Making a new trie TrieNode root = new TrieNode(); for(int i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity int []dp = new int[n1 + 1]; Arrays.fill(dp, INF); // Base Case dp[0] = 0; for(int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not TrieNode temp = root; for(int j = i + 1; j <= n1; j++) { if (temp.child[S1.charAt(j - 1) - 'a'] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1.charAt(j - 1) - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codepublic static void main(String[] args){ String S1 = \"abcdab\"; String S2 = \"dabc\"; System.out.print(minCuts(S1, S2));}} // This code is contributed by Rajput-Ji",
"e": 30392,
"s": 28005,
"text": null
},
{
"code": "# Python3 implementation to split the# string into minimum number of# parts such that each part is also# present in the another stringINF = 1e9 + 9 # Node of Trieclass TrieNode(): def __init__(self): self.child = [None] * 26 # Function to insert a node in the# Trie Data Structuredef insert(idx, s, root): temp = root for i in range(idx, len(s)): # Inserting every character from idx # till end to string into trie if temp.child[ord(s[i]) - ord('a')] == None: # If there is no edge corresponding # to the ith character, # then make a new node temp.child[ord(s[i]) - ord('a')] = TrieNode() temp = temp.child[ord(s[i]) - ord('a')] # Function to find the minimum# number of parts such that each# part is present into another stringdef minCuts(S1, S2): n1 = len(S1) n2 = len(S2) # Making a new trie root = TrieNode() for i in range(n2): # Inserting every substring # of S2 in trie insert(i, S2, root) # Creating dp array and # init it with infinity dp = [INF] * (n1 + 1) # Base Case dp[0] = 0 for i in range(n1): # Starting the cut from ith character # taking temporary node pointer # for checking whether the substring # [i, j) is present in trie of not temp = root for j in range(i + 1, n1 + 1): if temp.child[ord(S1[j - 1]) - ord('a')] == None: # If the jth character is not # in trie we'll break break # Updating the the ending of # jth character with dp[i] + 1 dp[j] = min(dp[j], dp[i] + 1) # Descending the trie pointer temp = temp.child[ord(S1[j - 1]) - ord('a')] # Answer not possible if dp[n1] >= INF: return -1 else: return dp[n1] # Driver CodeS1 = \"abcdab\"S2 = \"dabc\" print(minCuts(S1, S2)) # This code is contributed by Shivam Singh",
"e": 32526,
"s": 30392,
"text": null
},
{
"code": "// C# implementation to split the// String into minimum number of// parts such that each part is also// present in the another Stringusing System;class GFG{ static int INF = (int)(1e9 + 9); // Node of Trieclass TrieNode{ public TrieNode []child = new TrieNode[26];}; // Function to insert a node in the// Trie Data Structurestatic void insert(int idx, String s, TrieNode root){ TrieNode temp = root; for(int i = idx; i < s.Length; i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s[i] - 'a'] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s[i] - 'a'] = new TrieNode(); temp = temp.child[s[i] - 'a']; }} // Function to find the minimum// number of parts such that each// part is present into another Stringstatic int minCuts(String S1, String S2){ int n1 = S1.Length; int n2 = S2.Length; // Making a new trie TrieNode root = new TrieNode(); for(int i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity int []dp = new int[n1 + 1]; for(int i = 0; i <= n1; i++) dp[i] = INF; // Base Case dp[0] = 0; for(int i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not TrieNode temp = root; for(int j = i + 1; j <= n1; j++) { if (temp.child[S1[j-1] - 'a'] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.Min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1[j - 1] - 'a']; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1];} // Driver Codepublic static void Main(String[] args){ String S1 = \"abcdab\"; String S2 = \"dabc\"; Console.Write(minCuts(S1, S2));}}// This code is contributed by shikhasingrajput",
"e": 34925,
"s": 32526,
"text": null
},
{
"code": "<script> // Javascript implementation to split the // String into minimum number of // parts such that each part is also // present in the another String let INF = (1e9 + 9); // Node of Trie class Node { constructor() { } } function TrieNode() { let temp = new Node(); temp.child = new Node(26); for(let i = 0; i < 26; i++) { temp.child[i] = null; } return temp; } // Function to insert a node in the // Trie Data Structure function insert(idx, s, root) { let temp = root; for(let i = idx; i < s.length; i++) { // Inserting every character from idx // till end to String into trie if (temp.child[s[i].charCodeAt() - 'a'.charCodeAt()] == null) // If there is no edge corresponding // to the ith character, // then make a new node temp.child[s[i].charCodeAt() - 'a'.charCodeAt()] = new TrieNode(); temp = temp.child[s[i].charCodeAt() - 'a'.charCodeAt()]; } } // Function to find the minimum // number of parts such that each // part is present into another String function minCuts(S1, S2) { let n1 = S1.length; let n2 = S2.length; // Making a new trie let root = new TrieNode(); for(let i = 0; i < n2; i++) { // Inserting every subString // of S2 in trie insert(i, S2, root); } // Creating dp array and // init it with infinity let dp = new Array(n1 + 1); dp.fill(INF); // Base Case dp[0] = 0; for(let i = 0; i < n1; i++) { // Starting the cut from ith character // taking temporary node pointer // for checking whether the subString // [i, j) is present in trie of not let temp = root; for(let j = i + 1; j <= n1; j++) { if (temp.child[S1[j - 1].charCodeAt() - 'a'.charCodeAt()] == null) // If the jth character is not in trie // we'll break break; // Updating the the ending of // jth character with dp[i] + 1 dp[j] = Math.min(dp[j], dp[i] + 1); // Descending the trie pointer temp = temp.child[S1[j - 1].charCodeAt() - 'a'.charCodeAt()]; } } // Answer not possible if (dp[n1] >= INF) return -1; else return dp[n1]; } let S1 = \"abcdab\"; let S2 = \"dabc\"; document.write(minCuts(S1, S2)); // This code is contributed by mukesh07.</script>",
"e": 37728,
"s": 34925,
"text": null
},
{
"code": null,
"e": 37730,
"s": 37728,
"text": "2"
},
{
"code": null,
"e": 37749,
"s": 37730,
"text": "Time Complexity : "
},
{
"code": null,
"e": 37771,
"s": 37751,
"text": "Space Complexity : "
},
{
"code": null,
"e": 37787,
"s": 37773,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 37797,
"s": 37787,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37814,
"s": 37797,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 37823,
"s": 37814,
"text": "mukesh07"
},
{
"code": null,
"e": 37832,
"s": 37823,
"text": "sweetyty"
},
{
"code": null,
"e": 37856,
"s": 37832,
"text": "Competitive Programming"
},
{
"code": null,
"e": 37876,
"s": 37856,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37884,
"s": 37876,
"text": "Strings"
},
{
"code": null,
"e": 37889,
"s": 37884,
"text": "Tree"
},
{
"code": null,
"e": 37897,
"s": 37889,
"text": "Strings"
},
{
"code": null,
"e": 37917,
"s": 37897,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37922,
"s": 37917,
"text": "Tree"
},
{
"code": null,
"e": 38020,
"s": 37922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38029,
"s": 38020,
"text": "Comments"
},
{
"code": null,
"e": 38042,
"s": 38029,
"text": "Old Comments"
},
{
"code": null,
"e": 38088,
"s": 38042,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 38103,
"s": 38088,
"text": "Runtime Errors"
},
{
"code": null,
"e": 38136,
"s": 38103,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 38170,
"s": 38136,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 38228,
"s": 38170,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 38257,
"s": 38228,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 38287,
"s": 38257,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38319,
"s": 38287,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 38353,
"s": 38319,
"text": "Longest Common Subsequence | DP-4"
}
] |
Finding Armstrong numbers in a given range in JavaScript
|
A number is called Armstrong number if the following equation holds true for that number:
xy...z =xx +yy+...+zz, where n denotes the number of digits in the number.
153 is an Armstrong number because −
11 +55 +33 = 1 + 125 + 27 =153
We are required to write a JavaScript function that takes in two numbers, a range, and returns
all the numbers between them that are Armstrong numbers (including them, if they are Armstrong)
The code for this will be −
const isArmstrong = number => {
let num = number;
const len = String(num).split("").length;
let res = 0;
while(num){
const last = num % 10;
res += Math.pow(last, len);
num = Math.floor(num / 10);
};
return res === number;
};
const armstrongBetween = (lower, upper) => {
const res = [];
for(let i = lower; i <= upper; i++){
if(isArmstrong(i)){
res.push(i);
};
};
return res;
};
console.log(armstrongBetween(1, 400));
The output in the console −
[
1, 2, 3, 4, 5,
6, 7, 8, 9, 153,
370, 371
]
|
[
{
"code": null,
"e": 1227,
"s": 1062,
"text": "A number is called Armstrong number if the following equation holds true for that number:\nxy...z =xx +yy+...+zz, where n denotes the number of digits in the number."
},
{
"code": null,
"e": 1264,
"s": 1227,
"text": "153 is an Armstrong number because −"
},
{
"code": null,
"e": 1295,
"s": 1264,
"text": "11 +55 +33 = 1 + 125 + 27 =153"
},
{
"code": null,
"e": 1486,
"s": 1295,
"text": "We are required to write a JavaScript function that takes in two numbers, a range, and returns\nall the numbers between them that are Armstrong numbers (including them, if they are Armstrong)"
},
{
"code": null,
"e": 1514,
"s": 1486,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1999,
"s": 1514,
"text": "const isArmstrong = number => {\n let num = number;\n const len = String(num).split(\"\").length;\n let res = 0;\n while(num){\n const last = num % 10;\n res += Math.pow(last, len);\n num = Math.floor(num / 10);\n };\n return res === number;\n};\nconst armstrongBetween = (lower, upper) => {\n const res = [];\n for(let i = lower; i <= upper; i++){\n if(isArmstrong(i)){\n res.push(i);\n };\n };\n return res;\n};\nconsole.log(armstrongBetween(1, 400));"
},
{
"code": null,
"e": 2027,
"s": 1999,
"text": "The output in the console −"
},
{
"code": null,
"e": 2081,
"s": 2027,
"text": "[\n 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 153,\n 370, 371\n]"
}
] |
Java - abs() Method
|
The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte.
Following are all the variants of this method −
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)
Here is the detail of parameters −
Any primitive data type.
This method Returns the absolute value of the argument.
public class Test {
public static void main(String args[]) {
Integer a = -8;
double d = -100;
float f = -90;
System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));
}
}
This will produce the following result −
8
100.0
90.0
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": 2489,
"s": 2377,
"text": "The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte."
},
{
"code": null,
"e": 2537,
"s": 2489,
"text": "Following are all the variants of this method −"
},
{
"code": null,
"e": 2612,
"s": 2537,
"text": "double abs(double d)\nfloat abs(float f)\nint abs(int i)\nlong abs(long lng)\n"
},
{
"code": null,
"e": 2647,
"s": 2612,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2672,
"s": 2647,
"text": "Any primitive data type."
},
{
"code": null,
"e": 2728,
"s": 2672,
"text": "This method Returns the absolute value of the argument."
},
{
"code": null,
"e": 2994,
"s": 2728,
"text": "public class Test { \n\n public static void main(String args[]) {\n Integer a = -8;\n double d = -100;\n float f = -90;\n\n System.out.println(Math.abs(a));\n System.out.println(Math.abs(d)); \n System.out.println(Math.abs(f)); \n }\n}"
},
{
"code": null,
"e": 3035,
"s": 2994,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3049,
"s": 3035,
"text": "8\n100.0\n90.0\n"
},
{
"code": null,
"e": 3082,
"s": 3049,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3098,
"s": 3082,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3131,
"s": 3098,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3147,
"s": 3131,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3182,
"s": 3147,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3196,
"s": 3182,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3230,
"s": 3196,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3244,
"s": 3230,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3281,
"s": 3244,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3296,
"s": 3281,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3329,
"s": 3296,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3348,
"s": 3329,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3355,
"s": 3348,
"text": " Print"
},
{
"code": null,
"e": 3366,
"s": 3355,
"text": " Add Notes"
}
] |
How to Setup Compatibility in Microsoft SQL Server?
|
17 Dec, 2021
SQL Server compatibility level is one of the database settings. It helps to keep the database compatible with SQL server versions. By default compatibility level of the database is lower than the SQL server version. It impacts many objects in the server.
For Example: If we are creating a database from scratch on a particular version of SQL server and keeping the database in the same version then we do not have to worry about the compatibility level at all. But if we migrate our application from a lower to a higher version of the SQL server then we have to make sure the compatibility level matches. Otherwise, it may be possible that a few newer features are not supported by the older compatibility level of the database. So, in order to maintain it, we need the compatibility level that matches with the SQL server.
Let’s understand this concept with an example. First, we will create a database and set up its compatibility level with different SQL server versions. Now we will try to set up with the help of UI(without using SQL query) and after that, we will set it up with the help of query.
Step 1: Create a Database
In this step, we will create a database and name it geeksforgeeks. We need to use the CREATE operator.
Query:
CREATE DATABASE geeksforgeeks;
Step 2: Properties and options tab
In order to see the compatibility level of the databases, right-click on the database in Microsoft SQL Server Management Studio and select Properties, then click the Options tab. Go to root-database > right-click > properties > options. Below is the screenshot attached for reference.
Now, you have to click over the options tab in order to see the compatibility level of the particular database. Below is the screenshot for the same.
Step 3: Change the compatibility level
In this step we will change the compatibility level of the database, for this, you can use the drop-down attribute and choose a different compatibility level, and hit the OK button. This will update the compatibility level of your database. See the below image.
Step 4: Output
After saving all the changes when you again follow the above step and check the compatibility level of your database it will be updated. Here, we have updated the compatibility level to 140, below is the screenshot for the same.
In this method, we will update the compatibility level of the database using a SQL query.
Step 1: Checking the compatibility level of the database
First of all, we need to execute a query to see the compatibility level of the databases. For this, we use the following query.
Query:
select name, compatibility_level
from sys.databases;
Output:
This will give the compatibility level of the databases present in the system. Following output is generated.
Step 2: Changing the compatibility level of the database
We can also see that in Method 1, we have updated the compatibility level to 140. Now, we will change the the compatibility level to 120. For this we will use the following query.
Query:
ALTER DATABASE [geeksforgeeks]
SET COMPATIBILITY_LEVEL = 120;
Output:
Step 3: Check updated compatibility
In this step, we will check the updated compatibility level by using the following query.
SELECT compatibility_level FROM
sys.databases WHERE name = 'geeksforgeeks';
Output:
On the execution of the query, we will get the following output with an updated compatibility level for our database geeksforgeeks to 120.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "SQL Server compatibility level is one of the database settings. It helps to keep the database compatible with SQL server versions. By default compatibility level of the database is lower than the SQL server version. It impacts many objects in the server. "
},
{
"code": null,
"e": 853,
"s": 284,
"text": "For Example: If we are creating a database from scratch on a particular version of SQL server and keeping the database in the same version then we do not have to worry about the compatibility level at all. But if we migrate our application from a lower to a higher version of the SQL server then we have to make sure the compatibility level matches. Otherwise, it may be possible that a few newer features are not supported by the older compatibility level of the database. So, in order to maintain it, we need the compatibility level that matches with the SQL server."
},
{
"code": null,
"e": 1133,
"s": 853,
"text": "Let’s understand this concept with an example. First, we will create a database and set up its compatibility level with different SQL server versions. Now we will try to set up with the help of UI(without using SQL query) and after that, we will set it up with the help of query."
},
{
"code": null,
"e": 1159,
"s": 1133,
"text": "Step 1: Create a Database"
},
{
"code": null,
"e": 1262,
"s": 1159,
"text": "In this step, we will create a database and name it geeksforgeeks. We need to use the CREATE operator."
},
{
"code": null,
"e": 1269,
"s": 1262,
"text": "Query:"
},
{
"code": null,
"e": 1300,
"s": 1269,
"text": "CREATE DATABASE geeksforgeeks;"
},
{
"code": null,
"e": 1335,
"s": 1300,
"text": "Step 2: Properties and options tab"
},
{
"code": null,
"e": 1620,
"s": 1335,
"text": "In order to see the compatibility level of the databases, right-click on the database in Microsoft SQL Server Management Studio and select Properties, then click the Options tab. Go to root-database > right-click > properties > options. Below is the screenshot attached for reference."
},
{
"code": null,
"e": 1770,
"s": 1620,
"text": "Now, you have to click over the options tab in order to see the compatibility level of the particular database. Below is the screenshot for the same."
},
{
"code": null,
"e": 1809,
"s": 1770,
"text": "Step 3: Change the compatibility level"
},
{
"code": null,
"e": 2071,
"s": 1809,
"text": "In this step we will change the compatibility level of the database, for this, you can use the drop-down attribute and choose a different compatibility level, and hit the OK button. This will update the compatibility level of your database. See the below image."
},
{
"code": null,
"e": 2086,
"s": 2071,
"text": "Step 4: Output"
},
{
"code": null,
"e": 2315,
"s": 2086,
"text": "After saving all the changes when you again follow the above step and check the compatibility level of your database it will be updated. Here, we have updated the compatibility level to 140, below is the screenshot for the same."
},
{
"code": null,
"e": 2405,
"s": 2315,
"text": "In this method, we will update the compatibility level of the database using a SQL query."
},
{
"code": null,
"e": 2462,
"s": 2405,
"text": "Step 1: Checking the compatibility level of the database"
},
{
"code": null,
"e": 2590,
"s": 2462,
"text": "First of all, we need to execute a query to see the compatibility level of the databases. For this, we use the following query."
},
{
"code": null,
"e": 2597,
"s": 2590,
"text": "Query:"
},
{
"code": null,
"e": 2651,
"s": 2597,
"text": "select name, compatibility_level\n from sys.databases;"
},
{
"code": null,
"e": 2659,
"s": 2651,
"text": "Output:"
},
{
"code": null,
"e": 2769,
"s": 2659,
"text": "This will give the compatibility level of the databases present in the system. Following output is generated."
},
{
"code": null,
"e": 2826,
"s": 2769,
"text": "Step 2: Changing the compatibility level of the database"
},
{
"code": null,
"e": 3006,
"s": 2826,
"text": "We can also see that in Method 1, we have updated the compatibility level to 140. Now, we will change the the compatibility level to 120. For this we will use the following query."
},
{
"code": null,
"e": 3013,
"s": 3006,
"text": "Query:"
},
{
"code": null,
"e": 3076,
"s": 3013,
"text": "ALTER DATABASE [geeksforgeeks] \nSET COMPATIBILITY_LEVEL = 120;"
},
{
"code": null,
"e": 3084,
"s": 3076,
"text": "Output:"
},
{
"code": null,
"e": 3120,
"s": 3084,
"text": "Step 3: Check updated compatibility"
},
{
"code": null,
"e": 3210,
"s": 3120,
"text": "In this step, we will check the updated compatibility level by using the following query."
},
{
"code": null,
"e": 3287,
"s": 3210,
"text": "SELECT compatibility_level FROM \nsys.databases WHERE name = 'geeksforgeeks';"
},
{
"code": null,
"e": 3295,
"s": 3287,
"text": "Output:"
},
{
"code": null,
"e": 3434,
"s": 3295,
"text": "On the execution of the query, we will get the following output with an updated compatibility level for our database geeksforgeeks to 120."
},
{
"code": null,
"e": 3441,
"s": 3434,
"text": "Picked"
},
{
"code": null,
"e": 3452,
"s": 3441,
"text": "SQL-Server"
},
{
"code": null,
"e": 3456,
"s": 3452,
"text": "SQL"
},
{
"code": null,
"e": 3460,
"s": 3456,
"text": "SQL"
}
] |
Scala Map mkString() method with example
|
26 Jul, 2019
The mkString() method is utilized to represent the elements of the map as a string.
Method Definition: def mkString: String
Return Type: It returns the elements of the map as a string.
Example #1:
// Scala program of mkString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 6) // Applying mkString method val result = m1.mkString // Displays output println(result) }}
geeks -> 5for -> 3cs -> 6
Example #2:
// Scala program of mkString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3, "for" -> 3) // Applying mkString method val result = m1.mkString // Displays output println(result) }}
geeks -> 5for -> 3
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala Constructors
Scala | Arrays
Inheritance in Scala
Enumeration in Scala
How to get the first element of List in Scala
Lambda Expression in Scala
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "The mkString() method is utilized to represent the elements of the map as a string."
},
{
"code": null,
"e": 152,
"s": 112,
"text": "Method Definition: def mkString: String"
},
{
"code": null,
"e": 213,
"s": 152,
"text": "Return Type: It returns the elements of the map as a string."
},
{
"code": null,
"e": 225,
"s": 213,
"text": "Example #1:"
},
{
"code": "// Scala program of mkString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"cs\" -> 6) // Applying mkString method val result = m1.mkString // Displays output println(result) }}",
"e": 583,
"s": 225,
"text": null
},
{
"code": null,
"e": 610,
"s": 583,
"text": "geeks -> 5for -> 3cs -> 6\n"
},
{
"code": null,
"e": 622,
"s": 610,
"text": "Example #2:"
},
{
"code": "// Scala program of mkString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"for\" -> 3) // Applying mkString method val result = m1.mkString // Displays output println(result) }}",
"e": 981,
"s": 622,
"text": null
},
{
"code": null,
"e": 1001,
"s": 981,
"text": "geeks -> 5for -> 3\n"
},
{
"code": null,
"e": 1007,
"s": 1001,
"text": "Scala"
},
{
"code": null,
"e": 1017,
"s": 1007,
"text": "Scala-Map"
},
{
"code": null,
"e": 1030,
"s": 1017,
"text": "Scala-Method"
},
{
"code": null,
"e": 1036,
"s": 1030,
"text": "Scala"
},
{
"code": null,
"e": 1134,
"s": 1036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1160,
"s": 1134,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1213,
"s": 1160,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1225,
"s": 1213,
"text": "Scala Lists"
},
{
"code": null,
"e": 1244,
"s": 1225,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1263,
"s": 1244,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1278,
"s": 1263,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1299,
"s": 1278,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 1320,
"s": 1299,
"text": "Enumeration in Scala"
},
{
"code": null,
"e": 1366,
"s": 1320,
"text": "How to get the first element of List in Scala"
}
] |
Narcissistic number
|
30 Apr, 2021
Given N, check whether it is a Narcissistic number or not.Note:Narcissistic Number is a number that is the sum of its own digits each raised to the power of the number of digits
Examples :
Input : 153Output : yesExplanation: 1^3+5^3+3^3=153
Input : 1634Output : yesExplanation: 1^4+6^4+3^4+4^4=1634
The approach will be to count the number of digits and then extract every digit and then by using pow function we can get the power of that digit and then sum it up at the end and compare with the original number to check if it is a Narcissistic Number or not.
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for checking of// Narcissistic number#include <bits/stdc++.h>using namespace std; // function to count digitsint countDigit(int n){ if (n == 0) return 0; return 1 + countDigit(n / 10);} // Returns true if n is Narcissistic numberbool check(int n){ // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of digits // raised to power while (dup) { sum += pow(dup % 10, l); dup /= 10; } return (n == sum);} // Driver codeint main(){ int n = 1634; if (check(n)) cout << "yes"; else cout << "no"; return 0;}
// Java program for checking// of Narcissistic numberimport java.io.*;import static java.lang.Math.*;class narcissistic{ // function to count digitsint countDigit(int n){ if (n == 0) return 0; return 1 + countDigit(n / 10);} // Returns true if n is Narcissistic numberboolean check(int n){ // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of //digits raised to power while(dup > 0) { sum += pow(dup % 10, l); dup /= 10; } return (n == sum);} // Driver codepublic static void main(String args[]) { narcissistic obj = new narcissistic(); int n = 1634; if (obj.check(n)) System.out.println("yes"); else System.out.println("no"); }} //This code is contributed by Anshika Goyal.
# Python 3 program for checking of# Narcissistic number # function to count digitsdef countDigit(n) : if (n == 0) : return 0 return (1 + countDigit(n // 10)) # Returns true if n is Narcissistic numberdef check(n) : # Count the number of digits l = countDigit(n) dup = n; sm = 0 # Calculates the sum of digits # raised to power while (dup) : sm = sm + pow(dup % 10, l) dup = dup // 10 return (n == sm) # Driver coden = 1634if (check(n)) : print( "yes")else : print( "no") # This code is contributed by Nikita Tiwari.
// C# program for checking// of Narcissistic numberusing System; class narcissistic{ // function to count digits int countDigit(int n) { if (n == 0) return 0; return 1 + countDigit(n / 10); } // Returns true if n is Narcissistic number bool check(int n) { // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of //digits raised to power while(dup > 0) { sum += (int)Math.Pow(dup % 10, l); dup /= 10; } return (n == sum); } // Driver code public static void Main() { narcissistic obj = new narcissistic(); int n = 1634; if (obj.check(n)) Console.WriteLine("yes"); else Console.WriteLine("no"); }} // This code is contributed by vt_m.
<?php// PHP program for checking of// Narcissistic number // Function to count digitsfunction countDigit($n){ if ($n == 0) return 0; return (1 + countDigit($n / 10));} // Returns true if n is// Narcissistic numberfunction check( $n){ // count the number of digits $l = countDigit($n); $dup = $n; $sum = 0; // calculates the sum of digits // raised to power while ($dup) { $sum += pow($dup % 10, $l); $dup = (int)$dup / 10; } return ($n == $sum);} // Driver Code$n = 1634;if (check(!$n)) echo "yes";else echo "no"; // This code is contributed by akt_mit?>
<script> // Javascript program for checking of// Narcissistic number // Function to count digitsfunction countDigit(n){ if (n == 0) return 0; return (1 + countDigit(n / 10));} // Returns true if n is// Narcissistic numberfunction check( n){ // count the number of digits let l = countDigit(n); let dup = n; let sum = 0; // calculates the sum of digits // raised to power while (dup) { sum += Math.pow(dup % 10, l); dup = parseINT(dup / 10); } return (n == sum);} // Driver Codelet n = 1634;if (check(!n)) document.write("yes");else document.write("no"); // This code is contributed by _saurabh_jaiswal</script>
yes
Method 2: Simplified Method using string
We have to take input as a string and traverse through string computing power of each character with the length of the string. Note: Here length of the string gives the number of digits of that number
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// CPP program for checking of// Narcissistic number#include <bits/stdc++.h>#include <string.h>using namespace std; string getResult(string st){ int sum = 0; int length = st.length(); // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + pow(st[i] - '0', length); } // Converting string to integer int number = stoi(st); // Comparing number and sum if (number == sum) return "yes"; else return "no";} // Driver Codeint main(){ string st = "153"; cout << getResult(st); return 0;}
// Java program for checking of// Narcissistic numberclass GFG{ static String getResult(String st){ int sum = 0; int length = st.length(); // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + (int)Math.pow(st.charAt(i) - '0', length); } // Converting string to integer int number = Integer.parseInt(st); // Comparing number and sum if (number == sum) return "yes"; else return "no";} // Driver Codepublic static void main(String []args){ String st = "153"; System.out.print(getResult(st));}} // This code is contributed by rutvik_56.
# Python program for checking of# Narcissistic number def getResult(st): sum = 0 length = len(st) # Traversing through the string for i in st: # Converting character to int sum = sum + int(i) ** length # Converting string to integer number = int(st) # Comparing number and sum if (number == sum): return "true" else: return "false" # Driver Code# taking input as stringst = "153"print(getResult(st))
// C# program for checking of// Narcissistic numberusing System;class GFG{ static string getResult(string st){ int sum = 0; int length = st.Length; // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + (int)Math.Pow(st[i] - '0', length); } // Converting string to integer int number = int.Parse(st); // Comparing number and sum if (number == sum) return "yes"; else return "no";} // Driver Codepublic static void Main(string []args){ string st = "153"; Console.Write(getResult(st));}} // This code is contributed by pratham76.
<script> // Javascript program for checking of // Narcissistic number function getResult(st) { let sum = 0; let length = st.length; // Traversing through the string for (let i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + Math.pow(st[i] - '0', length); } // Converting string to integer let number = parseInt(st, 10); // Comparing number and sum if (number == sum) return "yes"; else return "no"; } let st = "153"; document.write(getResult(st)); </script>
yes
References: http://mathandmultimedia.com/2012/01/16/narcissistic-numbers/
jit_t
vikkycirus
rutvik_56
pratham76
_saurabh_jaiswal
mukesh07
number-digits
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 231,
"s": 53,
"text": "Given N, check whether it is a Narcissistic number or not.Note:Narcissistic Number is a number that is the sum of its own digits each raised to the power of the number of digits"
},
{
"code": null,
"e": 244,
"s": 231,
"text": "Examples : "
},
{
"code": null,
"e": 297,
"s": 244,
"text": "Input : 153Output : yesExplanation: 1^3+5^3+3^3=153 "
},
{
"code": null,
"e": 356,
"s": 297,
"text": "Input : 1634Output : yesExplanation: 1^4+6^4+3^4+4^4=1634 "
},
{
"code": null,
"e": 617,
"s": 356,
"text": "The approach will be to count the number of digits and then extract every digit and then by using pow function we can get the power of that digit and then sum it up at the end and compare with the original number to check if it is a Narcissistic Number or not."
},
{
"code": null,
"e": 664,
"s": 617,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 668,
"s": 664,
"text": "C++"
},
{
"code": null,
"e": 673,
"s": 668,
"text": "Java"
},
{
"code": null,
"e": 681,
"s": 673,
"text": "Python3"
},
{
"code": null,
"e": 684,
"s": 681,
"text": "C#"
},
{
"code": null,
"e": 688,
"s": 684,
"text": "PHP"
},
{
"code": null,
"e": 699,
"s": 688,
"text": "Javascript"
},
{
"code": "// CPP program for checking of// Narcissistic number#include <bits/stdc++.h>using namespace std; // function to count digitsint countDigit(int n){ if (n == 0) return 0; return 1 + countDigit(n / 10);} // Returns true if n is Narcissistic numberbool check(int n){ // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of digits // raised to power while (dup) { sum += pow(dup % 10, l); dup /= 10; } return (n == sum);} // Driver codeint main(){ int n = 1634; if (check(n)) cout << \"yes\"; else cout << \"no\"; return 0;}",
"e": 1349,
"s": 699,
"text": null
},
{
"code": "// Java program for checking// of Narcissistic numberimport java.io.*;import static java.lang.Math.*;class narcissistic{ // function to count digitsint countDigit(int n){ if (n == 0) return 0; return 1 + countDigit(n / 10);} // Returns true if n is Narcissistic numberboolean check(int n){ // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of //digits raised to power while(dup > 0) { sum += pow(dup % 10, l); dup /= 10; } return (n == sum);} // Driver codepublic static void main(String args[]) { narcissistic obj = new narcissistic(); int n = 1634; if (obj.check(n)) System.out.println(\"yes\"); else System.out.println(\"no\"); }} //This code is contributed by Anshika Goyal.",
"e": 2167,
"s": 1349,
"text": null
},
{
"code": "# Python 3 program for checking of# Narcissistic number # function to count digitsdef countDigit(n) : if (n == 0) : return 0 return (1 + countDigit(n // 10)) # Returns true if n is Narcissistic numberdef check(n) : # Count the number of digits l = countDigit(n) dup = n; sm = 0 # Calculates the sum of digits # raised to power while (dup) : sm = sm + pow(dup % 10, l) dup = dup // 10 return (n == sm) # Driver coden = 1634if (check(n)) : print( \"yes\")else : print( \"no\") # This code is contributed by Nikita Tiwari.",
"e": 2769,
"s": 2167,
"text": null
},
{
"code": "// C# program for checking// of Narcissistic numberusing System; class narcissistic{ // function to count digits int countDigit(int n) { if (n == 0) return 0; return 1 + countDigit(n / 10); } // Returns true if n is Narcissistic number bool check(int n) { // count the number of digits int l = countDigit(n); int dup = n; int sum = 0; // calculates the sum of //digits raised to power while(dup > 0) { sum += (int)Math.Pow(dup % 10, l); dup /= 10; } return (n == sum); } // Driver code public static void Main() { narcissistic obj = new narcissistic(); int n = 1634; if (obj.check(n)) Console.WriteLine(\"yes\"); else Console.WriteLine(\"no\"); }} // This code is contributed by vt_m.",
"e": 3679,
"s": 2769,
"text": null
},
{
"code": "<?php// PHP program for checking of// Narcissistic number // Function to count digitsfunction countDigit($n){ if ($n == 0) return 0; return (1 + countDigit($n / 10));} // Returns true if n is// Narcissistic numberfunction check( $n){ // count the number of digits $l = countDigit($n); $dup = $n; $sum = 0; // calculates the sum of digits // raised to power while ($dup) { $sum += pow($dup % 10, $l); $dup = (int)$dup / 10; } return ($n == $sum);} // Driver Code$n = 1634;if (check(!$n)) echo \"yes\";else echo \"no\"; // This code is contributed by akt_mit?>",
"e": 4300,
"s": 3679,
"text": null
},
{
"code": "<script> // Javascript program for checking of// Narcissistic number // Function to count digitsfunction countDigit(n){ if (n == 0) return 0; return (1 + countDigit(n / 10));} // Returns true if n is// Narcissistic numberfunction check( n){ // count the number of digits let l = countDigit(n); let dup = n; let sum = 0; // calculates the sum of digits // raised to power while (dup) { sum += Math.pow(dup % 10, l); dup = parseINT(dup / 10); } return (n == sum);} // Driver Codelet n = 1634;if (check(!n)) document.write(\"yes\");else document.write(\"no\"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 4984,
"s": 4300,
"text": null
},
{
"code": null,
"e": 4991,
"s": 4987,
"text": "yes"
},
{
"code": null,
"e": 5034,
"s": 4993,
"text": "Method 2: Simplified Method using string"
},
{
"code": null,
"e": 5237,
"s": 5036,
"text": "We have to take input as a string and traverse through string computing power of each character with the length of the string. Note: Here length of the string gives the number of digits of that number"
},
{
"code": null,
"e": 5289,
"s": 5239,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 5297,
"s": 5291,
"text": "C++14"
},
{
"code": null,
"e": 5302,
"s": 5297,
"text": "Java"
},
{
"code": null,
"e": 5310,
"s": 5302,
"text": "Python3"
},
{
"code": null,
"e": 5313,
"s": 5310,
"text": "C#"
},
{
"code": null,
"e": 5324,
"s": 5313,
"text": "Javascript"
},
{
"code": "// CPP program for checking of// Narcissistic number#include <bits/stdc++.h>#include <string.h>using namespace std; string getResult(string st){ int sum = 0; int length = st.length(); // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + pow(st[i] - '0', length); } // Converting string to integer int number = stoi(st); // Comparing number and sum if (number == sum) return \"yes\"; else return \"no\";} // Driver Codeint main(){ string st = \"153\"; cout << getResult(st); return 0;}",
"e": 5999,
"s": 5324,
"text": null
},
{
"code": "// Java program for checking of// Narcissistic numberclass GFG{ static String getResult(String st){ int sum = 0; int length = st.length(); // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + (int)Math.pow(st.charAt(i) - '0', length); } // Converting string to integer int number = Integer.parseInt(st); // Comparing number and sum if (number == sum) return \"yes\"; else return \"no\";} // Driver Codepublic static void main(String []args){ String st = \"153\"; System.out.print(getResult(st));}} // This code is contributed by rutvik_56.",
"e": 6733,
"s": 5999,
"text": null
},
{
"code": "# Python program for checking of# Narcissistic number def getResult(st): sum = 0 length = len(st) # Traversing through the string for i in st: # Converting character to int sum = sum + int(i) ** length # Converting string to integer number = int(st) # Comparing number and sum if (number == sum): return \"true\" else: return \"false\" # Driver Code# taking input as stringst = \"153\"print(getResult(st))",
"e": 7194,
"s": 6733,
"text": null
},
{
"code": "// C# program for checking of// Narcissistic numberusing System;class GFG{ static string getResult(string st){ int sum = 0; int length = st.Length; // Traversing through the string for (int i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + (int)Math.Pow(st[i] - '0', length); } // Converting string to integer int number = int.Parse(st); // Comparing number and sum if (number == sum) return \"yes\"; else return \"no\";} // Driver Codepublic static void Main(string []args){ string st = \"153\"; Console.Write(getResult(st));}} // This code is contributed by pratham76.",
"e": 7920,
"s": 7194,
"text": null
},
{
"code": "<script> // Javascript program for checking of // Narcissistic number function getResult(st) { let sum = 0; let length = st.length; // Traversing through the string for (let i = 0; i < length; i++) { // Since ascii value of numbers // starts from 48 so we subtract it from sum sum = sum + Math.pow(st[i] - '0', length); } // Converting string to integer let number = parseInt(st, 10); // Comparing number and sum if (number == sum) return \"yes\"; else return \"no\"; } let st = \"153\"; document.write(getResult(st)); </script>",
"e": 8614,
"s": 7920,
"text": null
},
{
"code": null,
"e": 8621,
"s": 8617,
"text": "yes"
},
{
"code": null,
"e": 8699,
"s": 8623,
"text": " References: http://mathandmultimedia.com/2012/01/16/narcissistic-numbers/ "
},
{
"code": null,
"e": 8707,
"s": 8701,
"text": "jit_t"
},
{
"code": null,
"e": 8718,
"s": 8707,
"text": "vikkycirus"
},
{
"code": null,
"e": 8728,
"s": 8718,
"text": "rutvik_56"
},
{
"code": null,
"e": 8738,
"s": 8728,
"text": "pratham76"
},
{
"code": null,
"e": 8755,
"s": 8738,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 8764,
"s": 8755,
"text": "mukesh07"
},
{
"code": null,
"e": 8778,
"s": 8764,
"text": "number-digits"
},
{
"code": null,
"e": 8792,
"s": 8778,
"text": "number-theory"
},
{
"code": null,
"e": 8805,
"s": 8792,
"text": "Mathematical"
},
{
"code": null,
"e": 8819,
"s": 8805,
"text": "number-theory"
},
{
"code": null,
"e": 8832,
"s": 8819,
"text": "Mathematical"
},
{
"code": null,
"e": 8930,
"s": 8832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8954,
"s": 8930,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 8975,
"s": 8954,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 8997,
"s": 8975,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 9011,
"s": 8997,
"text": "Prime Numbers"
},
{
"code": null,
"e": 9053,
"s": 9011,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 9090,
"s": 9053,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 9143,
"s": 9090,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9186,
"s": 9143,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 9218,
"s": 9186,
"text": "Algorithm to solve Rubik's Cube"
}
] |
Oracle India Pvt Ltd Interview Experience for Full Stack Java Developer
|
03 Mar, 2021
Round 1(Online Assessment and Coding Challenge–90 minutes): This assessment consisted of two different online programmatic sets of coding challenges and both are important and have to answer them.
Expectations:
Ability to identify problem types and apply conventionally known techniques to solve them.
Usage of optimal Data Structures for the problem statement
Demoable code
Functional Correctness and Completeness
Modularity and Extensibility
Good understanding of Java/ J2EE, Spring Boot, Restful Services & Webservices, Kubernetes, and PL/SQL (SQL is also ok)
1. Java/ J2EE (Online Assessment 30 minutes): This section contains three different types of programmatic skills, and each one has a different set of questions. Each Section has multiple choice question which needs to answer, and there is no negative marking.
Java (12 MCQ): This assessment includes basic understanding of core java, which contain 12 multiple choice question and will need to complete in 12 minutes.
Expectations:
Basic Knowledge of java programming
Multithreading
Exception Handling
Inheritance
Java 8 Functionality
Overloading
J2EE(8 MCQ): This assessment includes a basic understanding of J2EE concepts, which contain 8 multiple choice questions and will need to complete within 8 minutes.
Expectations:
Java Servlets.
JavaServer Pages (JSP)
Enterprise JavaBeans (EJB)
Java Message Service (JMS)
Java Naming and Directory Interface (JNDI)
Java Database Connectivity (JDBC)
Restful Services & Webservices(12 MCQ): This assessment includes a basic understanding of Restful Services & Webservices concepts, which contain 12 multiple choice questions and will need to complete within 12 minutes.
Expectations:
Basic understanding of SOAP
Basic Understanding of Restful
Basic Understanding of JSON
Request Headers
Resources
Request Body
Response Status codes
POST,GET, PUT and DELETE Method
2. Oracle Coding Challenge (60 mins): This assignment contains two different sets of programming questions, which need to complete in 60 minutes. Each one will be challenging, and need to choose the strategy to solve this problem wisely, as time is only 60 minutes.
Expectations:
How good is your algorithm, technique you apply to make the app faster, etc?
Scalability
Testability
Design patterns
Demoable code
Clear Separation of Concerns (Good Class Design)
Functional Correctness and Completeness
Readability
Modularity and Extensibility
Exception handling
Task 1: Girls in Tech Hackathon
Problem Statement:
The Girl in Tech Hackathon is code-a-thon where developers, designers, scientists, students, entrepreneurs, and educators gather to collaborate on projects including applications, software, hardware, data visualization, and platform solutions. The Participants are sitting around the table, and they are numbered from team1 to team n in the clockwise direction. This means that the Participants are numbered 1,2, ..,n-1,n and participants 1 and n are sitting next to each other. After the Hackathon duration, judges started reviewing the performance of each participant. However, some participants have not finished the project. Each participant needs ti extra minute to complete their project. Judges started reviewing the projects sequentially in the clock direction, starting with team x, and it takes them exactly 1 minute to review each project. This means team x gets no extra time to work, whereas team x +1 gets 1 min more to work and so on. Even if the project is not completed by the participant, but still the judges spend 1 min to understand the idea and rank the participant.
Input Format:
The first line contains a single positive integer, n, denoting the number of participants in the hackathon. Given the values of t1,t2, t3,... tn extra time requires by each participant to complete the project. You have to guide judges in selecting the best team x to start reviewing the project so that number of participants able to complete their project is maximal.
Output Format:
Print x on a new line. If there are multiple such teams,
select the smallest one.
Constraints:
1<=n<=9*10^5
0<=ti<=n
Sample Input:
3
1 0 0
Sample Output:
2
Java
import java.io.BufferReader;import java.io.InputStreamReader; Class Test{ /* Read input from stdin and provide input before * running*/ BufferedReader br = new BufferedReader( new InputStreamReader(System.in)) String line = br.readLine(); for (int i = 0; i < N; i++) { System.out.println(“Hello Word”); }}
Task 2: Stella and colorful tree
Problem Statement:
While returning from Byteland, Stella got one tree with N nodes from her friend over there. All nodes in this tree are colorless and Stella decided to fill colors to make it colorful. Stella wants it to look beautiful and decided to color it in such a way that any 2 nodes u and v with the shortest distance between u and v <=2 can not be of the same color. She is wondering how many different colors she needs if she fills optimally.
Input Format:
The first line contains a single integer n ( 3 <=n<100) – the number of nodes in the tree. Each of the next(n-1) lines contains two integers x and y(1<=x, y<=n) – the indices of two nodes directly connected by an edge. It is guaranteed that any node is reachable from any other using the edges.
Output Format:
In the first line print single integer k – the minimum number of colors Stell has to use.
Sample Input 1:
3
2 3
1 3
Sample Output 1:
3
Explanation Output 1:
Tree is like
1 -> 3 ->2
We can color as follows
1: Color a
3: Color b
2 : Color c
Total 3 colors
Sample Input 2:
5
2 1
3 2
4 3
5 4
Sample Output 2
3
Explanation Output2:
Tree is like:
1 -> 2 ->3 -> 4 -> 5
We can color as follows
1: Color a
2: Color b
3 : Color c
4: Color a
5 : Color b
Total 3 colors.
Java
import java.io.BufferReader;import java.io.InputStreamReader; Class Test { /* Read input from stdin and provide input before running*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) String line = br.readLine(); for (int i =0 ; i< N; i++){ System.out.println(“Hello Word”); } }
Marketing
Oracle
Interview Experiences
Oracle
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 249,
"s": 52,
"text": "Round 1(Online Assessment and Coding Challenge–90 minutes): This assessment consisted of two different online programmatic sets of coding challenges and both are important and have to answer them."
},
{
"code": null,
"e": 263,
"s": 249,
"text": "Expectations:"
},
{
"code": null,
"e": 354,
"s": 263,
"text": "Ability to identify problem types and apply conventionally known techniques to solve them."
},
{
"code": null,
"e": 413,
"s": 354,
"text": "Usage of optimal Data Structures for the problem statement"
},
{
"code": null,
"e": 427,
"s": 413,
"text": "Demoable code"
},
{
"code": null,
"e": 467,
"s": 427,
"text": "Functional Correctness and Completeness"
},
{
"code": null,
"e": 496,
"s": 467,
"text": "Modularity and Extensibility"
},
{
"code": null,
"e": 615,
"s": 496,
"text": "Good understanding of Java/ J2EE, Spring Boot, Restful Services & Webservices, Kubernetes, and PL/SQL (SQL is also ok)"
},
{
"code": null,
"e": 895,
"s": 615,
"text": " 1. Java/ J2EE (Online Assessment 30 minutes): This section contains three different types of programmatic skills, and each one has a different set of questions. Each Section has multiple choice question which needs to answer, and there is no negative marking. "
},
{
"code": null,
"e": 1052,
"s": 895,
"text": "Java (12 MCQ): This assessment includes basic understanding of core java, which contain 12 multiple choice question and will need to complete in 12 minutes."
},
{
"code": null,
"e": 1068,
"s": 1052,
"text": " Expectations:"
},
{
"code": null,
"e": 1104,
"s": 1068,
"text": "Basic Knowledge of java programming"
},
{
"code": null,
"e": 1119,
"s": 1104,
"text": "Multithreading"
},
{
"code": null,
"e": 1138,
"s": 1119,
"text": "Exception Handling"
},
{
"code": null,
"e": 1150,
"s": 1138,
"text": "Inheritance"
},
{
"code": null,
"e": 1171,
"s": 1150,
"text": "Java 8 Functionality"
},
{
"code": null,
"e": 1183,
"s": 1171,
"text": "Overloading"
},
{
"code": null,
"e": 1347,
"s": 1183,
"text": "J2EE(8 MCQ): This assessment includes a basic understanding of J2EE concepts, which contain 8 multiple choice questions and will need to complete within 8 minutes."
},
{
"code": null,
"e": 1361,
"s": 1347,
"text": "Expectations:"
},
{
"code": null,
"e": 1376,
"s": 1361,
"text": "Java Servlets."
},
{
"code": null,
"e": 1399,
"s": 1376,
"text": "JavaServer Pages (JSP)"
},
{
"code": null,
"e": 1426,
"s": 1399,
"text": "Enterprise JavaBeans (EJB)"
},
{
"code": null,
"e": 1453,
"s": 1426,
"text": "Java Message Service (JMS)"
},
{
"code": null,
"e": 1496,
"s": 1453,
"text": "Java Naming and Directory Interface (JNDI)"
},
{
"code": null,
"e": 1530,
"s": 1496,
"text": "Java Database Connectivity (JDBC)"
},
{
"code": null,
"e": 1749,
"s": 1530,
"text": "Restful Services & Webservices(12 MCQ): This assessment includes a basic understanding of Restful Services & Webservices concepts, which contain 12 multiple choice questions and will need to complete within 12 minutes."
},
{
"code": null,
"e": 1763,
"s": 1749,
"text": "Expectations:"
},
{
"code": null,
"e": 1791,
"s": 1763,
"text": "Basic understanding of SOAP"
},
{
"code": null,
"e": 1822,
"s": 1791,
"text": "Basic Understanding of Restful"
},
{
"code": null,
"e": 1850,
"s": 1822,
"text": "Basic Understanding of JSON"
},
{
"code": null,
"e": 1866,
"s": 1850,
"text": "Request Headers"
},
{
"code": null,
"e": 1876,
"s": 1866,
"text": "Resources"
},
{
"code": null,
"e": 1889,
"s": 1876,
"text": "Request Body"
},
{
"code": null,
"e": 1911,
"s": 1889,
"text": "Response Status codes"
},
{
"code": null,
"e": 1944,
"s": 1911,
"text": "POST,GET, PUT and DELETE Method"
},
{
"code": null,
"e": 2214,
"s": 1944,
"text": " 2. Oracle Coding Challenge (60 mins): This assignment contains two different sets of programming questions, which need to complete in 60 minutes. Each one will be challenging, and need to choose the strategy to solve this problem wisely, as time is only 60 minutes."
},
{
"code": null,
"e": 2228,
"s": 2214,
"text": "Expectations:"
},
{
"code": null,
"e": 2305,
"s": 2228,
"text": "How good is your algorithm, technique you apply to make the app faster, etc?"
},
{
"code": null,
"e": 2317,
"s": 2305,
"text": "Scalability"
},
{
"code": null,
"e": 2329,
"s": 2317,
"text": "Testability"
},
{
"code": null,
"e": 2345,
"s": 2329,
"text": "Design patterns"
},
{
"code": null,
"e": 2359,
"s": 2345,
"text": "Demoable code"
},
{
"code": null,
"e": 2408,
"s": 2359,
"text": "Clear Separation of Concerns (Good Class Design)"
},
{
"code": null,
"e": 2448,
"s": 2408,
"text": "Functional Correctness and Completeness"
},
{
"code": null,
"e": 2460,
"s": 2448,
"text": "Readability"
},
{
"code": null,
"e": 2489,
"s": 2460,
"text": "Modularity and Extensibility"
},
{
"code": null,
"e": 2508,
"s": 2489,
"text": "Exception handling"
},
{
"code": null,
"e": 2540,
"s": 2508,
"text": "Task 1: Girls in Tech Hackathon"
},
{
"code": null,
"e": 2559,
"s": 2540,
"text": "Problem Statement:"
},
{
"code": null,
"e": 3656,
"s": 2559,
"text": " The Girl in Tech Hackathon is code-a-thon where developers, designers, scientists, students, entrepreneurs, and educators gather to collaborate on projects including applications, software, hardware, data visualization, and platform solutions. The Participants are sitting around the table, and they are numbered from team1 to team n in the clockwise direction. This means that the Participants are numbered 1,2, ..,n-1,n and participants 1 and n are sitting next to each other. After the Hackathon duration, judges started reviewing the performance of each participant. However, some participants have not finished the project. Each participant needs ti extra minute to complete their project. Judges started reviewing the projects sequentially in the clock direction, starting with team x, and it takes them exactly 1 minute to review each project. This means team x gets no extra time to work, whereas team x +1 gets 1 min more to work and so on. Even if the project is not completed by the participant, but still the judges spend 1 min to understand the idea and rank the participant."
},
{
"code": null,
"e": 3670,
"s": 3656,
"text": "Input Format:"
},
{
"code": null,
"e": 4048,
"s": 3670,
"text": " The first line contains a single positive integer, n, denoting the number of participants in the hackathon. Given the values of t1,t2, t3,... tn extra time requires by each participant to complete the project. You have to guide judges in selecting the best team x to start reviewing the project so that number of participants able to complete their project is maximal."
},
{
"code": null,
"e": 4063,
"s": 4048,
"text": "Output Format:"
},
{
"code": null,
"e": 4222,
"s": 4063,
"text": "Print x on a new line. If there are multiple such teams, \nselect the smallest one.\nConstraints:\n1<=n<=9*10^5\n0<=ti<=n\nSample Input:\n 3\n1 0 0\nSample Output:\n 2"
},
{
"code": null,
"e": 4227,
"s": 4222,
"text": "Java"
},
{
"code": "import java.io.BufferReader;import java.io.InputStreamReader; Class Test{ /* Read input from stdin and provide input before * running*/ BufferedReader br = new BufferedReader( new InputStreamReader(System.in)) String line = br.readLine(); for (int i = 0; i < N; i++) { System.out.println(“Hello Word”); }}",
"e": 4575,
"s": 4227,
"text": null
},
{
"code": null,
"e": 4612,
"s": 4579,
"text": "Task 2: Stella and colorful tree"
},
{
"code": null,
"e": 4632,
"s": 4612,
"text": "Problem Statement: "
},
{
"code": null,
"e": 5074,
"s": 4632,
"text": " While returning from Byteland, Stella got one tree with N nodes from her friend over there. All nodes in this tree are colorless and Stella decided to fill colors to make it colorful. Stella wants it to look beautiful and decided to color it in such a way that any 2 nodes u and v with the shortest distance between u and v <=2 can not be of the same color. She is wondering how many different colors she needs if she fills optimally."
},
{
"code": null,
"e": 5089,
"s": 5074,
"text": " Input Format:"
},
{
"code": null,
"e": 5393,
"s": 5089,
"text": " The first line contains a single integer n ( 3 <=n<100) – the number of nodes in the tree. Each of the next(n-1) lines contains two integers x and y(1<=x, y<=n) – the indices of two nodes directly connected by an edge. It is guaranteed that any node is reachable from any other using the edges."
},
{
"code": null,
"e": 5408,
"s": 5393,
"text": "Output Format:"
},
{
"code": null,
"e": 5508,
"s": 5408,
"text": " In the first line print single integer k – the minimum number of colors Stell has to use."
},
{
"code": null,
"e": 6123,
"s": 5508,
"text": "Sample Input 1:\n 3\n 2 3\n 1 3\nSample Output 1:\n 3\n Explanation Output 1:\n Tree is like\n 1 -> 3 ->2\nWe can color as follows\n 1: Color a\n 3: Color b\n 2 : Color c\n Total 3 colors\nSample Input 2:\n 5\n 2 1\n 3 2\n 4 3\n 5 4\nSample Output 2\n 3\nExplanation Output2: \n Tree is like:\n 1 -> 2 ->3 -> 4 -> 5\n We can color as follows\n 1: Color a\n 2: Color b\n 3 : Color c\n 4: Color a\n 5 : Color b\n Total 3 colors."
},
{
"code": null,
"e": 6134,
"s": 6129,
"text": "Java"
},
{
"code": "import java.io.BufferReader;import java.io.InputStreamReader; Class Test { /* Read input from stdin and provide input before running*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) String line = br.readLine(); for (int i =0 ; i< N; i++){ System.out.println(“Hello Word”); } }",
"e": 6450,
"s": 6134,
"text": null
},
{
"code": null,
"e": 6460,
"s": 6450,
"text": "Marketing"
},
{
"code": null,
"e": 6467,
"s": 6460,
"text": "Oracle"
},
{
"code": null,
"e": 6489,
"s": 6467,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6496,
"s": 6489,
"text": "Oracle"
}
] |
Material Design Buttons using Jetpack Compose in Android
|
16 Nov, 2021
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain how you can create Material design buttons using Jetpack Compose. Below is the sample picture to show what we are going to build.
Step 1: Create a new project
To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.*import androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.FavoriteBorderimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using the 'background' color from the theme Surface(color = Color.White) { Column { // call the function which contains all the buttons allButtons() } } } } }}// In order to use compose properties annotate with @Compose@Composablefun allButtons() { Text(text = "Buttons", style = typography.h5, modifier = Modifier.padding(8.dp)) // Here we are using Row to add // two buttons in single Column // You can change it as per your need Row { // Create a Main Button or Normal Button Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = "Main Button") } // Create a Text Button TextButton(onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp)) { Text(text = "Text Button") } } Row { // Elevated Button Button( onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp), elevation = ButtonDefaults.elevation() ) { Text(text = "Elevated Button") } // Rounded Button Button( onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp), shape = RoundedCornerShape(20.dp) ) { Text(text = "Rounded") } } Row { // Outlined Button // add border field and set BorderStroke and its color OutlinedButton( onClick = { /*TODO*/ }, border = BorderStroke(1.dp, Color.Red), modifier = Modifier.padding(8.dp) ) { Text(text = "Outlined") } // Outlined Button with icon // add border field and set BorderStroke and its color // add Icon field OutlinedButton( onClick = { /*TODO*/ }, border = BorderStroke(1.dp, Color.Red), modifier = Modifier.padding(8.dp) ) { Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) Text(text = "Outlined Icon") } } Row { // Icon Button // Icon on the left of text Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Row { Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) Text(text = "Icon Button") } } // Icon Button // Icon on the Right of text Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = "Icon Button") Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(start = 4.dp) ) } } //custom background buttons // create a variable mainButtonColor and define background Color and content Color val mainButtonColor = ButtonDefaults.buttonColors( backgroundColor = Color.Magenta, contentColor = MaterialTheme.colors.surface ) Row { Button(colors = mainButtonColor, onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = "Custom colors") } } Row { // Create variable horizontalGradient and inside color property define start and end color val horizontalGradient = Brush.horizontalGradient( colors = listOf(MaterialTheme.colors.primary, MaterialTheme.colors.primaryVariant), 0f, 250f ) // Horizontal gradient Button // Create a text and set its background to horizontalGradient that we created above Text( text = "Horizontal gradient", style = typography.body2.copy(color = Color.White), modifier = Modifier .padding(12.dp) .clickable(onClick = {}) .clip(RoundedCornerShape(4.dp)) .background(brush = horizontalGradient) .padding(12.dp) ) // Create variable verticalGradient and inside color property define top and bottom color val verticalGradient = Brush.verticalGradient( colors = listOf(MaterialTheme.colors.primary, MaterialTheme.colors.primaryVariant), startY = 0f, endY = 100f ) // Vertical gradient Button // Create a text and set its background to verticalGradient that we created above Text( text = "Vertical gradient", style = typography.body1.copy(color = Color.White), modifier = Modifier .padding(12.dp) .clickable(onClick = {}) .clip(RoundedCornerShape(4.dp)) .background(brush = verticalGradient) .padding(12.dp) ) } }// To see the preview annotate with @Preview to the function@Preview@Composablefun DefaultPreview() { JetpackComposePracticeTheme { Column { allButtons() } }}
Output:
sumitgumber28
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Implicit Intent and Explicit Intent in Android
Retrofit with Kotlin Coroutine in Android
Flutter - BoxShadow Widget
Bundle in Android with Example
Animation in Android with Example
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Bundle in Android with Example
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 511,
"s": 28,
"text": "Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain how you can create Material design buttons using Jetpack Compose. Below is the sample picture to show what we are going to build. "
},
{
"code": null,
"e": 540,
"s": 511,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 704,
"s": 540,
"text": "To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose. "
},
{
"code": null,
"e": 741,
"s": 704,
"text": "Step 2: Working with MainActivity.kt"
},
{
"code": null,
"e": 927,
"s": 741,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 934,
"s": 927,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.*import androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.FavoriteBorderimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using the 'background' color from the theme Surface(color = Color.White) { Column { // call the function which contains all the buttons allButtons() } } } } }}// In order to use compose properties annotate with @Compose@Composablefun allButtons() { Text(text = \"Buttons\", style = typography.h5, modifier = Modifier.padding(8.dp)) // Here we are using Row to add // two buttons in single Column // You can change it as per your need Row { // Create a Main Button or Normal Button Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = \"Main Button\") } // Create a Text Button TextButton(onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp)) { Text(text = \"Text Button\") } } Row { // Elevated Button Button( onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp), elevation = ButtonDefaults.elevation() ) { Text(text = \"Elevated Button\") } // Rounded Button Button( onClick = { /*TODO*/ }, modifier = Modifier.padding(8.dp), shape = RoundedCornerShape(20.dp) ) { Text(text = \"Rounded\") } } Row { // Outlined Button // add border field and set BorderStroke and its color OutlinedButton( onClick = { /*TODO*/ }, border = BorderStroke(1.dp, Color.Red), modifier = Modifier.padding(8.dp) ) { Text(text = \"Outlined\") } // Outlined Button with icon // add border field and set BorderStroke and its color // add Icon field OutlinedButton( onClick = { /*TODO*/ }, border = BorderStroke(1.dp, Color.Red), modifier = Modifier.padding(8.dp) ) { Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) Text(text = \"Outlined Icon\") } } Row { // Icon Button // Icon on the left of text Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Row { Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) Text(text = \"Icon Button\") } } // Icon Button // Icon on the Right of text Button(onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = \"Icon Button\") Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = null, modifier = Modifier.padding(start = 4.dp) ) } } //custom background buttons // create a variable mainButtonColor and define background Color and content Color val mainButtonColor = ButtonDefaults.buttonColors( backgroundColor = Color.Magenta, contentColor = MaterialTheme.colors.surface ) Row { Button(colors = mainButtonColor, onClick = {}, modifier = Modifier.padding(8.dp)) { Text(text = \"Custom colors\") } } Row { // Create variable horizontalGradient and inside color property define start and end color val horizontalGradient = Brush.horizontalGradient( colors = listOf(MaterialTheme.colors.primary, MaterialTheme.colors.primaryVariant), 0f, 250f ) // Horizontal gradient Button // Create a text and set its background to horizontalGradient that we created above Text( text = \"Horizontal gradient\", style = typography.body2.copy(color = Color.White), modifier = Modifier .padding(12.dp) .clickable(onClick = {}) .clip(RoundedCornerShape(4.dp)) .background(brush = horizontalGradient) .padding(12.dp) ) // Create variable verticalGradient and inside color property define top and bottom color val verticalGradient = Brush.verticalGradient( colors = listOf(MaterialTheme.colors.primary, MaterialTheme.colors.primaryVariant), startY = 0f, endY = 100f ) // Vertical gradient Button // Create a text and set its background to verticalGradient that we created above Text( text = \"Vertical gradient\", style = typography.body1.copy(color = Color.White), modifier = Modifier .padding(12.dp) .clickable(onClick = {}) .clip(RoundedCornerShape(4.dp)) .background(brush = verticalGradient) .padding(12.dp) ) } }// To see the preview annotate with @Preview to the function@Preview@Composablefun DefaultPreview() { JetpackComposePracticeTheme { Column { allButtons() } }}",
"e": 7380,
"s": 934,
"text": null
},
{
"code": null,
"e": 7388,
"s": 7380,
"text": "Output:"
},
{
"code": null,
"e": 7402,
"s": 7388,
"text": "sumitgumber28"
},
{
"code": null,
"e": 7418,
"s": 7402,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 7426,
"s": 7418,
"text": "Android"
},
{
"code": null,
"e": 7433,
"s": 7426,
"text": "Kotlin"
},
{
"code": null,
"e": 7441,
"s": 7433,
"text": "Android"
},
{
"code": null,
"e": 7539,
"s": 7441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7605,
"s": 7539,
"text": "Difference Between Implicit Intent and Explicit Intent in Android"
},
{
"code": null,
"e": 7647,
"s": 7605,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7674,
"s": 7647,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 7705,
"s": 7674,
"text": "Bundle in Android with Example"
},
{
"code": null,
"e": 7739,
"s": 7705,
"text": "Animation in Android with Example"
},
{
"code": null,
"e": 7758,
"s": 7739,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 7771,
"s": 7758,
"text": "Kotlin Array"
},
{
"code": null,
"e": 7813,
"s": 7771,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7840,
"s": 7813,
"text": "Kotlin Setters and Getters"
}
] |
Minimum absolute difference of server loads
|
14 Jun, 2021
There are some processes that need to be executed. The amount of load that process causes a server that runs it, is being represented by a single integer. The total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which the mentioned processes can be run. Your goal is to distribute given processes between those two servers in a way that, the absolute difference of their loads will be minimized. Given an array of A[] of N integers, which represents loads caused by successive processes, the task is to print the minimum absolute difference of server loads. Examples:
Input: A[] = {1, 2, 3, 4, 5} Output: 1 Explanation: Distribute the processes with loads {1, 2, 4} on the first server and {3, 5} on the second server, so that their total loads will be 7 and 8, respectively. The difference of their loads will be equal to 1.
Input: A[] = {10, 10, 9, 9, 2} Output: 0
Naive Approach: The simplest approach to solve the problem is to generate all possibilities of the load distribution and find the minimum difference possible among all the possible combinations of loads of the two servers.
Time Complexity: O(2N) Auxiliary Space: O(1)
Efficient Approach: The problem can be visualized as a variation of the 0/1 Knapsack problem in which 2 servers are given, and we have to distribute the loads as equally possible. Therefore, it can be solved using Dynamic Programming. Below are the steps:
Compute required_load, which is equal to (sum of all loads / 2), since the loads need to distributed as equally possible.
Create a memoization table DP[][] to consider all the possible server loads in the range [1, required_load].
The state DP[i][j] stores the maximum value of j – load considering up to the ith element. So, considering li(load in ith row), it can be filled in all the columns having load values > li.
Now two possibilities arise, either to fill li in the given column or not.
Now, take a maximum of the above two possibilities, i.e.
DP[i][j] = max(DP[i – 1][j], DP[i – 1][j – li] + li]
Finally, DP[n][required_load] will contain the load on server1 which is as balanced as possible.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++14 program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function which returns the minimum// difference of loadsint minServerLoads(int n, vector<int>& servers){ // Compute the overall server load int totalLoad = 0; for(int i : servers) totalLoad += i; int requiredLoad = totalLoad / 2; // Stores the results of subproblems vector<vector<int>> dp(n + 1, vector<int>(requiredLoad + 1, 0)); // Fill the partition table // in bottom up manner for(int i = 1; i < n + 1; i++) { for(int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad];} // Driver Codeint main(){ int N = 5; vector<int> servers = { 1, 2, 3, 4, 5 }; // Function call cout << (minServerLoads(N, servers));} // This code is contributed by mohit kumar 29
// Java program to implement// the above approachimport java.util.*;class GFG { // Function which returns the minimum // difference of loads static int minServerLoads(int n, int[] servers) { // Compute the overall server load int totalLoad = 0; for (int i = 0; i < servers.length; i++) totalLoad += servers[i]; int requiredLoad = totalLoad / 2; // Stores the results of subproblems int dp[][] = new int[n + 1][requiredLoad + 1]; // Fill the partition table // in bottom up manner for (int i = 1; i < n + 1; i++) { for (int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = Math.max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad]; } // Driver Code public static void main(String[] args) { int N = 5; int servers[] = {1, 2, 3, 4, 5}; // Function call System.out.print(minServerLoads(N, servers)); }} // This code is contributed by Chitranayal
# Python3 program for the above approach # Function which returns the minimum# difference of loadsdef minServerLoads(n, servers): # Compute the overall server load totalLoad = sum(servers) requiredLoad = totalLoad // 2 # Stores the results of subproblems dp = [[0 for col in range(requiredLoad + 1)] for row in range(n + 1)] # Fill the partition table # in bottom up manner for i in range(1, n + 1): for j in range(1, requiredLoad + 1): # If i-th server is included if servers[i-1] > j: dp[i][j] = dp[i-1][j] # If i-th server is excluded else: dp[i][j] = max(dp[i-1][j], servers[i-1] + dp[i-1][j-servers[i-1]]) # Server A load: total_sum-ans # Server B load: ans # Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad] # Driver Code N = 5; servers = [1, 2, 3, 4, 5] # Function Callprint(minServerLoads(N, servers))
// C# program to implement// the above approachusing System; class GFG{ // Function which returns the minimum// difference of loadsstatic int minServerLoads(int n, int[] servers){ // Compute the overall server load int totalLoad = 0; for(int i = 0; i < servers.Length; i++) totalLoad += servers[i]; int requiredLoad = totalLoad / 2; // Stores the results of subproblems int [,]dp = new int[n + 1, requiredLoad + 1]; // Fill the partition table // in bottom up manner for(int i = 1; i < n + 1; i++) { for(int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i, j] = dp[i - 1, j]; // If i-th server is excluded else dp[i, j] = Math.Max(dp[i - 1, j], servers[i - 1] + dp[i - 1, j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n, requiredLoad];} // Driver Codepublic static void Main(string[] args){ int N = 5; int []servers = { 1, 2, 3, 4, 5 }; // Function call Console.Write(minServerLoads(N, servers));}} // This code is contributed by rutvik_56
<script> // JavaScript program to implement// the above approach // Function which returns the minimum// difference of loadsfunction minServerLoads(n, servers){ // Compute the overall server load var totalLoad = 0; servers.forEach(i => { totalLoad+=i; }); var requiredLoad = parseInt(totalLoad / 2); // Stores the results of subproblems var dp = Array.from(Array(n+1), ()=> Array(requiredLoad+1).fill(0)); // Fill the partition table // in bottom up manner for(var i = 1; i < n + 1; i++) { for(var j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = Math.max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad];} // Driver Codevar N = 5;var servers = [1, 2, 3, 4, 5]; // Function calldocument.write(minServerLoads(N, servers)); </script>
1
Time Complexity: O(N*S) where N is the number of servers and S is the sum of the load all servers. Auxiliary Space: O(N*S)
mohit kumar 29
ukasp
rutvik_56
rrrtnx
Google
interview-preparation
knapsack
subsequence
Arrays
Dynamic Programming
Mathematical
Searching
Google
Arrays
Searching
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 709,
"s": 52,
"text": "There are some processes that need to be executed. The amount of load that process causes a server that runs it, is being represented by a single integer. The total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which the mentioned processes can be run. Your goal is to distribute given processes between those two servers in a way that, the absolute difference of their loads will be minimized. Given an array of A[] of N integers, which represents loads caused by successive processes, the task is to print the minimum absolute difference of server loads. Examples:"
},
{
"code": null,
"e": 967,
"s": 709,
"text": "Input: A[] = {1, 2, 3, 4, 5} Output: 1 Explanation: Distribute the processes with loads {1, 2, 4} on the first server and {3, 5} on the second server, so that their total loads will be 7 and 8, respectively. The difference of their loads will be equal to 1."
},
{
"code": null,
"e": 1008,
"s": 967,
"text": "Input: A[] = {10, 10, 9, 9, 2} Output: 0"
},
{
"code": null,
"e": 1231,
"s": 1008,
"text": "Naive Approach: The simplest approach to solve the problem is to generate all possibilities of the load distribution and find the minimum difference possible among all the possible combinations of loads of the two servers."
},
{
"code": null,
"e": 1276,
"s": 1231,
"text": "Time Complexity: O(2N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1532,
"s": 1276,
"text": "Efficient Approach: The problem can be visualized as a variation of the 0/1 Knapsack problem in which 2 servers are given, and we have to distribute the loads as equally possible. Therefore, it can be solved using Dynamic Programming. Below are the steps:"
},
{
"code": null,
"e": 1654,
"s": 1532,
"text": "Compute required_load, which is equal to (sum of all loads / 2), since the loads need to distributed as equally possible."
},
{
"code": null,
"e": 1763,
"s": 1654,
"text": "Create a memoization table DP[][] to consider all the possible server loads in the range [1, required_load]."
},
{
"code": null,
"e": 1952,
"s": 1763,
"text": "The state DP[i][j] stores the maximum value of j – load considering up to the ith element. So, considering li(load in ith row), it can be filled in all the columns having load values > li."
},
{
"code": null,
"e": 2027,
"s": 1952,
"text": "Now two possibilities arise, either to fill li in the given column or not."
},
{
"code": null,
"e": 2084,
"s": 2027,
"text": "Now, take a maximum of the above two possibilities, i.e."
},
{
"code": null,
"e": 2137,
"s": 2084,
"text": "DP[i][j] = max(DP[i – 1][j], DP[i – 1][j – li] + li]"
},
{
"code": null,
"e": 2234,
"s": 2137,
"text": "Finally, DP[n][required_load] will contain the load on server1 which is as balanced as possible."
},
{
"code": null,
"e": 2285,
"s": 2234,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2291,
"s": 2285,
"text": "C++14"
},
{
"code": null,
"e": 2296,
"s": 2291,
"text": "Java"
},
{
"code": null,
"e": 2304,
"s": 2296,
"text": "Python3"
},
{
"code": null,
"e": 2307,
"s": 2304,
"text": "C#"
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": "Javascript"
},
{
"code": "// C++14 program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function which returns the minimum// difference of loadsint minServerLoads(int n, vector<int>& servers){ // Compute the overall server load int totalLoad = 0; for(int i : servers) totalLoad += i; int requiredLoad = totalLoad / 2; // Stores the results of subproblems vector<vector<int>> dp(n + 1, vector<int>(requiredLoad + 1, 0)); // Fill the partition table // in bottom up manner for(int i = 1; i < n + 1; i++) { for(int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad];} // Driver Codeint main(){ int N = 5; vector<int> servers = { 1, 2, 3, 4, 5 }; // Function call cout << (minServerLoads(N, servers));} // This code is contributed by mohit kumar 29",
"e": 3619,
"s": 2318,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG { // Function which returns the minimum // difference of loads static int minServerLoads(int n, int[] servers) { // Compute the overall server load int totalLoad = 0; for (int i = 0; i < servers.length; i++) totalLoad += servers[i]; int requiredLoad = totalLoad / 2; // Stores the results of subproblems int dp[][] = new int[n + 1][requiredLoad + 1]; // Fill the partition table // in bottom up manner for (int i = 1; i < n + 1; i++) { for (int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = Math.max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad]; } // Driver Code public static void main(String[] args) { int N = 5; int servers[] = {1, 2, 3, 4, 5}; // Function call System.out.print(minServerLoads(N, servers)); }} // This code is contributed by Chitranayal",
"e": 5107,
"s": 3619,
"text": null
},
{
"code": "# Python3 program for the above approach # Function which returns the minimum# difference of loadsdef minServerLoads(n, servers): # Compute the overall server load totalLoad = sum(servers) requiredLoad = totalLoad // 2 # Stores the results of subproblems dp = [[0 for col in range(requiredLoad + 1)] for row in range(n + 1)] # Fill the partition table # in bottom up manner for i in range(1, n + 1): for j in range(1, requiredLoad + 1): # If i-th server is included if servers[i-1] > j: dp[i][j] = dp[i-1][j] # If i-th server is excluded else: dp[i][j] = max(dp[i-1][j], servers[i-1] + dp[i-1][j-servers[i-1]]) # Server A load: total_sum-ans # Server B load: ans # Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad] # Driver Code N = 5; servers = [1, 2, 3, 4, 5] # Function Callprint(minServerLoads(N, servers))",
"e": 6125,
"s": 5107,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function which returns the minimum// difference of loadsstatic int minServerLoads(int n, int[] servers){ // Compute the overall server load int totalLoad = 0; for(int i = 0; i < servers.Length; i++) totalLoad += servers[i]; int requiredLoad = totalLoad / 2; // Stores the results of subproblems int [,]dp = new int[n + 1, requiredLoad + 1]; // Fill the partition table // in bottom up manner for(int i = 1; i < n + 1; i++) { for(int j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i, j] = dp[i - 1, j]; // If i-th server is excluded else dp[i, j] = Math.Max(dp[i - 1, j], servers[i - 1] + dp[i - 1, j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n, requiredLoad];} // Driver Codepublic static void Main(string[] args){ int N = 5; int []servers = { 1, 2, 3, 4, 5 }; // Function call Console.Write(minServerLoads(N, servers));}} // This code is contributed by rutvik_56",
"e": 7490,
"s": 6125,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function which returns the minimum// difference of loadsfunction minServerLoads(n, servers){ // Compute the overall server load var totalLoad = 0; servers.forEach(i => { totalLoad+=i; }); var requiredLoad = parseInt(totalLoad / 2); // Stores the results of subproblems var dp = Array.from(Array(n+1), ()=> Array(requiredLoad+1).fill(0)); // Fill the partition table // in bottom up manner for(var i = 1; i < n + 1; i++) { for(var j = 1; j < requiredLoad + 1; j++) { // If i-th server is included if (servers[i - 1] > j) dp[i][j] = dp[i - 1][j]; // If i-th server is excluded else dp[i][j] = Math.max(dp[i - 1][j], servers[i - 1] + dp[i - 1][j - servers[i - 1]]); } } // Server A load: total_sum-ans // Server B load: ans // Diff: abs(total_sum-2 * ans) return totalLoad - 2 * dp[n][requiredLoad];} // Driver Codevar N = 5;var servers = [1, 2, 3, 4, 5]; // Function calldocument.write(minServerLoads(N, servers)); </script>",
"e": 8707,
"s": 7490,
"text": null
},
{
"code": null,
"e": 8709,
"s": 8707,
"text": "1"
},
{
"code": null,
"e": 8832,
"s": 8709,
"text": "Time Complexity: O(N*S) where N is the number of servers and S is the sum of the load all servers. Auxiliary Space: O(N*S)"
},
{
"code": null,
"e": 8847,
"s": 8832,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8853,
"s": 8847,
"text": "ukasp"
},
{
"code": null,
"e": 8863,
"s": 8853,
"text": "rutvik_56"
},
{
"code": null,
"e": 8870,
"s": 8863,
"text": "rrrtnx"
},
{
"code": null,
"e": 8877,
"s": 8870,
"text": "Google"
},
{
"code": null,
"e": 8899,
"s": 8877,
"text": "interview-preparation"
},
{
"code": null,
"e": 8908,
"s": 8899,
"text": "knapsack"
},
{
"code": null,
"e": 8920,
"s": 8908,
"text": "subsequence"
},
{
"code": null,
"e": 8927,
"s": 8920,
"text": "Arrays"
},
{
"code": null,
"e": 8947,
"s": 8927,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8960,
"s": 8947,
"text": "Mathematical"
},
{
"code": null,
"e": 8970,
"s": 8960,
"text": "Searching"
},
{
"code": null,
"e": 8977,
"s": 8970,
"text": "Google"
},
{
"code": null,
"e": 8984,
"s": 8977,
"text": "Arrays"
},
{
"code": null,
"e": 8994,
"s": 8984,
"text": "Searching"
},
{
"code": null,
"e": 9014,
"s": 8994,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9027,
"s": 9014,
"text": "Mathematical"
}
] |
How to stream large .mp4 files?
|
28 Jul, 2021
Streaming large video files from the server to the client which might be a web app or mobile apps inefficient manner!
We can’t send the entire video once to a client. because there are conditions like the bandwidth and data restrictions of the user.
Example:
Let’s say youtube, the user may watch some part of the video and went away for some reason, if he opened that video again, it should not load the entire video from start.
Here is the part we need some mechanism to handle this situation.
Nodejs stream API comes into the picture, its more efficient than reading a file in a conventional manner and waiting for the callbacks to resolve.
Created a basic video streaming server to explain it little better.
The flow of the system:
User visits the site (index.html)
The html5 video component in index.html is pointed to URL of the video that is streaming by server
The video request is handler by the server by processing range header and sends out part of the video as partial content
Setting up project:
Open terminal
mkdir <project name>
cd <project name>
npm init -y
Open your favourite text editor
Create index.html on that folder (check below html code, use it there)
Create a server.js file(check the js code provided below)
Run the command “node server.js”
Open browser and navigate to “localhost:3000”
Complete source code:
https://github.com/varaprasadh/gfg-blogs/tree/master/streamvideo
We will need a index.html file show the video that coming from the server!
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>video player</title></head><body> <video src="http://localhost:3000/video" controls> </video></body></html>
Javascript
const http=require('http');const fs=require("fs");const path=require("path"); /* http.createServer takes a handler function and returns a server instance;*/const server=http.createServer((req, res)=>{ // return res.end(req.url+req.method); if(req.method==='GET' && req.url==="/"){ /*we will send a index.html page when user visits "/" endpoint*/ /*index.html will have video component that displays the video*/ fs.createReadStream(path.resolve( "index.html")).pipe(res); return; } //if video content is requesting if(req.method==='GET' && req.url==="/video"){ const filepath = path.resolve("video.mp4"); const stat = fs.statSync(filepath) const fileSize = stat.size const range = req.headers.range /*when we seek the video it will put range header to the request*/ /*if range header exists send some part of video*/ if (range) { //range format is "bytes=start-end", const parts = range.replace(/bytes=/, "").split("-"); const start = parseInt(parts[0], 10) /*in some cases end may not exists, if its not exists make it end of file*/ const end = parts[1] ?parseInt(parts[1], 10) :fileSize - 1 //chunk size is what the part of video we are sending. const chunksize = (end - start) + 1 /*we can provide offset values as options to the fs.createReadStream to read part of content*/ const file = fs.createReadStream(filepath, {start, end}) const head = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4', } /*we should set status code as 206 which is for partial content*/ // because video is continuously fetched part by part res.writeHead(206, head); file.pipe(res); }else{ //if not send the video from start. /* anyway html5 video player play content when sufficient frames available*/ // It doesn't wait for the entire video to load. const head = { 'Content-Length': fileSize, 'Content-Type': 'video/mp4', } res.writeHead(200, head); fs.createReadStream(path).pipe(res); } } /*if anything other than handler routes then send 400 status code, is for bad request*/ else{ res.writeHead(400); res.end("bad request"); }}) /*check if system has environment variable for the port, otherwise defaults to 3000*/const PORT = process.env.PORT || 3000; //start the serverserver.listen(PORT, () => { console.log(`server listening on port:${PORT}`);})
Finally we can see the result in the browser
Final Result
ruhelaa48
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "Streaming large video files from the server to the client which might be a web app or mobile apps inefficient manner! "
},
{
"code": null,
"e": 279,
"s": 147,
"text": "We can’t send the entire video once to a client. because there are conditions like the bandwidth and data restrictions of the user."
},
{
"code": null,
"e": 288,
"s": 279,
"text": "Example:"
},
{
"code": null,
"e": 460,
"s": 288,
"text": "Let’s say youtube, the user may watch some part of the video and went away for some reason, if he opened that video again, it should not load the entire video from start. "
},
{
"code": null,
"e": 527,
"s": 460,
"text": "Here is the part we need some mechanism to handle this situation. "
},
{
"code": null,
"e": 675,
"s": 527,
"text": "Nodejs stream API comes into the picture, its more efficient than reading a file in a conventional manner and waiting for the callbacks to resolve."
},
{
"code": null,
"e": 745,
"s": 675,
"text": "Created a basic video streaming server to explain it little better. "
},
{
"code": null,
"e": 769,
"s": 745,
"text": "The flow of the system:"
},
{
"code": null,
"e": 803,
"s": 769,
"text": "User visits the site (index.html)"
},
{
"code": null,
"e": 902,
"s": 803,
"text": "The html5 video component in index.html is pointed to URL of the video that is streaming by server"
},
{
"code": null,
"e": 1023,
"s": 902,
"text": "The video request is handler by the server by processing range header and sends out part of the video as partial content"
},
{
"code": null,
"e": 1043,
"s": 1023,
"text": "Setting up project:"
},
{
"code": null,
"e": 1057,
"s": 1043,
"text": "Open terminal"
},
{
"code": null,
"e": 1078,
"s": 1057,
"text": "mkdir <project name>"
},
{
"code": null,
"e": 1096,
"s": 1078,
"text": "cd <project name>"
},
{
"code": null,
"e": 1108,
"s": 1096,
"text": "npm init -y"
},
{
"code": null,
"e": 1141,
"s": 1108,
"text": "Open your favourite text editor"
},
{
"code": null,
"e": 1212,
"s": 1141,
"text": "Create index.html on that folder (check below html code, use it there)"
},
{
"code": null,
"e": 1270,
"s": 1212,
"text": "Create a server.js file(check the js code provided below)"
},
{
"code": null,
"e": 1303,
"s": 1270,
"text": "Run the command “node server.js”"
},
{
"code": null,
"e": 1349,
"s": 1303,
"text": "Open browser and navigate to “localhost:3000”"
},
{
"code": null,
"e": 1372,
"s": 1349,
"text": "Complete source code: "
},
{
"code": null,
"e": 1438,
"s": 1372,
"text": " https://github.com/varaprasadh/gfg-blogs/tree/master/streamvideo"
},
{
"code": null,
"e": 1513,
"s": 1438,
"text": "We will need a index.html file show the video that coming from the server!"
},
{
"code": null,
"e": 1518,
"s": 1513,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>video player</title></head><body> <video src=\"http://localhost:3000/video\" controls> </video></body></html>",
"e": 1874,
"s": 1518,
"text": null
},
{
"code": null,
"e": 1885,
"s": 1874,
"text": "Javascript"
},
{
"code": "const http=require('http');const fs=require(\"fs\");const path=require(\"path\"); /* http.createServer takes a handler function and returns a server instance;*/const server=http.createServer((req, res)=>{ // return res.end(req.url+req.method); if(req.method==='GET' && req.url===\"/\"){ /*we will send a index.html page when user visits \"/\" endpoint*/ /*index.html will have video component that displays the video*/ fs.createReadStream(path.resolve( \"index.html\")).pipe(res); return; } //if video content is requesting if(req.method==='GET' && req.url===\"/video\"){ const filepath = path.resolve(\"video.mp4\"); const stat = fs.statSync(filepath) const fileSize = stat.size const range = req.headers.range /*when we seek the video it will put range header to the request*/ /*if range header exists send some part of video*/ if (range) { //range format is \"bytes=start-end\", const parts = range.replace(/bytes=/, \"\").split(\"-\"); const start = parseInt(parts[0], 10) /*in some cases end may not exists, if its not exists make it end of file*/ const end = parts[1] ?parseInt(parts[1], 10) :fileSize - 1 //chunk size is what the part of video we are sending. const chunksize = (end - start) + 1 /*we can provide offset values as options to the fs.createReadStream to read part of content*/ const file = fs.createReadStream(filepath, {start, end}) const head = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4', } /*we should set status code as 206 which is for partial content*/ // because video is continuously fetched part by part res.writeHead(206, head); file.pipe(res); }else{ //if not send the video from start. /* anyway html5 video player play content when sufficient frames available*/ // It doesn't wait for the entire video to load. const head = { 'Content-Length': fileSize, 'Content-Type': 'video/mp4', } res.writeHead(200, head); fs.createReadStream(path).pipe(res); } } /*if anything other than handler routes then send 400 status code, is for bad request*/ else{ res.writeHead(400); res.end(\"bad request\"); }}) /*check if system has environment variable for the port, otherwise defaults to 3000*/const PORT = process.env.PORT || 3000; //start the serverserver.listen(PORT, () => { console.log(`server listening on port:${PORT}`);})",
"e": 4895,
"s": 1885,
"text": null
},
{
"code": null,
"e": 4940,
"s": 4895,
"text": "Finally we can see the result in the browser"
},
{
"code": null,
"e": 4953,
"s": 4940,
"text": "Final Result"
},
{
"code": null,
"e": 4963,
"s": 4953,
"text": "ruhelaa48"
},
{
"code": null,
"e": 4979,
"s": 4963,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4986,
"s": 4979,
"text": "Picked"
},
{
"code": null,
"e": 4991,
"s": 4986,
"text": "HTML"
},
{
"code": null,
"e": 5002,
"s": 4991,
"text": "JavaScript"
},
{
"code": null,
"e": 5019,
"s": 5002,
"text": "Web Technologies"
},
{
"code": null,
"e": 5024,
"s": 5019,
"text": "HTML"
}
] |
PHP | DirectoryIterator isDot() Function
|
26 Nov, 2019
The DirectoryIterator::isDot() function is an inbuilt function in PHP which is used to check the current DirectoryIterator item is ‘.’ or ‘..’
Syntax:
bool DirectoryIterator::isDot( void )
Parameters: This function does not accept any parameters.
Return Value: This function returns TRUE if the entry is . or .., otherwise FALSE.
Below programs illustrate the DirectoryIterator::isDot() function in PHP:
Program 1:
<?php // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__)); // Loop runs for each element of directoryforeach($directory as $dir) { // Check if not a dot directory if (!$dir->isDot()) { // Display directory element and its permission $perms = substr(sprintf('%o', $dir->getPerms()), -4); echo $dir->getFilename() . " " . " | Permission: " . $perms . "<br>"; }} ?>
Output:
applications.html | Permission: 0666
bitnami.css | Permission: 0666
dashboard | Permission: 0777
favicon.ico | Permission: 0666
geeks.PNG | Permission: 0666
gfg.php | Permission: 0666
img | Permission: 0777
index.php | Permission: 0666
Sublime Text Build 3211 x64 Setup.exe | Permission: 0777
webalizer | Permission: 0777
xampp | Permission: 0777
Program 2:
<?php // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__)); // Loop runs while directory is validwhile ($directory->valid()) { // Check if not a dot directory if (!$directory->isDot()) { echo $directory->getFilename() . "<br>"; } $directory->next();} ?>
Output:
applications.html
bitnami.css
dashboard
favicon.ico
geeks.PNG
gfg.php
img
index.php
Sublime Text Build 3211 x64 Setup.exe
webalizer
xampp
Note: The output of this function depends on the content of server folder.
Reference: https://www.php.net/manual/en/directoryiterator.isdot.php
PHP-function
PHP-Iterators
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
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": "\n26 Nov, 2019"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "The DirectoryIterator::isDot() function is an inbuilt function in PHP which is used to check the current DirectoryIterator item is ‘.’ or ‘..’"
},
{
"code": null,
"e": 179,
"s": 171,
"text": "Syntax:"
},
{
"code": null,
"e": 217,
"s": 179,
"text": "bool DirectoryIterator::isDot( void )"
},
{
"code": null,
"e": 275,
"s": 217,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 358,
"s": 275,
"text": "Return Value: This function returns TRUE if the entry is . or .., otherwise FALSE."
},
{
"code": null,
"e": 432,
"s": 358,
"text": "Below programs illustrate the DirectoryIterator::isDot() function in PHP:"
},
{
"code": null,
"e": 443,
"s": 432,
"text": "Program 1:"
},
{
"code": "<?php // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__)); // Loop runs for each element of directoryforeach($directory as $dir) { // Check if not a dot directory if (!$dir->isDot()) { // Display directory element and its permission $perms = substr(sprintf('%o', $dir->getPerms()), -4); echo $dir->getFilename() . \" \" . \" | Permission: \" . $perms . \"<br>\"; }} ?>",
"e": 887,
"s": 443,
"text": null
},
{
"code": null,
"e": 895,
"s": 887,
"text": "Output:"
},
{
"code": null,
"e": 1242,
"s": 895,
"text": "applications.html | Permission: 0666\nbitnami.css | Permission: 0666\ndashboard | Permission: 0777\nfavicon.ico | Permission: 0666\ngeeks.PNG | Permission: 0666\ngfg.php | Permission: 0666\nimg | Permission: 0777\nindex.php | Permission: 0666\nSublime Text Build 3211 x64 Setup.exe | Permission: 0777\nwebalizer | Permission: 0777\nxampp | Permission: 0777"
},
{
"code": null,
"e": 1253,
"s": 1242,
"text": "Program 2:"
},
{
"code": "<?php // Create a directory Iterator$directory = new DirectoryIterator(dirname(__FILE__)); // Loop runs while directory is validwhile ($directory->valid()) { // Check if not a dot directory if (!$directory->isDot()) { echo $directory->getFilename() . \"<br>\"; } $directory->next();} ?>",
"e": 1562,
"s": 1253,
"text": null
},
{
"code": null,
"e": 1570,
"s": 1562,
"text": "Output:"
},
{
"code": null,
"e": 1708,
"s": 1570,
"text": "applications.html\nbitnami.css\ndashboard\nfavicon.ico\ngeeks.PNG\ngfg.php\nimg\nindex.php\nSublime Text Build 3211 x64 Setup.exe\nwebalizer\nxampp"
},
{
"code": null,
"e": 1783,
"s": 1708,
"text": "Note: The output of this function depends on the content of server folder."
},
{
"code": null,
"e": 1852,
"s": 1783,
"text": "Reference: https://www.php.net/manual/en/directoryiterator.isdot.php"
},
{
"code": null,
"e": 1865,
"s": 1852,
"text": "PHP-function"
},
{
"code": null,
"e": 1879,
"s": 1865,
"text": "PHP-Iterators"
},
{
"code": null,
"e": 1883,
"s": 1879,
"text": "PHP"
},
{
"code": null,
"e": 1900,
"s": 1883,
"text": "Web Technologies"
},
{
"code": null,
"e": 1904,
"s": 1900,
"text": "PHP"
},
{
"code": null,
"e": 2002,
"s": 1904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2084,
"s": 2002,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2129,
"s": 2084,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 2180,
"s": 2129,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 2210,
"s": 2180,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 2233,
"s": 2210,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2266,
"s": 2233,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2328,
"s": 2266,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2389,
"s": 2328,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2439,
"s": 2389,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
List to Set in Java
|
11 Dec, 2018
Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java.
Method 1 (Simple)We simply create an list. We traverse the given set and one by one add elements to the list.
// Java program to demonstrate conversion of// list to set using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); Set<String> hSet = new HashSet<String>(); for (String x : aList) hSet.add(x); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); // We can created TreeSet same way }}
Method 2 (Using HashSet or TreeSet Constructor)
// Java program to demonstrate conversion of// list to set using constructorimport java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); // Creating a hash set using constructor Set<String> hSet = new HashSet<String>(aList); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); System.out.println("Created TreeSet is"); Set<String> tSet = new TreeSet<String>(aList); System.out.println("Created TreeSet is"); for (String x : tSet) System.out.println(x); }}
Method 3 (Using addAll method)
// Java program to demonstrate conversion of// Set to array using addAll() method.import java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); Set<String> hSet = new HashSet<String>(aList); hSet.addAll(aList); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); Set<String> tSet = new TreeSet<String>(aList); tSet.addAll(aList); System.out.println("Created TreeSet is"); for (String x : tSet) System.out.println(x); }}
Method 4 (Using stream in Java)We use stream in Java to convert given list to stream, then stream to set. This works only in Java 8 or versions after that.
// Java program to demonstrate conversion of// Set to list using streamimport java.util.*;import java.util.stream.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); // Converting to set using stream Set<String> set = aList.stream().collect(Collectors.toSet()); for (String x : set) System.out.println(x); }}
Java-ArrayList
Java-Collections
java-hashset
java-LinkedList
java-list
Java-List-Programs
Java-Set-Programs
java-stream
Java-Stream-programs
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Introduction to Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 156,
"s": 53,
"text": "Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java."
},
{
"code": null,
"e": 266,
"s": 156,
"text": "Method 1 (Simple)We simply create an list. We traverse the given set and one by one add elements to the list."
},
{
"code": "// Java program to demonstrate conversion of// list to set using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList(\"Geeks\", \"for\", \"GeeksQuiz\", \"GeeksforGeeks\", \"GFG\"); Set<String> hSet = new HashSet<String>(); for (String x : aList) hSet.add(x); System.out.println(\"Created HashSet is\"); for (String x : hSet) System.out.println(x); // We can created TreeSet same way }}",
"e": 852,
"s": 266,
"text": null
},
{
"code": null,
"e": 900,
"s": 852,
"text": "Method 2 (Using HashSet or TreeSet Constructor)"
},
{
"code": "// Java program to demonstrate conversion of// list to set using constructorimport java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList(\"Geeks\", \"for\", \"GeeksQuiz\", \"GeeksforGeeks\", \"GFG\"); // Creating a hash set using constructor Set<String> hSet = new HashSet<String>(aList); System.out.println(\"Created HashSet is\"); for (String x : hSet) System.out.println(x); System.out.println(\"Created TreeSet is\"); Set<String> tSet = new TreeSet<String>(aList); System.out.println(\"Created TreeSet is\"); for (String x : tSet) System.out.println(x); }}",
"e": 1653,
"s": 900,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1653,
"text": "Method 3 (Using addAll method)"
},
{
"code": "// Java program to demonstrate conversion of// Set to array using addAll() method.import java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList(\"Geeks\", \"for\", \"GeeksQuiz\", \"GeeksforGeeks\", \"GFG\"); Set<String> hSet = new HashSet<String>(aList); hSet.addAll(aList); System.out.println(\"Created HashSet is\"); for (String x : hSet) System.out.println(x); Set<String> tSet = new TreeSet<String>(aList); tSet.addAll(aList); System.out.println(\"Created TreeSet is\"); for (String x : tSet) System.out.println(x); }}",
"e": 2397,
"s": 1684,
"text": null
},
{
"code": null,
"e": 2553,
"s": 2397,
"text": "Method 4 (Using stream in Java)We use stream in Java to convert given list to stream, then stream to set. This works only in Java 8 or versions after that."
},
{
"code": "// Java program to demonstrate conversion of// Set to list using streamimport java.util.*;import java.util.stream.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList(\"Geeks\", \"for\", \"GeeksQuiz\", \"GeeksforGeeks\", \"GFG\"); // Converting to set using stream Set<String> set = aList.stream().collect(Collectors.toSet()); for (String x : set) System.out.println(x); }}",
"e": 3067,
"s": 2553,
"text": null
},
{
"code": null,
"e": 3082,
"s": 3067,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 3099,
"s": 3082,
"text": "Java-Collections"
},
{
"code": null,
"e": 3112,
"s": 3099,
"text": "java-hashset"
},
{
"code": null,
"e": 3128,
"s": 3112,
"text": "java-LinkedList"
},
{
"code": null,
"e": 3138,
"s": 3128,
"text": "java-list"
},
{
"code": null,
"e": 3157,
"s": 3138,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 3175,
"s": 3157,
"text": "Java-Set-Programs"
},
{
"code": null,
"e": 3187,
"s": 3175,
"text": "java-stream"
},
{
"code": null,
"e": 3208,
"s": 3187,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 3221,
"s": 3208,
"text": "java-treeset"
},
{
"code": null,
"e": 3226,
"s": 3221,
"text": "Java"
},
{
"code": null,
"e": 3231,
"s": 3226,
"text": "Java"
},
{
"code": null,
"e": 3248,
"s": 3231,
"text": "Java-Collections"
},
{
"code": null,
"e": 3346,
"s": 3248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3365,
"s": 3346,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3383,
"s": 3365,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3403,
"s": 3383,
"text": "Collections in Java"
},
{
"code": null,
"e": 3418,
"s": 3403,
"text": "Stream In Java"
},
{
"code": null,
"e": 3450,
"s": 3418,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3474,
"s": 3450,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3494,
"s": 3474,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3526,
"s": 3494,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 3554,
"s": 3526,
"text": "Initializing a List in Java"
}
] |
Python – Convert Float String List to Float Values
|
03 Jul, 2020
Sometimes, while working with Python Data, we can have a problem in which we need to perform conversion of Float Strings to float values. This kind of problem is quite common in all domains and find application quite often. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [‘8.6’, ‘4.6’]Output : [8.6, 4.6]
Input : test_list = [‘4.5’]Output : [4.5]
Method #1 : Using list comprehension + float()The combination of above functions can be used to solve this problem. In this, we perform task of conversion using float() and list comprehension is used to perform iteration.
# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using float() + list comprehension # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3'] # printing original list print("The original list : " + str(test_list)) # Convert Float String List to Float Values# Using float() + list comprehensionres = [float(ele) for ele in test_list] # printing result print("List after conversion : " + str(res))
The original list : ['87.6', '454.6', '9.34', '23', '12.3']
List after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]
Method #2 : Using map() + float()The combination of above functions can also be used to solve this problem. In this, we perform the task of conversion using float and extension of conversion logic using map().
# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using map() + float() # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3'] # printing original list print("The original list : " + str(test_list)) # Convert Float String List to Float Values# Using map() + float()res = list(map(float, test_list)) # printing result print("List after conversion : " + str(res))
The original list : ['87.6', '454.6', '9.34', '23', '12.3']
List after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 316,
"s": 28,
"text": "Sometimes, while working with Python Data, we can have a problem in which we need to perform conversion of Float Strings to float values. This kind of problem is quite common in all domains and find application quite often. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 370,
"s": 316,
"text": "Input : test_list = [‘8.6’, ‘4.6’]Output : [8.6, 4.6]"
},
{
"code": null,
"e": 412,
"s": 370,
"text": "Input : test_list = [‘4.5’]Output : [4.5]"
},
{
"code": null,
"e": 634,
"s": 412,
"text": "Method #1 : Using list comprehension + float()The combination of above functions can be used to solve this problem. In this, we perform task of conversion using float() and list comprehension is used to perform iteration."
},
{
"code": "# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using float() + list comprehension # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3'] # printing original list print(\"The original list : \" + str(test_list)) # Convert Float String List to Float Values# Using float() + list comprehensionres = [float(ele) for ele in test_list] # printing result print(\"List after conversion : \" + str(res))",
"e": 1084,
"s": 634,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1084,
"text": "The original list : ['87.6', '454.6', '9.34', '23', '12.3']\nList after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]\n"
},
{
"code": null,
"e": 1413,
"s": 1203,
"text": "Method #2 : Using map() + float()The combination of above functions can also be used to solve this problem. In this, we perform the task of conversion using float and extension of conversion logic using map()."
},
{
"code": "# Python3 code to demonstrate working of # Convert Float String List to Float Values# Using map() + float() # initializing listtest_list = ['87.6', '454.6', '9.34', '23', '12.3'] # printing original list print(\"The original list : \" + str(test_list)) # Convert Float String List to Float Values# Using map() + float()res = list(map(float, test_list)) # printing result print(\"List after conversion : \" + str(res))",
"e": 1831,
"s": 1413,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1831,
"text": "The original list : ['87.6', '454.6', '9.34', '23', '12.3']\nList after conversion : [87.6, 454.6, 9.34, 23.0, 12.3]\n"
},
{
"code": null,
"e": 1969,
"s": 1948,
"text": "Python list-programs"
},
{
"code": null,
"e": 1976,
"s": 1969,
"text": "Python"
},
{
"code": null,
"e": 1992,
"s": 1976,
"text": "Python Programs"
}
] |
Python – Mapping key values to Dictionary
|
22 Apr, 2020
Sometimes, while working with Python records, we can have a problem in which we need to extract key’s value as the dictionary values required. This can have application in domains in which we require to reduce the data storage and in web development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehensionThis is one of the way in which we can solve this problem. In this, we iterate the list keys and construct dictionary of required key-value pairs using dictionary comprehension.
# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dictionary comprehension # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23}, {'name' : 'Akshat', 'age' : 22}, {'name' : 'Nikhil', 'age' : 21}] # printing original listprint("The original list is : " + str(test_list)) # Mapping key values to Dictionary# Using dictionary comprehensionres = {sub['name'] : sub['age'] for sub in test_list} # printing result print("The flattened dictionary is : " + str(dict(res)))
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}
Method #2 : Using dict() + values()The combination of above functions can also be used to solve this problem. In this, we perform conversion to dictionary using dict() and extract dictionary values using values().
# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dict() + values() # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23}, {'name' : 'Akshat', 'age' : 22}, {'name' : 'Nikhil', 'age' : 21}] # printing original listprint("The original list is : " + str(test_list)) # Mapping key values to Dictionary# Using dict() + values()res = dict(sub.values() for sub in test_list) # printing result print("The flattened dictionary is : " + str(dict(res)))
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}
Python list-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
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 373,
"s": 52,
"text": "Sometimes, while working with Python records, we can have a problem in which we need to extract key’s value as the dictionary values required. This can have application in domains in which we require to reduce the data storage and in web development domain. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 593,
"s": 373,
"text": "Method #1 : Using dictionary comprehensionThis is one of the way in which we can solve this problem. In this, we iterate the list keys and construct dictionary of required key-value pairs using dictionary comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dictionary comprehension # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23}, {'name' : 'Akshat', 'age' : 22}, {'name' : 'Nikhil', 'age' : 21}] # printing original listprint(\"The original list is : \" + str(test_list)) # Mapping key values to Dictionary# Using dictionary comprehensionres = {sub['name'] : sub['age'] for sub in test_list} # printing result print(\"The flattened dictionary is : \" + str(dict(res))) ",
"e": 1133,
"s": 593,
"text": null
},
{
"code": null,
"e": 1324,
"s": 1133,
"text": "The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}"
},
{
"code": null,
"e": 1540,
"s": 1326,
"text": "Method #2 : Using dict() + values()The combination of above functions can also be used to solve this problem. In this, we perform conversion to dictionary using dict() and extract dictionary values using values()."
},
{
"code": "# Python3 code to demonstrate working of # Mapping key values to Dictionary# Using dict() + values() # initializing listtest_list = [{'name' : 'Manjeet', 'age' : 23}, {'name' : 'Akshat', 'age' : 22}, {'name' : 'Nikhil', 'age' : 21}] # printing original listprint(\"The original list is : \" + str(test_list)) # Mapping key values to Dictionary# Using dict() + values()res = dict(sub.values() for sub in test_list) # printing result print(\"The flattened dictionary is : \" + str(dict(res))) ",
"e": 2058,
"s": 1540,
"text": null
},
{
"code": null,
"e": 2249,
"s": 2058,
"text": "The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}"
},
{
"code": null,
"e": 2270,
"s": 2249,
"text": "Python list-programs"
},
{
"code": null,
"e": 2277,
"s": 2270,
"text": "Python"
},
{
"code": null,
"e": 2293,
"s": 2277,
"text": "Python Programs"
},
{
"code": null,
"e": 2391,
"s": 2293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2409,
"s": 2391,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2451,
"s": 2409,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2473,
"s": 2451,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2508,
"s": 2473,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2534,
"s": 2508,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2577,
"s": 2534,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2616,
"s": 2577,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2654,
"s": 2616,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2691,
"s": 2654,
"text": "Python Program for Fibonacci numbers"
}
] |
How to build a basic CRUD app with Node.js and ReactJS ?
|
10 Apr, 2022
In this article, we will create a basic Student app from scratch.
App functionality:
Create a new student
Update an existing student
Show students list
Delete a student
REST API in this project:
REST API
URL
First of all, we will work on the frontend part of our application using React.js.
Create React Application and installing modules
Step 1: Let’s start building the Front-end part with React. To create a new React App, enter the following code into terminal and hit enter.
npx create-react-app mern-stack-crud
Step 2: Move into the React project folder.
cd mern-stack-crud
Step 3: To run the React App, run the following command:
npm start
This command opens the React App to the browser on the following URL: http://localhost:3000/
Step 4: To build the React App we need to install some external modules.
NPM
Detail
To install, run the following code on the terminal.
npm i react-bootstrap@next bootstrap@5.1.0 react-router-dom axios formik yup
Step 5: Creating Simple React Components – In this step we will create some React Components to manage student data.
Head over to src folder, make a folder and name it Components and within that directory create the following components.
StudentForm.js – Reusable Student form
create-student.component.js – Responsible for create new student
edit-student.component.js – Responsible for update student data
student-list.component.js – Responsible for display all student
StudentTableRow.js – Responsible for display a single student
Project Structure: It will look like the following
front-end project structure
Step 6: Create student form – In this step, we will build a reusable student form with Formik and React-Bootstrap. This form has all the necessary fields to enter student details. We have also made client-side form validation with Yup. In the future, we will use this component for creating and update a student. Go to src/Components/StudentForm.js and write the following code.
StudentForm.js
import React from "react";import * as Yup from "yup";import { Formik, Form, Field, ErrorMessage } from "formik";import { FormGroup, FormControl, Button } from "react-bootstrap"; const StudentForm = (props) => { const validationSchema = Yup.object().shape({ name: Yup.string().required("Required"), email: Yup.string() .email("You have enter an invalid email address") .required("Required"), rollno: Yup.number() .positive("Invalid roll number") .integer("Invalid roll number") .required("Required"), }); console.log(props); return ( <div className="form-wrapper"> <Formik {...props} validationSchema={validationSchema}> <Form> <FormGroup> <Field name="name" type="text" className="form-control" /> <ErrorMessage name="name" className="d-block invalid-feedback" component="span" /> </FormGroup> <FormGroup> <Field name="email" type="text" className="form-control" /> <ErrorMessage name="email" className="d-block invalid-feedback" component="span" /> </FormGroup> <FormGroup> <Field name="rollno" type="number" className="form-control" /> <ErrorMessage name="rollno" className="d-block invalid-feedback" component="span" /> </FormGroup> <Button variant="danger" size="lg" block="block" type="submit"> {props.children} </Button> </Form> </Formik> </div> );}; export default StudentForm;
Step 7: Create a new student: In this step, we will create a component to add a new student. We have already created a StudentForm component to enter student details. Now, it’s time to use this component. Go to src/Components/create-student.component.js and write the following code.
create-student.component.js
// CreateStudent Component for add new student // Import Modulesimport React, { useState, useEffect } from "react";import axios from 'axios';import StudentForm from "./StudentForm"; // CreateStudent Componentconst CreateStudent = () => { const [formValues, setFormValues] = useState({ name: '', email: '', rollno: '' }) // onSubmit handler const onSubmit = studentObject => { axios.post('http://localhost:4000/students/create-student', studentObject) .then(res => { if (res.status === 200) alert('Student successfully created') else Promise.reject() }) .catch(err => alert('Something went wrong')) } // Return student form return( <StudentForm initialValues={formValues} onSubmit={onSubmit} enableReinitialize> Create Student </StudentForm> )} // Export CreateStudent Componentexport default CreateStudent
Step 8: Update student’s details: In this section, we will create a component to update details. We have reusable StudentForm component, let’s use it again. We will fetch student details to reinitialise form. Go to src/Components/edit-student.component.js and write the following code.
edit-student.component.js
// EditStudent Component for update student data // Import Modulesimport React, { useState, useEffect } from "react";import axios from "axios";import StudentForm from "./StudentForm"; // EditStudent Componentconst EditStudent = (props) => { const [formValues, setFormValues] = useState({ name: "", email: "", rollno: "", }); //onSubmit handler const onSubmit = (studentObject) => { axios .put( "http://localhost:4000/students/update-student/" + props.match.params.id, studentObject ) .then((res) => { if (res.status === 200) { alert("Student successfully updated"); props.history.push("/student-list"); } else Promise.reject(); }) .catch((err) => alert("Something went wrong")); }; // Load data from server and reinitialize student form useEffect(() => { axios .get( "http://localhost:4000/students/update-student/" + props.match.params.id ) .then((res) => { const { name, email, rollno } = res.data; setFormValues({ name, email, rollno }); }) .catch((err) => console.log(err)); }, []); // Return student form return ( <StudentForm initialValues={formValues} onSubmit={onSubmit} enableReinitialize > Update Student </StudentForm> );}; // Export EditStudent Componentexport default EditStudent;
Step 9: Display list of students: In this step, we will build a component to display the student details in a table. We will fetch student’s data and iterate over it to create table row for every student. Go to src/Components/student-list.component.js and write the following code.
student-list.component.js
import React, { useState, useEffect } from "react";import axios from "axios";import { Table } from "react-bootstrap";import StudentTableRow from "./StudentTableRow"; const StudentList = () => { const [students, setStudents] = useState([]); useEffect(() => { axios .get("http://localhost:4000/students/") .then(({ data }) => { setStudents(data); }) .catch((error) => { console.log(error); }); }, []); const DataTable = () => { return students.map((res, i) => { return <StudentTableRow obj={res} key={i} />; }); }; return ( <div className="table-wrapper"> <Table striped bordered hover> <thead> <tr> <th>Name</th> <th>Email</th> <th>Roll No</th> <th>Action</th> </tr> </thead> <tbody>{DataTable()}</tbody> </Table> </div> );}; export default StudentList;
Step 10: Display a single student: In this step, we will return table row which is responsible to display student data. Go to src/Components/StudentTableRow.js and write the following code.
StudentTableRow.js
import React from "react";import { Button } from "react-bootstrap";import { Link } from "react-router-dom";import axios from "axios"; const StudentTableRow = (props) => { const { _id, name, email, rollno } = props.obj; const deleteStudent = () => { axios .delete("http://localhost:4000/students/delete-student/" + _id) .then((res) => { if (res.status === 200) { alert("Student successfully deleted"); window.location.reload(); } else Promise.reject(); }) .catch((err) => alert("Something went wrong")); }; return ( <tr> <td>{name}</td> <td>{email}</td> <td>{rollno}</td> <td> <Link className="edit-link" to={"/edit-student/" + _id}> Edit </Link> <Button onClick={deleteStudent} size="sm" variant="danger"> Delete </Button> </td> </tr> );}; export default StudentTableRow;
Step 11: Edit App.js: Finally, include the menu to make routing in our MERN Stack CRUD app. Go to src/App.js and write the following code.
App.js
// Import Reactimport React from "react"; // Import Bootstrapimport { Nav, Navbar, Container, Row, Col } from "react-bootstrap";import "bootstrap/dist/css/bootstrap.css"; // Import Custom CSSimport "./App.css"; // Import from react-router-domimport { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; // Import other React Componentimport CreateStudent from "./Components/create-student.component";import EditStudent from "./Components/edit-student.component";import StudentList from "./Components/student-list.component"; // App Componentconst App = () => { return ( <Router> <div className="App"> <header className="App-header"> <Navbar bg="dark" variant="dark"> <Container> <Navbar.Brand> <Link to={"/create-student"} className="nav-link"> React MERN Stack App </Link> </Navbar.Brand> <Nav className="justify-content-end"> <Nav> <Link to={"/create-student"} className="nav-link"> Create Student </Link> </Nav> <Nav> <Link to={"/student-list"} className="nav-link"> Student List </Link> </Nav> </Nav> </Container> </Navbar> </header> <Container> <Row> <Col md={12}> <div className="wrapper"> <Switch> <Route exact path="/" component={CreateStudent} /> <Route path="/create-student" component={CreateStudent} /> <Route path="/edit-student/:id" component={EditStudent} /> <Route path="/student-list" component={StudentList} /> </Switch> </div> </Col> </Row> </Container> </div> </Router> );}; export default App;
Step 12: Add style – Go to src/App.css and write the following code.
App.css
.wrapper { padding-top: 30px;} body h3 { margin-bottom: 25px;} .navbar-brand a { color: #ffffff;} .form-wrapper,.table-wrapper { max-width: 500px; margin: 0 auto;} .table-wrapper { max-width: 700px;} .edit-link { padding: 7px 10px; font-size: 0.875rem; line-height: normal; border-radius: 0.2rem; color: #fff; background-color: #28a745; border-color: #28a745; margin-right: 10px; position: relative; top: 1px;} .edit-link:hover { text-decoration: none; color: #ffffff;} /* Chrome, Safari, Edge, Opera */input::-webkit-outer-spin-button,input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0;} /* Firefox */input[type=number] { -moz-appearance: textfield;}
Now, we have successfully created the frontend for our mern-stack-app. Let’s build the backend part. Before, jumping to next section take a look how the frontend part working without backend.
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Now we will work on the backend part of our application. We will create a folder inside our mern-stack-crud to manage the server services such as database, models, schema, routes and APIs, name this folder backend.
Step 1: Run command to create backend folder for server and get inside of it.
mkdir backend && cd backend
Step 2: Create package.json – Next, we need to create a separate package.json file for managing the server of our mern-stack-crud app.
npm init -y
Go to backend/package.json file will look like the following. Replace the test property like:
"test": "echo \"Error: no test specified\" && exit 1"
"start": "nodemon server.js"
Step 3: Install Node Dependencies – Install the following Node dependencies.
NPM
Detail
To install the above dependencies, run the following code on the terminal.
npm install express body-parser cors mongoose
You may install nodemon as dev dependency to automate the server restarting process.
npm i -D nodemon
Back-end project structure
back-end project structure
Step 4: Setting up MongoDB Database – In this step, we will set up a MongoDB database for our app. Before, starting make sure you have latest version of MongoDB is installed on your system. Create folder inside the backend folder and name it database. Create a file by the name of db.js inside the database folder. Go to backend/database/db.js and write the following code.
db.js
module.exports = { db: 'mongodb://localhost:27017/reactdb'};
We have declared the MongoDB database and name it reactdb.
Step 5: Define Mongoose Schema – Now, create MongoDB schema for interacting with MongoDB database. Create a folder called models inside backend folder to keep schema related files and create a file Student.js inside of it to define MongoDB schema. Go to backend/models/Student.js and write the following code.
Student.js
const mongoose = require('mongoose');const Schema = mongoose.Schema; let studentSchema = new Schema({ name: { type: String }, email: { type: String }, rollno: { type: Number }}, { collection: 'students' }) module.exports = mongoose.model('Student', studentSchema)
We declared name, email, and rollno fields along with their respective data types in student Schema.
Step 6: Create Routes Using ExpressJS – In this step, we are set up some routes (REST APIs) for CREATE, READ, UPDATE and DELETE using Express and Node.js. These routes will help us to manage the data in our mern-stack-crud app. Create a folder and name it routes inside backend folder. Here we will keep all the routes related files. Also, create a file and name it student.routes.js inside routes folder, in this file we will define our routes.
mkdir routes && cd routes && touch student.route.js
Then, go to backend/routes/student.route.js file and write the following code.
student.route.js
let mongoose = require("mongoose"), express = require("express"), router = express.Router(); // Student Modellet studentSchema = require("../models/Student"); // CREATE Studentrouter.post("/create-student", (req, res, next) => { studentSchema.create(req.body, (error, data) => { if (error) { return next(error); } else { console.log(data); res.json(data); } });}); // READ Studentsrouter.get("/", (req, res) => { studentSchema.find((error, data) => { if (error) { return next(error); } else { res.json(data); } });}); // UPDATE studentrouter .route("/update-student/:id") // Get Single Student .get((req, res) => { studentSchema.findById( req.params.id, (error, data) => { if (error) { return next(error); } else { res.json(data); } }); }) // Update Student Data .put((req, res, next) => { studentSchema.findByIdAndUpdate( req.params.id, { $set: req.body, }, (error, data) => { if (error) { return next(error); console.log(error); } else { res.json(data); console.log("Student updated successfully !"); } } ); }); // Delete Studentrouter.delete("/delete-student/:id", (req, res, next) => { studentSchema.findByIdAndRemove( req.params.id, (error, data) => { if (error) { return next(error); } else { res.status(200).json({ msg: data, }); } });}); module.exports = router;
Step 7: Configure server.js – We have almost created everything for our mern-stack-crud app. Now, create the server.js file in the root of the backend folder. Go to backend/server.js and write the following code.
server.js
let express = require('express');let mongoose = require('mongoose');let cors = require('cors');let bodyParser = require('body-parser');let dbConfig = require('./database/db'); // Express Routeconst studentRoute = require('../backend/routes/student.route') // Configure mongoDB Databasemongoose.set('useNewUrlParser', true);mongoose.set('useFindAndModify', false);mongoose.set('useCreateIndex', true);mongoose.set('useUnifiedTopology', true); // Connecting MongoDB Databasemongoose.Promise = global.Promise;mongoose.connect(dbConfig.db).then(() => { console.log('Database successfully connected!')}, error => { console.log('Could not connect to database : ' + error) }) const app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true}));app.use(cors());app.use('/students', studentRoute) // PORTconst port = process.env.PORT || 4000;const server = app.listen(port, () => { console.log('Connected to port ' + port)}) // 404 Errorapp.use((req, res, next) => { res.status(404).send('Error 404!')}); app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message);});
Now, we have successfully created the backend for our mern-stack-app.
Our final project directory structure:
project-directory-structure
Now, start the MongoDB database server to run the server.
Step to run the application: Open a terminal and run the following command to start the Nodemon server by staying in the backend folder.
npm start
If everything is working well you will see the following output on the terminal screen.
mern-stack-crud server-running
Final output:
mern-stack-crud-app
saurabh1990aror
rs1686740
sumitgumber28
Blogathon-2021
MongoDB-method
NodeJS-Questions
Picked
React-Questions
Blogathon
MongoDB
Node.js
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Data Mining - Cluster Analysis
Explain the purpose of render() in ReactJS
How to parse JSON Data into React Table Component ?
Spring Boot JpaRepository with Example
Upload and Retrieve Image on MongoDB using Mongoose
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Apr, 2022"
},
{
"code": null,
"e": 120,
"s": 54,
"text": "In this article, we will create a basic Student app from scratch."
},
{
"code": null,
"e": 140,
"s": 120,
"text": "App functionality: "
},
{
"code": null,
"e": 161,
"s": 140,
"text": "Create a new student"
},
{
"code": null,
"e": 188,
"s": 161,
"text": "Update an existing student"
},
{
"code": null,
"e": 207,
"s": 188,
"text": "Show students list"
},
{
"code": null,
"e": 224,
"s": 207,
"text": "Delete a student"
},
{
"code": null,
"e": 253,
"s": 226,
"text": "REST API in this project: "
},
{
"code": null,
"e": 263,
"s": 253,
"text": "REST API "
},
{
"code": null,
"e": 267,
"s": 263,
"text": "URL"
},
{
"code": null,
"e": 350,
"s": 267,
"text": "First of all, we will work on the frontend part of our application using React.js."
},
{
"code": null,
"e": 398,
"s": 350,
"text": "Create React Application and installing modules"
},
{
"code": null,
"e": 540,
"s": 398,
"text": "Step 1: Let’s start building the Front-end part with React. To create a new React App, enter the following code into terminal and hit enter. "
},
{
"code": null,
"e": 577,
"s": 540,
"text": "npx create-react-app mern-stack-crud"
},
{
"code": null,
"e": 621,
"s": 577,
"text": "Step 2: Move into the React project folder."
},
{
"code": null,
"e": 640,
"s": 621,
"text": "cd mern-stack-crud"
},
{
"code": null,
"e": 697,
"s": 640,
"text": "Step 3: To run the React App, run the following command:"
},
{
"code": null,
"e": 707,
"s": 697,
"text": "npm start"
},
{
"code": null,
"e": 800,
"s": 707,
"text": "This command opens the React App to the browser on the following URL: http://localhost:3000/"
},
{
"code": null,
"e": 874,
"s": 800,
"text": "Step 4: To build the React App we need to install some external modules. "
},
{
"code": null,
"e": 878,
"s": 874,
"text": "NPM"
},
{
"code": null,
"e": 885,
"s": 878,
"text": "Detail"
},
{
"code": null,
"e": 938,
"s": 885,
"text": "To install, run the following code on the terminal. "
},
{
"code": null,
"e": 1015,
"s": 938,
"text": "npm i react-bootstrap@next bootstrap@5.1.0 react-router-dom axios formik yup"
},
{
"code": null,
"e": 1132,
"s": 1015,
"text": "Step 5: Creating Simple React Components – In this step we will create some React Components to manage student data."
},
{
"code": null,
"e": 1253,
"s": 1132,
"text": "Head over to src folder, make a folder and name it Components and within that directory create the following components."
},
{
"code": null,
"e": 1292,
"s": 1253,
"text": "StudentForm.js – Reusable Student form"
},
{
"code": null,
"e": 1358,
"s": 1292,
"text": "create-student.component.js – Responsible for create new student "
},
{
"code": null,
"e": 1422,
"s": 1358,
"text": "edit-student.component.js – Responsible for update student data"
},
{
"code": null,
"e": 1486,
"s": 1422,
"text": "student-list.component.js – Responsible for display all student"
},
{
"code": null,
"e": 1550,
"s": 1486,
"text": "StudentTableRow.js – Responsible for display a single student "
},
{
"code": null,
"e": 1601,
"s": 1550,
"text": "Project Structure: It will look like the following"
},
{
"code": null,
"e": 1629,
"s": 1601,
"text": "front-end project structure"
},
{
"code": null,
"e": 2009,
"s": 1629,
"text": "Step 6: Create student form – In this step, we will build a reusable student form with Formik and React-Bootstrap. This form has all the necessary fields to enter student details. We have also made client-side form validation with Yup. In the future, we will use this component for creating and update a student. Go to src/Components/StudentForm.js and write the following code. "
},
{
"code": null,
"e": 2026,
"s": 2011,
"text": "StudentForm.js"
},
{
"code": "import React from \"react\";import * as Yup from \"yup\";import { Formik, Form, Field, ErrorMessage } from \"formik\";import { FormGroup, FormControl, Button } from \"react-bootstrap\"; const StudentForm = (props) => { const validationSchema = Yup.object().shape({ name: Yup.string().required(\"Required\"), email: Yup.string() .email(\"You have enter an invalid email address\") .required(\"Required\"), rollno: Yup.number() .positive(\"Invalid roll number\") .integer(\"Invalid roll number\") .required(\"Required\"), }); console.log(props); return ( <div className=\"form-wrapper\"> <Formik {...props} validationSchema={validationSchema}> <Form> <FormGroup> <Field name=\"name\" type=\"text\" className=\"form-control\" /> <ErrorMessage name=\"name\" className=\"d-block invalid-feedback\" component=\"span\" /> </FormGroup> <FormGroup> <Field name=\"email\" type=\"text\" className=\"form-control\" /> <ErrorMessage name=\"email\" className=\"d-block invalid-feedback\" component=\"span\" /> </FormGroup> <FormGroup> <Field name=\"rollno\" type=\"number\" className=\"form-control\" /> <ErrorMessage name=\"rollno\" className=\"d-block invalid-feedback\" component=\"span\" /> </FormGroup> <Button variant=\"danger\" size=\"lg\" block=\"block\" type=\"submit\"> {props.children} </Button> </Form> </Formik> </div> );}; export default StudentForm;",
"e": 3741,
"s": 2026,
"text": null
},
{
"code": null,
"e": 4028,
"s": 3741,
"text": "Step 7: Create a new student: In this step, we will create a component to add a new student. We have already created a StudentForm component to enter student details. Now, it’s time to use this component. Go to src/Components/create-student.component.js and write the following code. "
},
{
"code": null,
"e": 4056,
"s": 4028,
"text": "create-student.component.js"
},
{
"code": "// CreateStudent Component for add new student // Import Modulesimport React, { useState, useEffect } from \"react\";import axios from 'axios';import StudentForm from \"./StudentForm\"; // CreateStudent Componentconst CreateStudent = () => { const [formValues, setFormValues] = useState({ name: '', email: '', rollno: '' }) // onSubmit handler const onSubmit = studentObject => { axios.post('http://localhost:4000/students/create-student', studentObject) .then(res => { if (res.status === 200) alert('Student successfully created') else Promise.reject() }) .catch(err => alert('Something went wrong')) } // Return student form return( <StudentForm initialValues={formValues} onSubmit={onSubmit} enableReinitialize> Create Student </StudentForm> )} // Export CreateStudent Componentexport default CreateStudent",
"e": 4957,
"s": 4056,
"text": null
},
{
"code": null,
"e": 5245,
"s": 4957,
"text": "Step 8: Update student’s details: In this section, we will create a component to update details. We have reusable StudentForm component, let’s use it again. We will fetch student details to reinitialise form. Go to src/Components/edit-student.component.js and write the following code. "
},
{
"code": null,
"e": 5271,
"s": 5245,
"text": "edit-student.component.js"
},
{
"code": "// EditStudent Component for update student data // Import Modulesimport React, { useState, useEffect } from \"react\";import axios from \"axios\";import StudentForm from \"./StudentForm\"; // EditStudent Componentconst EditStudent = (props) => { const [formValues, setFormValues] = useState({ name: \"\", email: \"\", rollno: \"\", }); //onSubmit handler const onSubmit = (studentObject) => { axios .put( \"http://localhost:4000/students/update-student/\" + props.match.params.id, studentObject ) .then((res) => { if (res.status === 200) { alert(\"Student successfully updated\"); props.history.push(\"/student-list\"); } else Promise.reject(); }) .catch((err) => alert(\"Something went wrong\")); }; // Load data from server and reinitialize student form useEffect(() => { axios .get( \"http://localhost:4000/students/update-student/\" + props.match.params.id ) .then((res) => { const { name, email, rollno } = res.data; setFormValues({ name, email, rollno }); }) .catch((err) => console.log(err)); }, []); // Return student form return ( <StudentForm initialValues={formValues} onSubmit={onSubmit} enableReinitialize > Update Student </StudentForm> );}; // Export EditStudent Componentexport default EditStudent;",
"e": 6665,
"s": 5271,
"text": null
},
{
"code": null,
"e": 6948,
"s": 6665,
"text": "Step 9: Display list of students: In this step, we will build a component to display the student details in a table. We will fetch student’s data and iterate over it to create table row for every student. Go to src/Components/student-list.component.js and write the following code."
},
{
"code": null,
"e": 6974,
"s": 6948,
"text": "student-list.component.js"
},
{
"code": "import React, { useState, useEffect } from \"react\";import axios from \"axios\";import { Table } from \"react-bootstrap\";import StudentTableRow from \"./StudentTableRow\"; const StudentList = () => { const [students, setStudents] = useState([]); useEffect(() => { axios .get(\"http://localhost:4000/students/\") .then(({ data }) => { setStudents(data); }) .catch((error) => { console.log(error); }); }, []); const DataTable = () => { return students.map((res, i) => { return <StudentTableRow obj={res} key={i} />; }); }; return ( <div className=\"table-wrapper\"> <Table striped bordered hover> <thead> <tr> <th>Name</th> <th>Email</th> <th>Roll No</th> <th>Action</th> </tr> </thead> <tbody>{DataTable()}</tbody> </Table> </div> );}; export default StudentList;",
"e": 7894,
"s": 6974,
"text": null
},
{
"code": null,
"e": 8084,
"s": 7894,
"text": "Step 10: Display a single student: In this step, we will return table row which is responsible to display student data. Go to src/Components/StudentTableRow.js and write the following code."
},
{
"code": null,
"e": 8103,
"s": 8084,
"text": "StudentTableRow.js"
},
{
"code": "import React from \"react\";import { Button } from \"react-bootstrap\";import { Link } from \"react-router-dom\";import axios from \"axios\"; const StudentTableRow = (props) => { const { _id, name, email, rollno } = props.obj; const deleteStudent = () => { axios .delete(\"http://localhost:4000/students/delete-student/\" + _id) .then((res) => { if (res.status === 200) { alert(\"Student successfully deleted\"); window.location.reload(); } else Promise.reject(); }) .catch((err) => alert(\"Something went wrong\")); }; return ( <tr> <td>{name}</td> <td>{email}</td> <td>{rollno}</td> <td> <Link className=\"edit-link\" to={\"/edit-student/\" + _id}> Edit </Link> <Button onClick={deleteStudent} size=\"sm\" variant=\"danger\"> Delete </Button> </td> </tr> );}; export default StudentTableRow;",
"e": 9038,
"s": 8103,
"text": null
},
{
"code": null,
"e": 9178,
"s": 9038,
"text": "Step 11: Edit App.js: Finally, include the menu to make routing in our MERN Stack CRUD app. Go to src/App.js and write the following code. "
},
{
"code": null,
"e": 9185,
"s": 9178,
"text": "App.js"
},
{
"code": "// Import Reactimport React from \"react\"; // Import Bootstrapimport { Nav, Navbar, Container, Row, Col } from \"react-bootstrap\";import \"bootstrap/dist/css/bootstrap.css\"; // Import Custom CSSimport \"./App.css\"; // Import from react-router-domimport { BrowserRouter as Router, Switch, Route, Link } from \"react-router-dom\"; // Import other React Componentimport CreateStudent from \"./Components/create-student.component\";import EditStudent from \"./Components/edit-student.component\";import StudentList from \"./Components/student-list.component\"; // App Componentconst App = () => { return ( <Router> <div className=\"App\"> <header className=\"App-header\"> <Navbar bg=\"dark\" variant=\"dark\"> <Container> <Navbar.Brand> <Link to={\"/create-student\"} className=\"nav-link\"> React MERN Stack App </Link> </Navbar.Brand> <Nav className=\"justify-content-end\"> <Nav> <Link to={\"/create-student\"} className=\"nav-link\"> Create Student </Link> </Nav> <Nav> <Link to={\"/student-list\"} className=\"nav-link\"> Student List </Link> </Nav> </Nav> </Container> </Navbar> </header> <Container> <Row> <Col md={12}> <div className=\"wrapper\"> <Switch> <Route exact path=\"/\" component={CreateStudent} /> <Route path=\"/create-student\" component={CreateStudent} /> <Route path=\"/edit-student/:id\" component={EditStudent} /> <Route path=\"/student-list\" component={StudentList} /> </Switch> </div> </Col> </Row> </Container> </div> </Router> );}; export default App;",
"e": 11308,
"s": 9185,
"text": null
},
{
"code": null,
"e": 11378,
"s": 11308,
"text": "Step 12: Add style – Go to src/App.css and write the following code. "
},
{
"code": null,
"e": 11386,
"s": 11378,
"text": "App.css"
},
{
"code": ".wrapper { padding-top: 30px;} body h3 { margin-bottom: 25px;} .navbar-brand a { color: #ffffff;} .form-wrapper,.table-wrapper { max-width: 500px; margin: 0 auto;} .table-wrapper { max-width: 700px;} .edit-link { padding: 7px 10px; font-size: 0.875rem; line-height: normal; border-radius: 0.2rem; color: #fff; background-color: #28a745; border-color: #28a745; margin-right: 10px; position: relative; top: 1px;} .edit-link:hover { text-decoration: none; color: #ffffff;} /* Chrome, Safari, Edge, Opera */input::-webkit-outer-spin-button,input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0;} /* Firefox */input[type=number] { -moz-appearance: textfield;}",
"e": 12087,
"s": 11386,
"text": null
},
{
"code": null,
"e": 12279,
"s": 12087,
"text": "Now, we have successfully created the frontend for our mern-stack-app. Let’s build the backend part. Before, jumping to next section take a look how the frontend part working without backend."
},
{
"code": null,
"e": 12358,
"s": 12279,
"text": "Step to run the application: Open the terminal and type the following command."
},
{
"code": null,
"e": 12368,
"s": 12358,
"text": "npm start"
},
{
"code": null,
"e": 12376,
"s": 12368,
"text": "Output:"
},
{
"code": null,
"e": 12592,
"s": 12376,
"text": "Now we will work on the backend part of our application. We will create a folder inside our mern-stack-crud to manage the server services such as database, models, schema, routes and APIs, name this folder backend."
},
{
"code": null,
"e": 12670,
"s": 12592,
"text": "Step 1: Run command to create backend folder for server and get inside of it."
},
{
"code": null,
"e": 12698,
"s": 12670,
"text": "mkdir backend && cd backend"
},
{
"code": null,
"e": 12834,
"s": 12698,
"text": "Step 2: Create package.json – Next, we need to create a separate package.json file for managing the server of our mern-stack-crud app."
},
{
"code": null,
"e": 12846,
"s": 12834,
"text": "npm init -y"
},
{
"code": null,
"e": 12941,
"s": 12846,
"text": "Go to backend/package.json file will look like the following. Replace the test property like: "
},
{
"code": null,
"e": 13025,
"s": 12941,
"text": "\"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" \n\"start\": \"nodemon server.js\""
},
{
"code": null,
"e": 13103,
"s": 13025,
"text": "Step 3: Install Node Dependencies – Install the following Node dependencies. "
},
{
"code": null,
"e": 13107,
"s": 13103,
"text": "NPM"
},
{
"code": null,
"e": 13114,
"s": 13107,
"text": "Detail"
},
{
"code": null,
"e": 13190,
"s": 13114,
"text": "To install the above dependencies, run the following code on the terminal. "
},
{
"code": null,
"e": 13236,
"s": 13190,
"text": "npm install express body-parser cors mongoose"
},
{
"code": null,
"e": 13321,
"s": 13236,
"text": "You may install nodemon as dev dependency to automate the server restarting process."
},
{
"code": null,
"e": 13338,
"s": 13321,
"text": "npm i -D nodemon"
},
{
"code": null,
"e": 13365,
"s": 13338,
"text": "Back-end project structure"
},
{
"code": null,
"e": 13392,
"s": 13365,
"text": "back-end project structure"
},
{
"code": null,
"e": 13769,
"s": 13392,
"text": "Step 4: Setting up MongoDB Database – In this step, we will set up a MongoDB database for our app. Before, starting make sure you have latest version of MongoDB is installed on your system. Create folder inside the backend folder and name it database. Create a file by the name of db.js inside the database folder. Go to backend/database/db.js and write the following code. "
},
{
"code": null,
"e": 13775,
"s": 13769,
"text": "db.js"
},
{
"code": "module.exports = { db: 'mongodb://localhost:27017/reactdb'};",
"e": 13837,
"s": 13775,
"text": null
},
{
"code": null,
"e": 13897,
"s": 13837,
"text": "We have declared the MongoDB database and name it reactdb. "
},
{
"code": null,
"e": 14209,
"s": 13897,
"text": "Step 5: Define Mongoose Schema – Now, create MongoDB schema for interacting with MongoDB database. Create a folder called models inside backend folder to keep schema related files and create a file Student.js inside of it to define MongoDB schema. Go to backend/models/Student.js and write the following code. "
},
{
"code": null,
"e": 14220,
"s": 14209,
"text": "Student.js"
},
{
"code": "const mongoose = require('mongoose');const Schema = mongoose.Schema; let studentSchema = new Schema({ name: { type: String }, email: { type: String }, rollno: { type: Number }}, { collection: 'students' }) module.exports = mongoose.model('Student', studentSchema)",
"e": 14505,
"s": 14220,
"text": null
},
{
"code": null,
"e": 14606,
"s": 14505,
"text": "We declared name, email, and rollno fields along with their respective data types in student Schema."
},
{
"code": null,
"e": 15053,
"s": 14606,
"text": "Step 6: Create Routes Using ExpressJS – In this step, we are set up some routes (REST APIs) for CREATE, READ, UPDATE and DELETE using Express and Node.js. These routes will help us to manage the data in our mern-stack-crud app. Create a folder and name it routes inside backend folder. Here we will keep all the routes related files. Also, create a file and name it student.routes.js inside routes folder, in this file we will define our routes. "
},
{
"code": null,
"e": 15105,
"s": 15053,
"text": "mkdir routes && cd routes && touch student.route.js"
},
{
"code": null,
"e": 15185,
"s": 15105,
"text": "Then, go to backend/routes/student.route.js file and write the following code. "
},
{
"code": null,
"e": 15202,
"s": 15185,
"text": "student.route.js"
},
{
"code": "let mongoose = require(\"mongoose\"), express = require(\"express\"), router = express.Router(); // Student Modellet studentSchema = require(\"../models/Student\"); // CREATE Studentrouter.post(\"/create-student\", (req, res, next) => { studentSchema.create(req.body, (error, data) => { if (error) { return next(error); } else { console.log(data); res.json(data); } });}); // READ Studentsrouter.get(\"/\", (req, res) => { studentSchema.find((error, data) => { if (error) { return next(error); } else { res.json(data); } });}); // UPDATE studentrouter .route(\"/update-student/:id\") // Get Single Student .get((req, res) => { studentSchema.findById( req.params.id, (error, data) => { if (error) { return next(error); } else { res.json(data); } }); }) // Update Student Data .put((req, res, next) => { studentSchema.findByIdAndUpdate( req.params.id, { $set: req.body, }, (error, data) => { if (error) { return next(error); console.log(error); } else { res.json(data); console.log(\"Student updated successfully !\"); } } ); }); // Delete Studentrouter.delete(\"/delete-student/:id\", (req, res, next) => { studentSchema.findByIdAndRemove( req.params.id, (error, data) => { if (error) { return next(error); } else { res.status(200).json({ msg: data, }); } });}); module.exports = router;",
"e": 16712,
"s": 15202,
"text": null
},
{
"code": null,
"e": 16925,
"s": 16712,
"text": "Step 7: Configure server.js – We have almost created everything for our mern-stack-crud app. Now, create the server.js file in the root of the backend folder. Go to backend/server.js and write the following code."
},
{
"code": null,
"e": 16935,
"s": 16925,
"text": "server.js"
},
{
"code": "let express = require('express');let mongoose = require('mongoose');let cors = require('cors');let bodyParser = require('body-parser');let dbConfig = require('./database/db'); // Express Routeconst studentRoute = require('../backend/routes/student.route') // Configure mongoDB Databasemongoose.set('useNewUrlParser', true);mongoose.set('useFindAndModify', false);mongoose.set('useCreateIndex', true);mongoose.set('useUnifiedTopology', true); // Connecting MongoDB Databasemongoose.Promise = global.Promise;mongoose.connect(dbConfig.db).then(() => { console.log('Database successfully connected!')}, error => { console.log('Could not connect to database : ' + error) }) const app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true}));app.use(cors());app.use('/students', studentRoute) // PORTconst port = process.env.PORT || 4000;const server = app.listen(port, () => { console.log('Connected to port ' + port)}) // 404 Errorapp.use((req, res, next) => { res.status(404).send('Error 404!')}); app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message);});",
"e": 18144,
"s": 16935,
"text": null
},
{
"code": null,
"e": 18216,
"s": 18144,
"text": "Now, we have successfully created the backend for our mern-stack-app. "
},
{
"code": null,
"e": 18255,
"s": 18216,
"text": "Our final project directory structure:"
},
{
"code": null,
"e": 18283,
"s": 18255,
"text": "project-directory-structure"
},
{
"code": null,
"e": 18341,
"s": 18283,
"text": "Now, start the MongoDB database server to run the server."
},
{
"code": null,
"e": 18478,
"s": 18341,
"text": "Step to run the application: Open a terminal and run the following command to start the Nodemon server by staying in the backend folder."
},
{
"code": null,
"e": 18488,
"s": 18478,
"text": "npm start"
},
{
"code": null,
"e": 18577,
"s": 18488,
"text": "If everything is working well you will see the following output on the terminal screen. "
},
{
"code": null,
"e": 18608,
"s": 18577,
"text": "mern-stack-crud server-running"
},
{
"code": null,
"e": 18623,
"s": 18608,
"text": "Final output: "
},
{
"code": null,
"e": 18643,
"s": 18623,
"text": "mern-stack-crud-app"
},
{
"code": null,
"e": 18659,
"s": 18643,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 18669,
"s": 18659,
"text": "rs1686740"
},
{
"code": null,
"e": 18683,
"s": 18669,
"text": "sumitgumber28"
},
{
"code": null,
"e": 18698,
"s": 18683,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 18713,
"s": 18698,
"text": "MongoDB-method"
},
{
"code": null,
"e": 18730,
"s": 18713,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 18737,
"s": 18730,
"text": "Picked"
},
{
"code": null,
"e": 18753,
"s": 18737,
"text": "React-Questions"
},
{
"code": null,
"e": 18763,
"s": 18753,
"text": "Blogathon"
},
{
"code": null,
"e": 18771,
"s": 18763,
"text": "MongoDB"
},
{
"code": null,
"e": 18779,
"s": 18771,
"text": "Node.js"
},
{
"code": null,
"e": 18787,
"s": 18779,
"text": "ReactJS"
},
{
"code": null,
"e": 18885,
"s": 18787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18926,
"s": 18885,
"text": "How to Connect Python with SQL Database?"
},
{
"code": null,
"e": 18967,
"s": 18926,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 18998,
"s": 18967,
"text": "Data Mining - Cluster Analysis"
},
{
"code": null,
"e": 19041,
"s": 18998,
"text": "Explain the purpose of render() in ReactJS"
},
{
"code": null,
"e": 19093,
"s": 19041,
"text": "How to parse JSON Data into React Table Component ?"
},
{
"code": null,
"e": 19132,
"s": 19093,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 19184,
"s": 19132,
"text": "Upload and Retrieve Image on MongoDB using Mongoose"
},
{
"code": null,
"e": 19211,
"s": 19184,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 19249,
"s": 19211,
"text": "MongoDB - db.collection.Find() Method"
}
] |
Javascript | Window Open() & Window Close() Method
|
15 Jun, 2022
Window.open(): This method is used to open the web pages into a new window.
Syntax:
window.open(URL, name, specs, replace)
Parameters: This method accepts four parameters as mentioned above and described below:
URL: It is an optional parameter. It is used to set the URL of web pages which need to open. If URL is not set then window.open() method open a blank window.
name: It is an optional parameter and is used to set the window name.
specs: It is an optional parameter used to separate the item using a comma.
replace: It is an optional parameter and used to specify the URL URL creates a new entry or replaces the current entry in the history list. This parameter returns a boolean value. If this parameter returns true then URL replaces the current document in the history list and if returns false then URL creates a new entry in the history list.
Return Value: This method creates a new window.
Window.close(): This method is used to close the window which is opened by the window.open() method.
Syntax:
window.close()
Parameters: This method does not contain any parameters.
Return Value: This method does not return any value. Below example illustrates the window.open() and window.close() method in jQuery.
Example:
HTML
<!DOCTYPE html><html> <head> <title> window open and close method </title> <style> body { display: flex; flex-direction: column; justify-content: center; align-items: center; } .container { position: relative; text-align: center; } </style> <script> var Window; // Function that open the new Window function windowOpen() { Window = window.open( "https://www.geeksforgeeks.org/", "_blank", "width=400, height=300, top=230, left=540"); } // function that Closes the open Window function windowClose() { Window.close(); } </script></head> <body> <div class="container"> <h1 style="color: rgb(18, 154, 18);">GeeksforGeeks</h1> <button onclick="windowOpen()"> Open GeeksforGeeks </button> <button onclick="windowClose()"> Close GeeksforGeeks </button> </div></body> </html>
Output:
After Clicking on Open GeeksforGeeks:
If you click on the Open GeeksforGeeks button then the geeksforgeeks.org page opens in a new window and if you click on the close GeeksforGeeks button then the geeksforgeeks.org windows will close.
Supported Browser: The browsers are supported by the window.open() & window.close() method are listed below:
Chrome version 1 and above
Edge version 12 and above
Firefox version 1 and above
Internet Explorer version 4 and above
Opera version 3 and above
Safari version 1 and above
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
satyamm09
sanjyotpanure
javascript-functions
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "Window.open(): This method is used to open the web pages into a new window. "
},
{
"code": null,
"e": 113,
"s": 105,
"text": "Syntax:"
},
{
"code": null,
"e": 152,
"s": 113,
"text": "window.open(URL, name, specs, replace)"
},
{
"code": null,
"e": 240,
"s": 152,
"text": "Parameters: This method accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 398,
"s": 240,
"text": "URL: It is an optional parameter. It is used to set the URL of web pages which need to open. If URL is not set then window.open() method open a blank window."
},
{
"code": null,
"e": 468,
"s": 398,
"text": "name: It is an optional parameter and is used to set the window name."
},
{
"code": null,
"e": 544,
"s": 468,
"text": "specs: It is an optional parameter used to separate the item using a comma."
},
{
"code": null,
"e": 885,
"s": 544,
"text": "replace: It is an optional parameter and used to specify the URL URL creates a new entry or replaces the current entry in the history list. This parameter returns a boolean value. If this parameter returns true then URL replaces the current document in the history list and if returns false then URL creates a new entry in the history list."
},
{
"code": null,
"e": 934,
"s": 885,
"text": "Return Value: This method creates a new window. "
},
{
"code": null,
"e": 1036,
"s": 934,
"text": "Window.close(): This method is used to close the window which is opened by the window.open() method. "
},
{
"code": null,
"e": 1044,
"s": 1036,
"text": "Syntax:"
},
{
"code": null,
"e": 1059,
"s": 1044,
"text": "window.close()"
},
{
"code": null,
"e": 1117,
"s": 1059,
"text": "Parameters: This method does not contain any parameters. "
},
{
"code": null,
"e": 1251,
"s": 1117,
"text": "Return Value: This method does not return any value. Below example illustrates the window.open() and window.close() method in jQuery."
},
{
"code": null,
"e": 1261,
"s": 1251,
"text": "Example: "
},
{
"code": null,
"e": 1266,
"s": 1261,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> window open and close method </title> <style> body { display: flex; flex-direction: column; justify-content: center; align-items: center; } .container { position: relative; text-align: center; } </style> <script> var Window; // Function that open the new Window function windowOpen() { Window = window.open( \"https://www.geeksforgeeks.org/\", \"_blank\", \"width=400, height=300, top=230, left=540\"); } // function that Closes the open Window function windowClose() { Window.close(); } </script></head> <body> <div class=\"container\"> <h1 style=\"color: rgb(18, 154, 18);\">GeeksforGeeks</h1> <button onclick=\"windowOpen()\"> Open GeeksforGeeks </button> <button onclick=\"windowClose()\"> Close GeeksforGeeks </button> </div></body> </html>",
"e": 2320,
"s": 1266,
"text": null
},
{
"code": null,
"e": 2329,
"s": 2320,
"text": "Output: "
},
{
"code": null,
"e": 2370,
"s": 2331,
"text": "After Clicking on Open GeeksforGeeks: "
},
{
"code": null,
"e": 2570,
"s": 2372,
"text": "If you click on the Open GeeksforGeeks button then the geeksforgeeks.org page opens in a new window and if you click on the close GeeksforGeeks button then the geeksforgeeks.org windows will close."
},
{
"code": null,
"e": 2681,
"s": 2572,
"text": "Supported Browser: The browsers are supported by the window.open() & window.close() method are listed below:"
},
{
"code": null,
"e": 2708,
"s": 2681,
"text": "Chrome version 1 and above"
},
{
"code": null,
"e": 2734,
"s": 2708,
"text": "Edge version 12 and above"
},
{
"code": null,
"e": 2762,
"s": 2734,
"text": "Firefox version 1 and above"
},
{
"code": null,
"e": 2800,
"s": 2762,
"text": "Internet Explorer version 4 and above"
},
{
"code": null,
"e": 2827,
"s": 2800,
"text": "Opera version 3 and above"
},
{
"code": null,
"e": 2854,
"s": 2827,
"text": "Safari version 1 and above"
},
{
"code": null,
"e": 3073,
"s": 2854,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3272,
"s": 3073,
"text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 3282,
"s": 3272,
"text": "satyamm09"
},
{
"code": null,
"e": 3296,
"s": 3282,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 3317,
"s": 3296,
"text": "javascript-functions"
},
{
"code": null,
"e": 3328,
"s": 3317,
"text": "JavaScript"
}
] |
SQL Full Form
|
12 Jun, 2020
SQL is a declarative language laying its basics on relation algebra. It is a standardized language supported by all major commercial databases. The query optimizer is an important component of SQL which takes an input the SQL query and executes, it in the fastest way possible.
These are main classification of SQL queries:
Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows.Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views.
Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows.
Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views.
A basic SQL query has the following syntax:
SELECT (attribute list)
FROM (table list)
[WHERE (condition)]
[GROUP BY (grouping attributes)]
[HAVING (group condition)]
[ORDER BY (attribute list)]
where the SELECT and FROM clauses are mandatory.
The SELECT clause lists the attributes to be retrieved.The FROM Clause specifies all tablesThe WHERE clause specifies the conditions for selection of records from these tables, including join conditions.GROUP BY specifies grouping attributesHAVING specifies a condition for retrieval of groups.
The SELECT clause lists the attributes to be retrieved.
The FROM Clause specifies all tables
The WHERE clause specifies the conditions for selection of records from these tables, including join conditions.
GROUP BY specifies grouping attributes
HAVING specifies a condition for retrieval of groups.
Various aggregator functions COUNT, SUM, MIN, MAX, and AVG can be in conjunction with grouping. ORDER BY specifies an order for displaying the result of a query.
Characteristics :
Tables, also called as relations are represented by a name, not exceeding 20 characters in length.
The table names as well as the column fields should have unique names.
While table definition, the field list is separated using commas, and each field name consists of a data type followed by length attribute enclosed in brackets.
SQL statements must end with a semicolon.
Advantages :
High performance.
Easily compatible with most of the databases like MS Access, MS SQL server.
Good flexibility in terms of creation of new Data Base tables and deletion of redundant tables.
Can handle large records and multiple transactions.
Easily accessible in the form of an open-source programming language.
High Security: Tables, procedures and views can easily be protected using permissions
Easy to learn and understand data
Disadvantages :
Complex interface to understand and deal with it.
Higher cost required to set up.
It is a platform dependent and compound based language.
Extra space is required for each record storage.
Partial control given to databases, due to hidden permissions.
Picked
DBMS
Full Form
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "SQL is a declarative language laying its basics on relation algebra. It is a standardized language supported by all major commercial databases. The query optimizer is an important component of SQL which takes an input the SQL query and executes, it in the fastest way possible."
},
{
"code": null,
"e": 352,
"s": 306,
"text": "These are main classification of SQL queries:"
},
{
"code": null,
"e": 591,
"s": 352,
"text": "Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows.Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views."
},
{
"code": null,
"e": 708,
"s": 591,
"text": "Data Manipulation Language (DML) –It deals with the queries related to insertion, deletion and modification of rows."
},
{
"code": null,
"e": 831,
"s": 708,
"text": "Data Definition Language (DDL) –It deals with the creation, deletion and modification of definitions for tables and views."
},
{
"code": null,
"e": 875,
"s": 831,
"text": "A basic SQL query has the following syntax:"
},
{
"code": null,
"e": 1028,
"s": 875,
"text": "SELECT (attribute list)\nFROM (table list)\n[WHERE (condition)]\n[GROUP BY (grouping attributes)]\n[HAVING (group condition)]\n[ORDER BY (attribute list)] "
},
{
"code": null,
"e": 1077,
"s": 1028,
"text": "where the SELECT and FROM clauses are mandatory."
},
{
"code": null,
"e": 1372,
"s": 1077,
"text": "The SELECT clause lists the attributes to be retrieved.The FROM Clause specifies all tablesThe WHERE clause specifies the conditions for selection of records from these tables, including join conditions.GROUP BY specifies grouping attributesHAVING specifies a condition for retrieval of groups."
},
{
"code": null,
"e": 1428,
"s": 1372,
"text": "The SELECT clause lists the attributes to be retrieved."
},
{
"code": null,
"e": 1465,
"s": 1428,
"text": "The FROM Clause specifies all tables"
},
{
"code": null,
"e": 1578,
"s": 1465,
"text": "The WHERE clause specifies the conditions for selection of records from these tables, including join conditions."
},
{
"code": null,
"e": 1617,
"s": 1578,
"text": "GROUP BY specifies grouping attributes"
},
{
"code": null,
"e": 1671,
"s": 1617,
"text": "HAVING specifies a condition for retrieval of groups."
},
{
"code": null,
"e": 1833,
"s": 1671,
"text": "Various aggregator functions COUNT, SUM, MIN, MAX, and AVG can be in conjunction with grouping. ORDER BY specifies an order for displaying the result of a query."
},
{
"code": null,
"e": 1851,
"s": 1833,
"text": "Characteristics :"
},
{
"code": null,
"e": 1950,
"s": 1851,
"text": "Tables, also called as relations are represented by a name, not exceeding 20 characters in length."
},
{
"code": null,
"e": 2021,
"s": 1950,
"text": "The table names as well as the column fields should have unique names."
},
{
"code": null,
"e": 2182,
"s": 2021,
"text": "While table definition, the field list is separated using commas, and each field name consists of a data type followed by length attribute enclosed in brackets."
},
{
"code": null,
"e": 2224,
"s": 2182,
"text": "SQL statements must end with a semicolon."
},
{
"code": null,
"e": 2237,
"s": 2224,
"text": "Advantages :"
},
{
"code": null,
"e": 2255,
"s": 2237,
"text": "High performance."
},
{
"code": null,
"e": 2331,
"s": 2255,
"text": "Easily compatible with most of the databases like MS Access, MS SQL server."
},
{
"code": null,
"e": 2427,
"s": 2331,
"text": "Good flexibility in terms of creation of new Data Base tables and deletion of redundant tables."
},
{
"code": null,
"e": 2479,
"s": 2427,
"text": "Can handle large records and multiple transactions."
},
{
"code": null,
"e": 2549,
"s": 2479,
"text": "Easily accessible in the form of an open-source programming language."
},
{
"code": null,
"e": 2635,
"s": 2549,
"text": "High Security: Tables, procedures and views can easily be protected using permissions"
},
{
"code": null,
"e": 2669,
"s": 2635,
"text": "Easy to learn and understand data"
},
{
"code": null,
"e": 2685,
"s": 2669,
"text": "Disadvantages :"
},
{
"code": null,
"e": 2735,
"s": 2685,
"text": "Complex interface to understand and deal with it."
},
{
"code": null,
"e": 2767,
"s": 2735,
"text": "Higher cost required to set up."
},
{
"code": null,
"e": 2823,
"s": 2767,
"text": "It is a platform dependent and compound based language."
},
{
"code": null,
"e": 2872,
"s": 2823,
"text": "Extra space is required for each record storage."
},
{
"code": null,
"e": 2935,
"s": 2872,
"text": "Partial control given to databases, due to hidden permissions."
},
{
"code": null,
"e": 2942,
"s": 2935,
"text": "Picked"
},
{
"code": null,
"e": 2947,
"s": 2942,
"text": "DBMS"
},
{
"code": null,
"e": 2957,
"s": 2947,
"text": "Full Form"
},
{
"code": null,
"e": 2965,
"s": 2957,
"text": "GATE CS"
},
{
"code": null,
"e": 2970,
"s": 2965,
"text": "DBMS"
}
] |
Program to find value of 1^k + 2^k + 3^k + ... + n^k
|
10 Jun, 2021
Given two positive integers N and K. The task is to evaluate the value of 1K + 2 K + 3K + ... + NK.Examples
Input: N = 3, K = 4 Output: 98 Explanation: ∑(x4) = 14 + 24 + 34, where 1 ≤ x ≤ N ∑(x4) = 1 + 16 + 81 ∑(x4) = 98Input: N = 8, K = 4 Output: 8772
Approach:
The idea is to find the value of xK using pow() function. (where x is from 1 to N).The required sum is the summation of all values calculated above.
The idea is to find the value of xK using pow() function. (where x is from 1 to N).
The required sum is the summation of all values calculated above.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ Program to find the value// 1^K + 2^K + 3^K + .. + N^K#include <bits/stdc++.h>using namespace std; // Function to find value of// 1^K + 2^K + 3^K + .. + N^Kint findSum(int N, int k){ // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += pow(i, k); } // Return the sum return sum;} // Drivers Codeint main(){ int N = 8, k = 4; // Function call to // find the sum cout << findSum(N, k) << endl; return 0;}
// Java Program to find the value// 1^K + 2^K + 3^K + .. + N^Kclass GFG { // Function to find value of // 1^K + 2^K + 3^K + .. + N^K static int findSum(int N, int k) { // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += (int)Math.pow(i, k); } // Return the sum return sum; } // Drivers Code public static void main (String[] args) { int N = 8, k = 4; // Function call to // find the sum System.out.println(findSum(N, k)); }} // This code is contributed by AnkitRai01
# Python 3 Program to find the value# 1^K + 2^K + 3^K + .. + N^Kfrom math import pow # Function to find value of# 1^K + 2^K + 3^K + .. + N^Kdef findSum(N, k): # Initialise sum to 0 sum = 0 for i in range(1, N + 1, 1): # Find the value of # pow(i, 4) and then # add it to the sum sum += pow(i, k) # Return the sum return sum # Drives Codeif __name__ == '__main__': N = 8 k = 4 # Function call to # find the sum print(int(findSum(N, k))) # This code is contributed by Surendra_Gangwar
// C# Program to find the value// 1^K + 2^K + 3^K + .. + N^K using System; public class GFG { // Function to find value of // 1^K + 2^K + 3^K + .. + N^K static int findSum(int N, int k) { // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += (int)Math.Pow(i, k); } // Return the sum return sum; } // Drivers Code public static void Main (string[] args) { int N = 8, k = 4; // Function call to // find the sum Console.WriteLine(findSum(N, k)); } } // This code is contributed by AnkitRai01
<script> // Javascript Program to find the value // 1^K + 2^K + 3^K + .. + N^K // Function to find value of // 1^K + 2^K + 3^K + .. + N^K function findSum(N, k) { // Initialise sum to 0 let sum = 0; for (let i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += Math.pow(i, k); } // Return the sum return sum; } let N = 8, k = 4; // Function call to // find the sum document.write(findSum(N, k)); // This code is contributed by divyesh072019.</script>
8772
Time Complexity: O(N)
SURENDRA_GANGWAR
ankthon
divyesh072019
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Product of Array except itself
Find Union and Intersection of two unsorted arrays
Median of two sorted arrays of same size
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 164,
"s": 54,
"text": "Given two positive integers N and K. The task is to evaluate the value of 1K + 2 K + 3K + ... + NK.Examples "
},
{
"code": null,
"e": 311,
"s": 164,
"text": "Input: N = 3, K = 4 Output: 98 Explanation: ∑(x4) = 14 + 24 + 34, where 1 ≤ x ≤ N ∑(x4) = 1 + 16 + 81 ∑(x4) = 98Input: N = 8, K = 4 Output: 8772 "
},
{
"code": null,
"e": 324,
"s": 313,
"text": "Approach: "
},
{
"code": null,
"e": 473,
"s": 324,
"text": "The idea is to find the value of xK using pow() function. (where x is from 1 to N).The required sum is the summation of all values calculated above."
},
{
"code": null,
"e": 557,
"s": 473,
"text": "The idea is to find the value of xK using pow() function. (where x is from 1 to N)."
},
{
"code": null,
"e": 623,
"s": 557,
"text": "The required sum is the summation of all values calculated above."
},
{
"code": null,
"e": 676,
"s": 623,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 680,
"s": 676,
"text": "C++"
},
{
"code": null,
"e": 685,
"s": 680,
"text": "Java"
},
{
"code": null,
"e": 694,
"s": 685,
"text": "Python 3"
},
{
"code": null,
"e": 697,
"s": 694,
"text": "C#"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "Javascript"
},
{
"code": "// C++ Program to find the value// 1^K + 2^K + 3^K + .. + N^K#include <bits/stdc++.h>using namespace std; // Function to find value of// 1^K + 2^K + 3^K + .. + N^Kint findSum(int N, int k){ // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += pow(i, k); } // Return the sum return sum;} // Drivers Codeint main(){ int N = 8, k = 4; // Function call to // find the sum cout << findSum(N, k) << endl; return 0;}",
"e": 1267,
"s": 708,
"text": null
},
{
"code": "// Java Program to find the value// 1^K + 2^K + 3^K + .. + N^Kclass GFG { // Function to find value of // 1^K + 2^K + 3^K + .. + N^K static int findSum(int N, int k) { // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += (int)Math.pow(i, k); } // Return the sum return sum; } // Drivers Code public static void main (String[] args) { int N = 8, k = 4; // Function call to // find the sum System.out.println(findSum(N, k)); }} // This code is contributed by AnkitRai01",
"e": 1986,
"s": 1267,
"text": null
},
{
"code": "# Python 3 Program to find the value# 1^K + 2^K + 3^K + .. + N^Kfrom math import pow # Function to find value of# 1^K + 2^K + 3^K + .. + N^Kdef findSum(N, k): # Initialise sum to 0 sum = 0 for i in range(1, N + 1, 1): # Find the value of # pow(i, 4) and then # add it to the sum sum += pow(i, k) # Return the sum return sum # Drives Codeif __name__ == '__main__': N = 8 k = 4 # Function call to # find the sum print(int(findSum(N, k))) # This code is contributed by Surendra_Gangwar",
"e": 2543,
"s": 1986,
"text": null
},
{
"code": "// C# Program to find the value// 1^K + 2^K + 3^K + .. + N^K using System; public class GFG { // Function to find value of // 1^K + 2^K + 3^K + .. + N^K static int findSum(int N, int k) { // Initialise sum to 0 int sum = 0; for (int i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += (int)Math.Pow(i, k); } // Return the sum return sum; } // Drivers Code public static void Main (string[] args) { int N = 8, k = 4; // Function call to // find the sum Console.WriteLine(findSum(N, k)); } } // This code is contributed by AnkitRai01",
"e": 3282,
"s": 2543,
"text": null
},
{
"code": "<script> // Javascript Program to find the value // 1^K + 2^K + 3^K + .. + N^K // Function to find value of // 1^K + 2^K + 3^K + .. + N^K function findSum(N, k) { // Initialise sum to 0 let sum = 0; for (let i = 1; i <= N; i++) { // Find the value of // pow(i, 4) and then // add it to the sum sum += Math.pow(i, k); } // Return the sum return sum; } let N = 8, k = 4; // Function call to // find the sum document.write(findSum(N, k)); // This code is contributed by divyesh072019.</script>",
"e": 3923,
"s": 3282,
"text": null
},
{
"code": null,
"e": 3928,
"s": 3923,
"text": "8772"
},
{
"code": null,
"e": 3953,
"s": 3930,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 3970,
"s": 3953,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 3978,
"s": 3970,
"text": "ankthon"
},
{
"code": null,
"e": 3992,
"s": 3978,
"text": "divyesh072019"
},
{
"code": null,
"e": 4005,
"s": 3992,
"text": "Mathematical"
},
{
"code": null,
"e": 4018,
"s": 4005,
"text": "Mathematical"
},
{
"code": null,
"e": 4116,
"s": 4018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4148,
"s": 4116,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4192,
"s": 4148,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 4238,
"s": 4192,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 4280,
"s": 4238,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 4305,
"s": 4280,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 4337,
"s": 4305,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 4372,
"s": 4337,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 4403,
"s": 4372,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 4454,
"s": 4403,
"text": "Find Union and Intersection of two unsorted arrays"
}
] |
Set Theory Operations in Relational Algebra
|
14 May, 2020
Prerequisite – Relational Algebra in DBMSThese Set Theory operations are the standard mathematical operations on set. These operations are Binary operation that is, these are operated on 2 relations unlike PROJECT, SELECT and RENAME operations. These operations are used to merge 2 sets in various ways.
The set operation are mainly categorized into the following:
Union operationIntersection operationSet difference or Minus operation
Union operation
Intersection operation
Set difference or Minus operation
Before we apply one of the 3 set operations on relations, the two relations on which we are performing the operations must have same type of tuples. This is also known as be Union compatibility (or Type compatibility).
Type compatibility: Two relations A(P1, P2, ..., Pn) and B(Q1, Q2, ..., Qn) are said to be Type compatible (or Union compatible) if both the relation have same degree ‘k’ and
domain(Pi) = domain(Qi) for 1<= i <= k.
1. UNION Operation:
Notation:
A ∪ S
where, A and S are the relations,
symbol ‘∪’ is used to denote the Union operator.
The result of Union operation, which is denoted by A ∪ S, is a relation that basically includes all the tuples that are present in A or in S, or in both, eliminating the duplicate tuples.
Important points on UNION Operation:
1. The UNION operation is commutative, that is :
A ∪ B = B ∪ A
2. The UNION is associative, that means it is applicable to any number of relation.
A ∪ ( B ∪ C ) = ( A ∪ B ) ∪ C
3. In SQL, the operation UNION is as same as UNION operation here.
4. Moreover, In SQL there is multiset operation UNION ALL.
2. INTERSECTION Operation:
Notations:
A ∩ S
where, A and S are the relations,
symbol ‘∩’ is used to denote the Intersection operator.
The result of Intersection operation, which is denoted by A ∩ S, is a relation that basically includes all the tuples that are present in both A an S.
Important points on INTERSECTION Operation:
1. The INTERSECTION operation is commutative, that is :
A ∩ B = B ∩ A
2. The INTERSECTION is associative, that means it is applicable to any number of relation.
A ∩ ( B ∩ C ) = ( A ∩ B ) ∩ C
3. INTERSECTION can be formed using UNION and MINUS as follows:
A ∩ B = ((A ∪ B) - (A - B)) - (B - A)
4. In SQL, the operation INTERSECT is as same as INTERSECTION operation here.
5. Moreover, In SQL there is multiset operation INTERSECT ALL.
3. MINUS (or SET DIFFERENCE) Operation:
Notations:
A - S
where, A and S are the relations,
symbol ‘ – ’ is used to denote the Minus operator.
The result of Intersection operation, which is denoted by A – S, is a relation that basically includes all the tuples that are present in A but not in S.
Important points on MINUS (or SET DIFFERENCE) Operation:
1. The SET DIFFERENCE operation is not commutative, that means :
A - B != B - A
2. In SQL, the operation EXCEPT is as same as MINUS operation here.
3. Moreover, In SQL there is multiset operation EXCEPT ALL.
Example:Consider a relation Student(FIRST, LAST) and Faculty(FIRSTN, LASTN) given below :
1. Student UNION Faculty :
Student ∪ Faculty
2. Student INTERSECTION Faculty :
Student ∩ Faculty
3. Student MINUS Faculty :
Student - Faculty
DBMS-Relational Algebra
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Interview Questions
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 356,
"s": 52,
"text": "Prerequisite – Relational Algebra in DBMSThese Set Theory operations are the standard mathematical operations on set. These operations are Binary operation that is, these are operated on 2 relations unlike PROJECT, SELECT and RENAME operations. These operations are used to merge 2 sets in various ways."
},
{
"code": null,
"e": 417,
"s": 356,
"text": "The set operation are mainly categorized into the following:"
},
{
"code": null,
"e": 488,
"s": 417,
"text": "Union operationIntersection operationSet difference or Minus operation"
},
{
"code": null,
"e": 504,
"s": 488,
"text": "Union operation"
},
{
"code": null,
"e": 527,
"s": 504,
"text": "Intersection operation"
},
{
"code": null,
"e": 561,
"s": 527,
"text": "Set difference or Minus operation"
},
{
"code": null,
"e": 780,
"s": 561,
"text": "Before we apply one of the 3 set operations on relations, the two relations on which we are performing the operations must have same type of tuples. This is also known as be Union compatibility (or Type compatibility)."
},
{
"code": null,
"e": 955,
"s": 780,
"text": "Type compatibility: Two relations A(P1, P2, ..., Pn) and B(Q1, Q2, ..., Qn) are said to be Type compatible (or Union compatible) if both the relation have same degree ‘k’ and"
},
{
"code": null,
"e": 996,
"s": 955,
"text": "domain(Pi) = domain(Qi) for 1<= i <= k. "
},
{
"code": null,
"e": 1016,
"s": 996,
"text": "1. UNION Operation:"
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": "Notation: "
},
{
"code": null,
"e": 1034,
"s": 1027,
"text": "A ∪ S\n"
},
{
"code": null,
"e": 1068,
"s": 1034,
"text": "where, A and S are the relations,"
},
{
"code": null,
"e": 1118,
"s": 1068,
"text": "symbol ‘∪’ is used to denote the Union operator."
},
{
"code": null,
"e": 1306,
"s": 1118,
"text": "The result of Union operation, which is denoted by A ∪ S, is a relation that basically includes all the tuples that are present in A or in S, or in both, eliminating the duplicate tuples."
},
{
"code": null,
"e": 1343,
"s": 1306,
"text": "Important points on UNION Operation:"
},
{
"code": null,
"e": 1392,
"s": 1343,
"text": "1. The UNION operation is commutative, that is :"
},
{
"code": null,
"e": 1406,
"s": 1392,
"text": "A ∪ B = B ∪ A"
},
{
"code": null,
"e": 1490,
"s": 1406,
"text": "2. The UNION is associative, that means it is applicable to any number of relation."
},
{
"code": null,
"e": 1520,
"s": 1490,
"text": "A ∪ ( B ∪ C ) = ( A ∪ B ) ∪ C"
},
{
"code": null,
"e": 1587,
"s": 1520,
"text": "3. In SQL, the operation UNION is as same as UNION operation here."
},
{
"code": null,
"e": 1646,
"s": 1587,
"text": "4. Moreover, In SQL there is multiset operation UNION ALL."
},
{
"code": null,
"e": 1673,
"s": 1646,
"text": "2. INTERSECTION Operation:"
},
{
"code": null,
"e": 1684,
"s": 1673,
"text": "Notations:"
},
{
"code": null,
"e": 1691,
"s": 1684,
"text": "A ∩ S\n"
},
{
"code": null,
"e": 1725,
"s": 1691,
"text": "where, A and S are the relations,"
},
{
"code": null,
"e": 1782,
"s": 1725,
"text": "symbol ‘∩’ is used to denote the Intersection operator."
},
{
"code": null,
"e": 1933,
"s": 1782,
"text": "The result of Intersection operation, which is denoted by A ∩ S, is a relation that basically includes all the tuples that are present in both A an S."
},
{
"code": null,
"e": 1977,
"s": 1933,
"text": "Important points on INTERSECTION Operation:"
},
{
"code": null,
"e": 2033,
"s": 1977,
"text": "1. The INTERSECTION operation is commutative, that is :"
},
{
"code": null,
"e": 2047,
"s": 2033,
"text": "A ∩ B = B ∩ A"
},
{
"code": null,
"e": 2138,
"s": 2047,
"text": "2. The INTERSECTION is associative, that means it is applicable to any number of relation."
},
{
"code": null,
"e": 2168,
"s": 2138,
"text": "A ∩ ( B ∩ C ) = ( A ∩ B ) ∩ C"
},
{
"code": null,
"e": 2232,
"s": 2168,
"text": "3. INTERSECTION can be formed using UNION and MINUS as follows:"
},
{
"code": null,
"e": 2270,
"s": 2232,
"text": "A ∩ B = ((A ∪ B) - (A - B)) - (B - A)"
},
{
"code": null,
"e": 2348,
"s": 2270,
"text": "4. In SQL, the operation INTERSECT is as same as INTERSECTION operation here."
},
{
"code": null,
"e": 2411,
"s": 2348,
"text": "5. Moreover, In SQL there is multiset operation INTERSECT ALL."
},
{
"code": null,
"e": 2451,
"s": 2411,
"text": "3. MINUS (or SET DIFFERENCE) Operation:"
},
{
"code": null,
"e": 2462,
"s": 2451,
"text": "Notations:"
},
{
"code": null,
"e": 2469,
"s": 2462,
"text": "A - S\n"
},
{
"code": null,
"e": 2503,
"s": 2469,
"text": "where, A and S are the relations,"
},
{
"code": null,
"e": 2555,
"s": 2503,
"text": "symbol ‘ – ’ is used to denote the Minus operator."
},
{
"code": null,
"e": 2709,
"s": 2555,
"text": "The result of Intersection operation, which is denoted by A – S, is a relation that basically includes all the tuples that are present in A but not in S."
},
{
"code": null,
"e": 2766,
"s": 2709,
"text": "Important points on MINUS (or SET DIFFERENCE) Operation:"
},
{
"code": null,
"e": 2831,
"s": 2766,
"text": "1. The SET DIFFERENCE operation is not commutative, that means :"
},
{
"code": null,
"e": 2846,
"s": 2831,
"text": "A - B != B - A"
},
{
"code": null,
"e": 2914,
"s": 2846,
"text": "2. In SQL, the operation EXCEPT is as same as MINUS operation here."
},
{
"code": null,
"e": 2974,
"s": 2914,
"text": "3. Moreover, In SQL there is multiset operation EXCEPT ALL."
},
{
"code": null,
"e": 3064,
"s": 2974,
"text": "Example:Consider a relation Student(FIRST, LAST) and Faculty(FIRSTN, LASTN) given below :"
},
{
"code": null,
"e": 3091,
"s": 3064,
"text": "1. Student UNION Faculty :"
},
{
"code": null,
"e": 3110,
"s": 3091,
"text": "Student ∪ Faculty "
},
{
"code": null,
"e": 3144,
"s": 3110,
"text": "2. Student INTERSECTION Faculty :"
},
{
"code": null,
"e": 3163,
"s": 3144,
"text": "Student ∩ Faculty "
},
{
"code": null,
"e": 3190,
"s": 3163,
"text": "3. Student MINUS Faculty :"
},
{
"code": null,
"e": 3208,
"s": 3190,
"text": "Student - Faculty"
},
{
"code": null,
"e": 3232,
"s": 3208,
"text": "DBMS-Relational Algebra"
},
{
"code": null,
"e": 3237,
"s": 3232,
"text": "DBMS"
},
{
"code": null,
"e": 3245,
"s": 3237,
"text": "GATE CS"
},
{
"code": null,
"e": 3250,
"s": 3245,
"text": "DBMS"
},
{
"code": null,
"e": 3348,
"s": 3250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3359,
"s": 3348,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3412,
"s": 3359,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 3470,
"s": 3412,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 3493,
"s": 3470,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 3517,
"s": 3493,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 3537,
"s": 3517,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 3550,
"s": 3537,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 3577,
"s": 3550,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 3626,
"s": 3577,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
make - Unix, Linux Command
|
make - utility for building and maintaining groups of programs.
make [ -f makefile ] [ options ] ... [ targets ] ...
make [ -f makefile ] [ options ] ... [ targets ] ...
make The purpose of the make utility is to determine automatically which pieces of a large program need to be recompiled, and issue the commands to recompile them.
you can use make with any programming language whose compiler can be run with a shell command. In fact, make is not limited to programs. You can use it to describe any task
where some files must be updated automatically from others whenever the others change.
To prepare to use make, you must write a file called the makefile that describes the relationships among files in your program, and the states the commands for updating
each file. In a program, typically the executable file is updated from object files, which are in turn made by compiling source files.
Example-1:
To Build your programs:
$ make
output:
gcc -c -Wall test1.c
gcc -c -Wall test2.c
gcc -Wall test1.o test2.o -o test
Note: make reads makefile present in current directory and executes based on statements in makefile
Example-2:
To clean all the object files:
$ make clean
output:
rm -rf *.o test
Example-3:
To forcibly build all programs, use -B option:
$ make -B
output:
gcc -c -Wall test.c
gcc -c -Wall anotherTest.c
gcc -Wall test.o anotherTest.o -o test
Example-4:
To run make in debug mode, use the -d option :
$ make -d
output:
Copyright (C) 2006 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.This program built for x86_64-pc-linux-gnuReading makefiles...Reading makefile `Makefile'...Updating makefiles....Considering target file `Makefile'.Looking for an implicit rule for `Makefile'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.o'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.c'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cc'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.C'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cpp'.Trying pattern rule with stem `Makefile'.--More--
Example-5:
To build programs present in different directory:
$ make -C /home/testdir/
output:
make: Entering directory `/home/himanshu/practice/make-dir'make: Nothing to be done for `all'.make: Leaving directory `/home/himanshu/practice/make-dir'
Example-6:
To use other file instead of default makefile, use -f option :
$ make -f my_makefile
output:
gcc -c -Wall test1.c
gcc -c -Wall test2.c
gcc -Wall test1.o test2.o -o test
|
[
{
"code": null,
"e": 10775,
"s": 10711,
"text": "make - utility for building and maintaining groups of programs."
},
{
"code": null,
"e": 10830,
"s": 10775,
"text": "make [ -f makefile ] [ options ] ... [ targets ] ... \n"
},
{
"code": null,
"e": 10884,
"s": 10830,
"text": "make [ -f makefile ] [ options ] ... [ targets ] ... "
},
{
"code": null,
"e": 11614,
"s": 10884,
"text": "make The purpose of the make utility is to determine automatically which pieces of a large program need to be recompiled, and issue the commands to recompile them.\nyou can use make with any programming language whose compiler can be run with a shell command. In fact, make is not limited to programs. You can use it to describe any task \nwhere some files must be updated automatically from others whenever the others change.\nTo prepare to use make, you must write a file called the makefile that describes the relationships among files in your program, and the states the commands for updating \neach file. In a program, typically the executable file is updated from object files, which are in turn made by compiling source files."
},
{
"code": null,
"e": 11625,
"s": 11614,
"text": "Example-1:"
},
{
"code": null,
"e": 11649,
"s": 11625,
"text": "To Build your programs:"
},
{
"code": null,
"e": 11656,
"s": 11649,
"text": "$ make"
},
{
"code": null,
"e": 11664,
"s": 11656,
"text": "output:"
},
{
"code": null,
"e": 11846,
"s": 11664,
"text": " gcc -c -Wall test1.c\n gcc -c -Wall test2.c\n gcc -Wall test1.o test2.o -o test \n\nNote: make reads makefile present in current directory and executes based on statements in makefile\n"
},
{
"code": null,
"e": 11857,
"s": 11846,
"text": "Example-2:"
},
{
"code": null,
"e": 11888,
"s": 11857,
"text": "To clean all the object files:"
},
{
"code": null,
"e": 11901,
"s": 11888,
"text": "$ make clean"
},
{
"code": null,
"e": 11909,
"s": 11901,
"text": "output:"
},
{
"code": null,
"e": 11927,
"s": 11909,
"text": " rm -rf *.o test\n"
},
{
"code": null,
"e": 11938,
"s": 11927,
"text": "Example-3:"
},
{
"code": null,
"e": 11986,
"s": 11938,
"text": " To forcibly build all programs, use -B option:"
},
{
"code": null,
"e": 11996,
"s": 11986,
"text": "$ make -B"
},
{
"code": null,
"e": 12004,
"s": 11996,
"text": "output:"
},
{
"code": null,
"e": 12094,
"s": 12004,
"text": " gcc -c -Wall test.c\n gcc -c -Wall anotherTest.c\n gcc -Wall test.o anotherTest.o -o test\n"
},
{
"code": null,
"e": 12105,
"s": 12094,
"text": "Example-4:"
},
{
"code": null,
"e": 12152,
"s": 12105,
"text": "To run make in debug mode, use the -d option :"
},
{
"code": null,
"e": 12162,
"s": 12152,
"text": "$ make -d"
},
{
"code": null,
"e": 12170,
"s": 12162,
"text": "output:"
},
{
"code": null,
"e": 13027,
"s": 12170,
"text": "Copyright (C) 2006 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.This program built for x86_64-pc-linux-gnuReading makefiles...Reading makefile `Makefile'...Updating makefiles....Considering target file `Makefile'.Looking for an implicit rule for `Makefile'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.o'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.c'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cc'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.C'.Trying pattern rule with stem `Makefile'.Trying implicit prerequisite `Makefile.cpp'.Trying pattern rule with stem `Makefile'.--More--"
},
{
"code": null,
"e": 13038,
"s": 13027,
"text": "Example-5:"
},
{
"code": null,
"e": 13088,
"s": 13038,
"text": "To build programs present in different directory:"
},
{
"code": null,
"e": 13113,
"s": 13088,
"text": "$ make -C /home/testdir/"
},
{
"code": null,
"e": 13121,
"s": 13113,
"text": "output:"
},
{
"code": null,
"e": 13274,
"s": 13121,
"text": "make: Entering directory `/home/himanshu/practice/make-dir'make: Nothing to be done for `all'.make: Leaving directory `/home/himanshu/practice/make-dir'"
},
{
"code": null,
"e": 13285,
"s": 13274,
"text": "Example-6:"
},
{
"code": null,
"e": 13348,
"s": 13285,
"text": "To use other file instead of default makefile, use -f option :"
},
{
"code": null,
"e": 13370,
"s": 13348,
"text": "$ make -f my_makefile"
},
{
"code": null,
"e": 13378,
"s": 13370,
"text": "output:"
}
] |
How to Convert Character to Factor in R?
|
19 Dec, 2021
The as.factor() method in R Programming Language is used to convert the character vector to factor class.
Syntax:
as.factor(char-vec)
where char-vec is the character vector
The class indicative of the data type of the vector can be obtained using the class() method. Upon conversion, the data type is returned as a factor.
class(fac-vec)
where char-vec is the character vector
Example:
R
# declaring a character vectorstr_vec < - c("Geeks", "For", "Geeks", "Programming", "Coding")print("Original String")print(str_vec) # getting the class of vectorclass(str_vec) str_mod < - as.factor(str_vec)print("Modified String")print(str_mod) # getting the class of vectorclass(str_mod)
Output
[1] "Original String"
[1] "Geeks" "For" "Geeks" "Programming" "Coding"
[1] "character"
[1] "Modified String"
[1] Geeks For Geeks Programming Coding
Levels: Coding For Geeks Programming
[1] "factor"
Similarly, a dataframe column can be converted to factor type, by referring to the particular data column using df$col-name command in R.
Example:
R
# declaring a character vectordata_frame < - data.frame(col1=c(1: 5), col2=c("Geeks", "For", "Geeks", "Programming", "Coding") )print("Original Class") # getting the class of vectorclass(data_frame$col2) # modifying the col2 of data framedata_frame$col2 < - as.factor(data_frame$col2) print("Modified Class")class(data_frame$col2)
Output
[1] "Original Class"
[1] "character"
[1] "Modified Class"
[1] "factor"
Picked
R Factor-Programs
R-Factors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "The as.factor() method in R Programming Language is used to convert the character vector to factor class."
},
{
"code": null,
"e": 142,
"s": 134,
"text": "Syntax:"
},
{
"code": null,
"e": 162,
"s": 142,
"text": "as.factor(char-vec)"
},
{
"code": null,
"e": 201,
"s": 162,
"text": "where char-vec is the character vector"
},
{
"code": null,
"e": 352,
"s": 201,
"text": "The class indicative of the data type of the vector can be obtained using the class() method. Upon conversion, the data type is returned as a factor. "
},
{
"code": null,
"e": 367,
"s": 352,
"text": "class(fac-vec)"
},
{
"code": null,
"e": 406,
"s": 367,
"text": "where char-vec is the character vector"
},
{
"code": null,
"e": 415,
"s": 406,
"text": "Example:"
},
{
"code": null,
"e": 417,
"s": 415,
"text": "R"
},
{
"code": "# declaring a character vectorstr_vec < - c(\"Geeks\", \"For\", \"Geeks\", \"Programming\", \"Coding\")print(\"Original String\")print(str_vec) # getting the class of vectorclass(str_vec) str_mod < - as.factor(str_vec)print(\"Modified String\")print(str_mod) # getting the class of vectorclass(str_mod)",
"e": 709,
"s": 417,
"text": null
},
{
"code": null,
"e": 716,
"s": 709,
"text": "Output"
},
{
"code": null,
"e": 962,
"s": 716,
"text": "[1] \"Original String\"\n[1] \"Geeks\" \"For\" \"Geeks\" \"Programming\" \"Coding\" \n[1] \"character\"\n[1] \"Modified String\"\n[1] Geeks For Geeks Programming Coding \nLevels: Coding For Geeks Programming\n[1] \"factor\""
},
{
"code": null,
"e": 1101,
"s": 962,
"text": "Similarly, a dataframe column can be converted to factor type, by referring to the particular data column using df$col-name command in R. "
},
{
"code": null,
"e": 1110,
"s": 1101,
"text": "Example:"
},
{
"code": null,
"e": 1112,
"s": 1110,
"text": "R"
},
{
"code": "# declaring a character vectordata_frame < - data.frame(col1=c(1: 5), col2=c(\"Geeks\", \"For\", \"Geeks\", \"Programming\", \"Coding\") )print(\"Original Class\") # getting the class of vectorclass(data_frame$col2) # modifying the col2 of data framedata_frame$col2 < - as.factor(data_frame$col2) print(\"Modified Class\")class(data_frame$col2)",
"e": 1528,
"s": 1112,
"text": null
},
{
"code": null,
"e": 1535,
"s": 1528,
"text": "Output"
},
{
"code": null,
"e": 1609,
"s": 1535,
"text": "[1] \"Original Class\" \n[1] \"character\" \n[1] \"Modified Class\" \n[1] \"factor\""
},
{
"code": null,
"e": 1616,
"s": 1609,
"text": "Picked"
},
{
"code": null,
"e": 1634,
"s": 1616,
"text": "R Factor-Programs"
},
{
"code": null,
"e": 1644,
"s": 1634,
"text": "R-Factors"
},
{
"code": null,
"e": 1655,
"s": 1644,
"text": "R Language"
},
{
"code": null,
"e": 1666,
"s": 1655,
"text": "R Programs"
},
{
"code": null,
"e": 1764,
"s": 1666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1816,
"s": 1764,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 1874,
"s": 1816,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 1926,
"s": 1874,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1984,
"s": 1926,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2016,
"s": 1984,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 2074,
"s": 2016,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 2132,
"s": 2074,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2176,
"s": 2132,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 2225,
"s": 2176,
"text": "How to filter R DataFrame by values in a column?"
}
] |
How to View All the Uploaded Images in Firebase Storage?
|
21 Aug, 2021
In this article, we are going to Load all the images from the Firebase Storage and showing them in the RecyclerView. Normally we show an image after adding a link to the real-time database. Let’s say we want to show all the images uploaded as we see in the gallery. We will be just viewing all the images. So here we will be showing images uploaded in firebase storage in a particular folder. But here we will show the image after adding all the image URLs in Arraylist.
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 this into the AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Add this into the build.gradle file
implementation 'com.google.firebase:firebase-storage:19.1.1'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
Step 3: Working with the item.xml file
Go to the app > res > layout > New > Layout Resource File and name the file as item. Go to the item.xml file and refer to the following code. Below is the code for the item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="250dp" android:layout_marginTop="5dp" app:cardCornerRadius="8dp"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/item" android:scaleType="centerCrop"/> </androidx.cardview.widget.CardView>
Step 4: Working with the ImageAdapter.java file
Create a new java class in android studio and name the class as ImageAdapter. Go to the ImageAdapter.java file and refer to the following code. Below is the code for the ImageAdapter.java file.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.anni.uploaddataexcelsheet.R;import com.bumptech.glide.Glide; import java.util.ArrayList; public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> { private ArrayList<String> imageList; public ImageAdapter(ArrayList<String> imageList, Context context) { this.imageList = imageList; this.context = context; } private Context context; @NonNull @Override public ImageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImageAdapter.ViewHolder holder, int position) { // loading the images from the position Glide.with(holder.itemView.getContext()).load(imageList.get(position)).into(holder.imageView); } @Override public int getItemCount() { return imageList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public ViewHolder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.item); } }}
Step 5: Working with the activity_showallimages.xml file
You can work with the MainActivity or can create another new empty acticty in android studio. Go to the activity_showallimages.xml file and refer to the following code. Below is the code for the activity_showallimages.xml file
XML
<?xml version="1.0" encoding="utf-8"?><FrameLayout 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=".ShowAllImagesFromStorage"> <androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recyclerview" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:listitem="@layout/item"/> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progress" android:layout_gravity="center" android:indeterminate="true"/> </FrameLayout>
Step 6: Working with the ShowAllImagesFromStorage.java file
Go to the ShowAllImagesFromStorage.java file and refer to the following code. Below is the code for the ShowAllImagesFromStorage.java file. Loading the items in the Firebase Storage.
listRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
@Override
public void onSuccess(ListResult listResult) {
for(StorageReference file:listResult.getItems()){
file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// adding the url in the arraylist
imagelist.add(uri.toString());
Log.e("Itemvalue",uri.toString());
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
});
}
}
});
Below is the complete code for the ShowAllImagesFromStorage.java file.
Java
import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import android.net.Uri;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ProgressBar; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.storage.FileDownloadTask;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.ListResult;import com.google.firebase.storage.StorageReference; import java.util.ArrayList; public class ShowAllImagesFromStorage extends AppCompatActivity { ArrayList<String> imagelist; RecyclerView recyclerView; StorageReference root; ProgressBar progressBar; ImageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_all_images_from_storage); imagelist=new ArrayList<>(); recyclerView=findViewById(R.id.recyclerview); adapter=new ImageAdapter(imagelist,this); recyclerView.setLayoutManager(new LinearLayoutManager(null)); progressBar=findViewById(R.id.progress); progressBar.setVisibility(View.VISIBLE); StorageReference listRef = FirebaseStorage.getInstance().getReference().child("images"); listRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() { @Override public void onSuccess(ListResult listResult) { for(StorageReference file:listResult.getItems()){ file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { imagelist.add(uri.toString()); Log.e("Itemvalue",uri.toString()); } }).addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { recyclerView.setAdapter(adapter); progressBar.setVisibility(View.GONE); } }); } } }); }}
Output:
Uploaded Files in Firebase Storage:
sooda367
Firebase
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
Android SDK and it's Components
How to Add Views Dynamically and Store Data in Arraylist in Android?
Broadcast Receiver in Android With Example
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 499,
"s": 28,
"text": "In this article, we are going to Load all the images from the Firebase Storage and showing them in the RecyclerView. Normally we show an image after adding a link to the real-time database. Let’s say we want to show all the images uploaded as we see in the gallery. We will be just viewing all the images. So here we will be showing images uploaded in firebase storage in a particular folder. But here we will show the image after adding all the image URLs in Arraylist."
},
{
"code": null,
"e": 528,
"s": 499,
"text": "Step 1: Create a new Project"
},
{
"code": null,
"e": 692,
"s": 528,
"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": 743,
"s": 692,
"text": "Step 2: Add this into the AndroidManifest.xml file"
},
{
"code": null,
"e": 805,
"s": 743,
"text": "<uses-permission android:name=\"android.permission.INTERNET\"/>"
},
{
"code": null,
"e": 841,
"s": 805,
"text": "Add this into the build.gradle file"
},
{
"code": null,
"e": 1086,
"s": 841,
"text": "implementation 'com.google.firebase:firebase-storage:19.1.1'\nimplementation 'com.github.bumptech.glide:glide:4.11.0'\nannotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'\nannotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'"
},
{
"code": null,
"e": 1125,
"s": 1086,
"text": "Step 3: Working with the item.xml file"
},
{
"code": null,
"e": 1308,
"s": 1125,
"text": "Go to the app > res > layout > New > Layout Resource File and name the file as item. Go to the item.xml file and refer to the following code. Below is the code for the item.xml file."
},
{
"code": null,
"e": 1312,
"s": 1308,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"250dp\" android:layout_marginTop=\"5dp\" app:cardCornerRadius=\"8dp\"> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/item\" android:scaleType=\"centerCrop\"/> </androidx.cardview.widget.CardView>",
"e": 1866,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1914,
"s": 1866,
"text": "Step 4: Working with the ImageAdapter.java file"
},
{
"code": null,
"e": 2109,
"s": 1914,
"text": "Create a new java class in android studio and name the class as ImageAdapter. Go to the ImageAdapter.java file and refer to the following code. Below is the code for the ImageAdapter.java file. "
},
{
"code": null,
"e": 2114,
"s": 2109,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.anni.uploaddataexcelsheet.R;import com.bumptech.glide.Glide; import java.util.ArrayList; public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> { private ArrayList<String> imageList; public ImageAdapter(ArrayList<String> imageList, Context context) { this.imageList = imageList; this.context = context; } private Context context; @NonNull @Override public ImageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImageAdapter.ViewHolder holder, int position) { // loading the images from the position Glide.with(holder.itemView.getContext()).load(imageList.get(position)).into(holder.imageView); } @Override public int getItemCount() { return imageList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public ViewHolder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.item); } }}",
"e": 3582,
"s": 2114,
"text": null
},
{
"code": null,
"e": 3639,
"s": 3582,
"text": "Step 5: Working with the activity_showallimages.xml file"
},
{
"code": null,
"e": 3867,
"s": 3639,
"text": "You can work with the MainActivity or can create another new empty acticty in android studio. Go to the activity_showallimages.xml file and refer to the following code. Below is the code for the activity_showallimages.xml file "
},
{
"code": null,
"e": 3871,
"s": 3867,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout 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=\".ShowAllImagesFromStorage\"> <androidx.recyclerview.widget.RecyclerView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/recyclerview\" app:layoutManager=\"androidx.recyclerview.widget.LinearLayoutManager\" tools:listitem=\"@layout/item\"/> <ProgressBar android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/progress\" android:layout_gravity=\"center\" android:indeterminate=\"true\"/> </FrameLayout>",
"e": 4713,
"s": 3871,
"text": null
},
{
"code": null,
"e": 4773,
"s": 4713,
"text": "Step 6: Working with the ShowAllImagesFromStorage.java file"
},
{
"code": null,
"e": 4956,
"s": 4773,
"text": "Go to the ShowAllImagesFromStorage.java file and refer to the following code. Below is the code for the ShowAllImagesFromStorage.java file. Loading the items in the Firebase Storage."
},
{
"code": null,
"e": 5964,
"s": 4956,
"text": "listRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {\n @Override\n public void onSuccess(ListResult listResult) {\n for(StorageReference file:listResult.getItems()){\n file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {\n @Override\n public void onSuccess(Uri uri) {\n // adding the url in the arraylist\n imagelist.add(uri.toString());\n Log.e(\"Itemvalue\",uri.toString());\n }\n }).addOnSuccessListener(new OnSuccessListener<Uri>() {\n @Override\n public void onSuccess(Uri uri) {\n recyclerView.setAdapter(adapter);\n progressBar.setVisibility(View.GONE);\n }\n });\n }\n }\n });"
},
{
"code": null,
"e": 6035,
"s": 5964,
"text": "Below is the complete code for the ShowAllImagesFromStorage.java file."
},
{
"code": null,
"e": 6040,
"s": 6035,
"text": "Java"
},
{
"code": "import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import android.net.Uri;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ProgressBar; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.storage.FileDownloadTask;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.ListResult;import com.google.firebase.storage.StorageReference; import java.util.ArrayList; public class ShowAllImagesFromStorage extends AppCompatActivity { ArrayList<String> imagelist; RecyclerView recyclerView; StorageReference root; ProgressBar progressBar; ImageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_all_images_from_storage); imagelist=new ArrayList<>(); recyclerView=findViewById(R.id.recyclerview); adapter=new ImageAdapter(imagelist,this); recyclerView.setLayoutManager(new LinearLayoutManager(null)); progressBar=findViewById(R.id.progress); progressBar.setVisibility(View.VISIBLE); StorageReference listRef = FirebaseStorage.getInstance().getReference().child(\"images\"); listRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() { @Override public void onSuccess(ListResult listResult) { for(StorageReference file:listResult.getItems()){ file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { imagelist.add(uri.toString()); Log.e(\"Itemvalue\",uri.toString()); } }).addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { recyclerView.setAdapter(adapter); progressBar.setVisibility(View.GONE); } }); } } }); }}",
"e": 8469,
"s": 6040,
"text": null
},
{
"code": null,
"e": 8477,
"s": 8469,
"text": "Output:"
},
{
"code": null,
"e": 8513,
"s": 8477,
"text": "Uploaded Files in Firebase Storage:"
},
{
"code": null,
"e": 8522,
"s": 8513,
"text": "sooda367"
},
{
"code": null,
"e": 8531,
"s": 8522,
"text": "Firebase"
},
{
"code": null,
"e": 8539,
"s": 8531,
"text": "Android"
},
{
"code": null,
"e": 8544,
"s": 8539,
"text": "Java"
},
{
"code": null,
"e": 8549,
"s": 8544,
"text": "Java"
},
{
"code": null,
"e": 8557,
"s": 8549,
"text": "Android"
},
{
"code": null,
"e": 8655,
"s": 8557,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8686,
"s": 8655,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8718,
"s": 8686,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8787,
"s": 8718,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8830,
"s": 8787,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 8859,
"s": 8830,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 8874,
"s": 8859,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8918,
"s": 8874,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 8969,
"s": 8918,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8994,
"s": 8969,
"text": "Reverse a string in Java"
}
] |
Program to count number of elements present in a set of elements with recursive indexing in Python
|
Suppose we have a list of numbers called A and another number k, we have to make a new set
of possible elements {A[k], A[A[k]], A[A[A[k]]], ... } stopping before it's out of index. We have to
find the size of this set, otherwise -1 when there is a cycle.
So, if the input is like A = [1,2,3,4,5,6,7], k = 1, then the output will be 6 as A[1] = 2, A[2] = 3,
A[3] = 4, A[4] = 5, A[5] = 6, A[6] = 7, So the set is {2,3,4,5,6,7}, size of set is 6.
To solve this, we will follow these steps −
seen := a new set
while k < size of A, doif A[k] in seen, thenreturn -1insert A[k] into seenk := A[k]
if A[k] in seen, thenreturn -1
return -1
insert A[k] into seen
k := A[k]
return size of seen
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, A, k):
seen = set()
while k < len(A):
if A[k] in seen:
return -1
seen.add(A[k])
k = A[k]
return len(seen)
ob = Solution()
print(ob.solve([1,2,3,4,5,6,7], 1))
[1,2,3,4,5,6,7], 1
6
|
[
{
"code": null,
"e": 1442,
"s": 1187,
"text": "Suppose we have a list of numbers called A and another number k, we have to make a new set\nof possible elements {A[k], A[A[k]], A[A[A[k]]], ... } stopping before it's out of index. We have to\nfind the size of this set, otherwise -1 when there is a cycle."
},
{
"code": null,
"e": 1631,
"s": 1442,
"text": "So, if the input is like A = [1,2,3,4,5,6,7], k = 1, then the output will be 6 as A[1] = 2, A[2] = 3,\nA[3] = 4, A[4] = 5, A[5] = 6, A[6] = 7, So the set is {2,3,4,5,6,7}, size of set is 6."
},
{
"code": null,
"e": 1675,
"s": 1631,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1693,
"s": 1675,
"text": "seen := a new set"
},
{
"code": null,
"e": 1777,
"s": 1693,
"text": "while k < size of A, doif A[k] in seen, thenreturn -1insert A[k] into seenk := A[k]"
},
{
"code": null,
"e": 1808,
"s": 1777,
"text": "if A[k] in seen, thenreturn -1"
},
{
"code": null,
"e": 1818,
"s": 1808,
"text": "return -1"
},
{
"code": null,
"e": 1840,
"s": 1818,
"text": "insert A[k] into seen"
},
{
"code": null,
"e": 1850,
"s": 1840,
"text": "k := A[k]"
},
{
"code": null,
"e": 1870,
"s": 1850,
"text": "return size of seen"
},
{
"code": null,
"e": 1940,
"s": 1870,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1951,
"s": 1940,
"text": " Live Demo"
},
{
"code": null,
"e": 2201,
"s": 1951,
"text": "class Solution:\n def solve(self, A, k):\n seen = set()\n while k < len(A):\n if A[k] in seen:\n return -1\n seen.add(A[k])\n k = A[k]\n return len(seen)\nob = Solution()\nprint(ob.solve([1,2,3,4,5,6,7], 1))"
},
{
"code": null,
"e": 2220,
"s": 2201,
"text": "[1,2,3,4,5,6,7], 1"
},
{
"code": null,
"e": 2222,
"s": 2220,
"text": "6"
}
] |
Redis - List Blpop Command
|
Redis BLPOP command is used to remove and get the first element in a list, or block until one is available. BLPOP command just returns the first element, if available, or blocks the client for specific time to execute any command.
String reply, the value of element stored at the key or nil.
Following is the basic syntax of Redis BLPOP command.
redis 127.0.0.1:6379> BLPOP LIST1 LIST2 .. LISTN TIMEOUT
redis 127.0.0.1:6379> BLPOP list1 100
The above example will block the client for 100 seconds to execute any command. If any data comes in the specified key list1, then it returns; otherwise after 100 seconds nil value is returned.
|
[
{
"code": null,
"e": 2410,
"s": 2179,
"text": "Redis BLPOP command is used to remove and get the first element in a list, or block until one is available. BLPOP command just returns the first element, if available, or blocks the client for specific time to execute any command."
},
{
"code": null,
"e": 2471,
"s": 2410,
"text": "String reply, the value of element stored at the key or nil."
},
{
"code": null,
"e": 2525,
"s": 2471,
"text": "Following is the basic syntax of Redis BLPOP command."
},
{
"code": null,
"e": 2583,
"s": 2525,
"text": "redis 127.0.0.1:6379> BLPOP LIST1 LIST2 .. LISTN TIMEOUT\n"
},
{
"code": null,
"e": 2623,
"s": 2583,
"text": "redis 127.0.0.1:6379> BLPOP list1 100 \n"
}
] |
How to become a 4 star coder on codechef in only 3 contests ?
|
03 May, 2020
Many people messaged me how you achieved 4 stars in only 3 contests in a month interval.That sounds amazing! But the reality is I am doing coding since 8 months and I have practiced on many platforms before jumping to the contests.I personally don’t know anyone who just started coding and became a 4 star or so in a very short period. People usually practice a lot before coming in the competitive scenario.
There is no such shortcut or trick ( PS- if you know such trick than please share XD ) .You have to grind hard for improvement and don’t get depressed by seeing others results, they don’t show the complete truth.Many people will suggest you to do participate in contests, I also agree that its a good practice but I will recommend you to first practice before directly jumping in to contests .
As this is my first post and I don’t want it to be to long (it is already too long XD), so that’s it for this time. Comment down if you want me to write on other such stuff and feel free to message me if you have doubts regarding such things.
Career-Advices
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 461,
"s": 52,
"text": "Many people messaged me how you achieved 4 stars in only 3 contests in a month interval.That sounds amazing! But the reality is I am doing coding since 8 months and I have practiced on many platforms before jumping to the contests.I personally don’t know anyone who just started coding and became a 4 star or so in a very short period. People usually practice a lot before coming in the competitive scenario."
},
{
"code": null,
"e": 855,
"s": 461,
"text": "There is no such shortcut or trick ( PS- if you know such trick than please share XD ) .You have to grind hard for improvement and don’t get depressed by seeing others results, they don’t show the complete truth.Many people will suggest you to do participate in contests, I also agree that its a good practice but I will recommend you to first practice before directly jumping in to contests ."
},
{
"code": null,
"e": 1098,
"s": 855,
"text": "As this is my first post and I don’t want it to be to long (it is already too long XD), so that’s it for this time. Comment down if you want me to write on other such stuff and feel free to message me if you have doubts regarding such things."
},
{
"code": null,
"e": 1113,
"s": 1098,
"text": "Career-Advices"
},
{
"code": null,
"e": 1137,
"s": 1113,
"text": "Competitive Programming"
}
] |
What is a target type of lambda expression in Java?
|
A functional Interface for which a lambda expression has invoked is called target type of lambda expression. It means that if a lambda expression has invoked for some "X" interface then "X" is the target type of that lambda expression. Hence, we conclude that lambda expressions can be used only in those situations where java compiler can determine the Target Type.
In the below example, the target type of lambda expression is BiFunction. An instance of a class is automatically created that implements the functional interface and lambda expression provides an implementation of the abstract method declared by the functional interface.
interface BiFunction {
R apply(K k , V v);
}
public class LambdaTypeInferenceTest {
public static void main(String[] args) {
BiFunction result = (n1, n2) ->
{ return n1 + n2;}; // lambda expression
Integer n1 = 10;
Integer n2 = 20;
System.out.println("The addition of n1 and n2 is: "+ result.apply(n1, n2));
}
}
The addition of n1 and n2 is: 30
|
[
{
"code": null,
"e": 1554,
"s": 1187,
"text": "A functional Interface for which a lambda expression has invoked is called target type of lambda expression. It means that if a lambda expression has invoked for some \"X\" interface then \"X\" is the target type of that lambda expression. Hence, we conclude that lambda expressions can be used only in those situations where java compiler can determine the Target Type."
},
{
"code": null,
"e": 1827,
"s": 1554,
"text": "In the below example, the target type of lambda expression is BiFunction. An instance of a class is automatically created that implements the functional interface and lambda expression provides an implementation of the abstract method declared by the functional interface."
},
{
"code": null,
"e": 2187,
"s": 1827,
"text": "interface BiFunction {\n R apply(K k , V v);\n}\npublic class LambdaTypeInferenceTest {\n public static void main(String[] args) {\n BiFunction result = (n1, n2) ->\n { return n1 + n2;}; // lambda expression\n Integer n1 = 10;\n Integer n2 = 20;\n System.out.println(\"The addition of n1 and n2 is: \"+ result.apply(n1, n2));\n }\n}"
},
{
"code": null,
"e": 2220,
"s": 2187,
"text": "The addition of n1 and n2 is: 30"
}
] |
C/C++ Program for the n-th Fibonacci number?
|
The Fibonacci sequence is a series where the next term is the sum of the previous two terms.The first two terms of the Fibonacci sequence is 0 followed by 1.
In this problem, we will find the nth number in the Fibonacci series. For this we will calculate all the numbers and print the n terms.
Input:8
Output:0 1 1 2 3 5 8 13
0+1=1
1+1=2
1+2=3
2+3=5
Using For loop to sum of previous two terms for next term
#include<iostream>
using namespace std;
int main() {
int t1=0,t2=1,n,i,nextTerm;
n = 8;
for ( i = 1; i <= n; ++i) {
if(i == 1) {
cout << " " << t1 ;
continue;
}
if(i == 2) {
cout << " " << t2 << " " ;
continue;
}
nextTerm = t1 + t2 ;
t1 = t2 ;
t2 = nextTerm ;
cout << nextTerm << " ";
}
}
0 1 1 2 3 5 8 13
|
[
{
"code": null,
"e": 1346,
"s": 1187,
"text": "The Fibonacci sequence is a series where the next term is the sum of the previous two terms.The first two terms of the Fibonacci sequence is 0 followed by 1. "
},
{
"code": null,
"e": 1482,
"s": 1346,
"text": "In this problem, we will find the nth number in the Fibonacci series. For this we will calculate all the numbers and print the n terms."
},
{
"code": null,
"e": 1514,
"s": 1482,
"text": "Input:8\nOutput:0 1 1 2 3 5 8 13"
},
{
"code": null,
"e": 1538,
"s": 1514,
"text": "0+1=1\n1+1=2\n1+2=3\n2+3=5"
},
{
"code": null,
"e": 1596,
"s": 1538,
"text": "Using For loop to sum of previous two terms for next term"
},
{
"code": null,
"e": 1981,
"s": 1596,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int t1=0,t2=1,n,i,nextTerm;\n n = 8;\n for ( i = 1; i <= n; ++i) {\n if(i == 1) {\n cout << \" \" << t1 ;\n continue;\n }\n if(i == 2) {\n cout << \" \" << t2 << \" \" ;\n continue;\n }\n nextTerm = t1 + t2 ;\n t1 = t2 ;\n t2 = nextTerm ;\n cout << nextTerm << \" \";\n }\n}"
},
{
"code": null,
"e": 1998,
"s": 1981,
"text": "0 1 1 2 3 5 8 13"
}
] |
Program to check if three points are collinear
|
03 Jun, 2022
Given three points, check whether they lie on a straight (collinear) or notExamples :
Input : (1, 1), (1, 4), (1, 5)
Output : Yes
The points lie on a straight line
Input : (1, 5), (2, 5), (4, 6)
Output : No
The points do not lie on a straight line
First approach Three points lie on the straight line if the area formed by the triangle of these three points is zero. So we will check if the area formed by the triangle is zero or not
Formula for area of triangle is :
0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)]
The formula is basically half of determinant
value of following.
x1 x2 x3
y1 y2 y3
1 1 1
The above formula is derived from shoelace formula.
If this equals zero then points lie on a straight line
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to check if three// points are collinear or not// using area of triangle.#include <bits/stdc++.h>#include <math.h>#include <stdlib.h> using namespace std;// function to check if point// collinear or notvoid collinear(int x1, int y1, int x2, int y2, int x3, int y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// C program to check if three// points are collinear or not// using area of triangle.#include <stdio.h>#include <math.h>#include <stdlib.h> // function to check if point// collinear or notvoid collinear(int x1, int y1, int x2, int y2, int x3, int y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) printf("Yes"); else printf("No");} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); return 0;}
// Java program to check if// three points are collinear// or not using area of triangle.class GFG{ // function to check if // point collinear or not static void collinear(int x1, int y1, int x2, int y2, int x3, int y3) { /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) System.out.println("Yes"); else System.out.println("No"); } // Driver Code public static void main(String args[]) { int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); }} // This code is contributed by Sam007.
# Python program to check# if three points are collinear# or not using area of triangle. # function to check if# point collinear or notdef collinear(x1, y1, x2, y2, x3, y3): """ Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations """ a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2) if (a == 0): print "Yes" else: print "No" # Driver Codex1, x2, x3, y1, y2, y3 = 1, 1, 1, 1, 4, 5collinear(x1, y1, x2, y2, x3, y3) # This code is contributed# by Sachin Bisht
// C# program to check if// three points are collinear// or not using area of triangle.using System; class GFG{ /* function to check if point collinear or not */ static void collinear(int x1, int y1, int x2, int y2, int x3, int y3) { /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) Console.Write("Yes"); else Console.Write("No"); } // Driver code public static void Main () { int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); }} // This code is contributed by Sam007.
<?php// PHP or not using area of triangle. /* function to check ifpoint collinear or not */function collinear($x1, $y1, $x2, $y2, $x3, $y3){ /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ $a = $x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2); if ($a == 0) printf("Yes"); else printf("No");} // Driver Code$x1 = 1; $x2 = 1; $x3 = 1;$y1 = 1; $y2 = 4; $y3 = 5;collinear($x1, $y1, $x2, $y2, $x3, $y3); // This code is contributed by Sam007.?>
<script>// Javascript program to check if three// points are collinear or not// using area of triangle. function collinear(x1, y1, x2, y2, x3, y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations var a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) document.write("Yes"); else document.write( "No");} var x1 = 1, x2 = 1, x3 = 1,y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); // This code is contributed by akshitsaxenaa09.</script>
Output :
Yes
Time Complexity: O(1)
Auxiliary Space: O(1) Second approach
For three points, slope of any pair of points
must be same as other pair.
For example, slope of line joining (x2, y2)
and (x3, y3), and line joining (x1, y1) and
(x2, y2) must be same.
(y3 - y2)/(x3 - x2) = (y2 - y1)/(x2 - x1)
In other words,
(y3 - y2)(x2 - x1) = (y2 - y1)(x3 - x2)
C++
C
Java
Python
C#
PHP
Javascript
// A C++ program// Slope based solution to check// if three points are collinear.#include <bits/stdc++.h>using namespace std; /* function to check ifpoint collinear or not*/void collinear(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) cout << "Yes" << endl; else cout << "No" << endl;} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 0, y1 = 1, y2 = 6, y3 = 9; collinear(x1, y1, x2, y2, x3, y3); return 0;} // The code is contributed by Gautam goel (gautamgoel962)
// Slope based solution to check// if three points are collinear.#include <stdio.h>#include <math.h> /* function to check ifpoint collinear or not*/void collinear(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) printf("Yes"); else printf("No");} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 0, y1 = 1, y2 = 6, y3 = 9; collinear(x1, y1, x2, y2, x3, y3); return 0;}
// Slope based solution to check// if three points are collinear. import java.io.*; class GFG { /* function to check ifpoint collinear or not*/static void cool_line(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) System.out.println("Yes"); else System.out.println("No");} // Driver Code public static void main (String[] args) { int a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3); }}//This Code is Contributed by ajit
# Slope based solution to check if three# points are collinear. # function to check if# point collinear or notdef collinear(x1, y1, x2, y2, x3, y3): if ((y3 - y2)*(x2 - x1) == (y2 - y1)*(x3 - x2)): print ("Yes") else: print ("No") # Driver Codex1, x2, x3, y1, y2, y3 = 1, 1, 0, 1, 6, 9collinear(x1, y1, x2, y2, x3, y3); # This code is contributed# by Sachin Bisht
// Slope based solution to check// if three points are collinear.using System; class GFG{ /* function to check ifpoint collinear or not*/static void cool_line(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver Codestatic public void Main (){ int a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3);}} // This code is contributed by ajit
<?php// Slope based solution to check// if three points are collinear. /* function to check ifpoint collinear or not*/function collinear($x1, $y1, $x2, $y2, $x3, $y3){ if (($y3 - $y2) * ($x2 - $x1) == ($y2 - $y1) * ($x3 - $x2)) echo ("Yes"); else echo ("No");} // Driver Code$x1 = 1;$x2 = 1;$x3 = 0;$y1 = 1;$y2 = 6;$y3 = 9;collinear($x1, $y1, $x2, $y2, $x3, $y3); // This code is contributed by ajit?>
<script>// Slope based solution to check// if three points are collinear./* * function to check if point collinear or not */ function cool_line(x1 , y1 , x2 , y2 , x3 , y3) { if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) document.write("Yes"); else document.write("No"); } // Driver Code var a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3); // This code is contributed by aashish1995</script>
Output :
No
Time Complexity: O(1)
Auxiliary Space: O(1)
This article is contributed by Pranav. 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.
Sam007
jit_t
Akanksha_Rai
aashish1995
akshitsaxenaa09
CoderSaty
simranarora5sos
rohitsingh07052
gautamgoel962
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for Point of Intersection of Two Lines
Window to Viewport Transformation in Computer Graphics with Implementation
Find K Closest Points to the Origin
Closest Pair of Points | O(nlogn) Implementation
Haversine formula to find distance between two points on a sphere
Check if a point lies inside a rectangle | Set-2
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 140,
"s": 52,
"text": "Given three points, check whether they lie on a straight (collinear) or notExamples : "
},
{
"code": null,
"e": 305,
"s": 140,
"text": "Input : (1, 1), (1, 4), (1, 5)\nOutput : Yes \nThe points lie on a straight line\n\nInput : (1, 5), (2, 5), (4, 6)\nOutput : No \nThe points do not lie on a straight line"
},
{
"code": null,
"e": 494,
"s": 307,
"text": "First approach Three points lie on the straight line if the area formed by the triangle of these three points is zero. So we will check if the area formed by the triangle is zero or not "
},
{
"code": null,
"e": 789,
"s": 494,
"text": "Formula for area of triangle is : \n0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)]\n\nThe formula is basically half of determinant\nvalue of following.\nx1 x2 x3\ny1 y2 y3\n1 1 1\n\nThe above formula is derived from shoelace formula.\n\nIf this equals zero then points lie on a straight line "
},
{
"code": null,
"e": 793,
"s": 789,
"text": "C++"
},
{
"code": null,
"e": 795,
"s": 793,
"text": "C"
},
{
"code": null,
"e": 800,
"s": 795,
"text": "Java"
},
{
"code": null,
"e": 807,
"s": 800,
"text": "Python"
},
{
"code": null,
"e": 810,
"s": 807,
"text": "C#"
},
{
"code": null,
"e": 814,
"s": 810,
"text": "PHP"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Javascript"
},
{
"code": "// C++ program to check if three// points are collinear or not// using area of triangle.#include <bits/stdc++.h>#include <math.h>#include <stdlib.h> using namespace std;// function to check if point// collinear or notvoid collinear(int x1, int y1, int x2, int y2, int x3, int y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) cout << \"Yes\"; else cout << \"No\";} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 1609,
"s": 825,
"text": null
},
{
"code": "// C program to check if three// points are collinear or not// using area of triangle.#include <stdio.h>#include <math.h>#include <stdlib.h> // function to check if point// collinear or notvoid collinear(int x1, int y1, int x2, int y2, int x3, int y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) printf(\"Yes\"); else printf(\"No\");} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); return 0;}",
"e": 2308,
"s": 1609,
"text": null
},
{
"code": "// Java program to check if// three points are collinear// or not using area of triangle.class GFG{ // function to check if // point collinear or not static void collinear(int x1, int y1, int x2, int y2, int x3, int y3) { /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // Driver Code public static void main(String args[]) { int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); }} // This code is contributed by Sam007.",
"e": 3205,
"s": 2308,
"text": null
},
{
"code": "# Python program to check# if three points are collinear# or not using area of triangle. # function to check if# point collinear or notdef collinear(x1, y1, x2, y2, x3, y3): \"\"\" Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations \"\"\" a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2) if (a == 0): print \"Yes\" else: print \"No\" # Driver Codex1, x2, x3, y1, y2, y3 = 1, 1, 1, 1, 4, 5collinear(x1, y1, x2, y2, x3, y3) # This code is contributed# by Sachin Bisht",
"e": 3779,
"s": 3205,
"text": null
},
{
"code": "// C# program to check if// three points are collinear// or not using area of triangle.using System; class GFG{ /* function to check if point collinear or not */ static void collinear(int x1, int y1, int x2, int y2, int x3, int y3) { /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) Console.Write(\"Yes\"); else Console.Write(\"No\"); } // Driver code public static void Main () { int x1 = 1, x2 = 1, x3 = 1, y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); }} // This code is contributed by Sam007.",
"e": 4655,
"s": 3779,
"text": null
},
{
"code": "<?php// PHP or not using area of triangle. /* function to check ifpoint collinear or not */function collinear($x1, $y1, $x2, $y2, $x3, $y3){ /* Calculation the area of triangle. We have skipped multiplication with 0.5 to avoid floating point computations */ $a = $x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2); if ($a == 0) printf(\"Yes\"); else printf(\"No\");} // Driver Code$x1 = 1; $x2 = 1; $x3 = 1;$y1 = 1; $y2 = 4; $y3 = 5;collinear($x1, $y1, $x2, $y2, $x3, $y3); // This code is contributed by Sam007.?>",
"e": 5243,
"s": 4655,
"text": null
},
{
"code": "<script>// Javascript program to check if three// points are collinear or not// using area of triangle. function collinear(x1, y1, x2, y2, x3, y3){ // Calculation the area of // triangle. We have skipped // multiplication with 0.5 // to avoid floating point // computations var a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0) document.write(\"Yes\"); else document.write( \"No\");} var x1 = 1, x2 = 1, x3 = 1,y1 = 1, y2 = 4, y3 = 5; collinear(x1, y1, x2, y2, x3, y3); // This code is contributed by akshitsaxenaa09.</script>",
"e": 5851,
"s": 5243,
"text": null
},
{
"code": null,
"e": 5862,
"s": 5851,
"text": "Output : "
},
{
"code": null,
"e": 5866,
"s": 5862,
"text": "Yes"
},
{
"code": null,
"e": 5888,
"s": 5866,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 5928,
"s": 5888,
"text": "Auxiliary Space: O(1) Second approach "
},
{
"code": null,
"e": 6216,
"s": 5928,
"text": "For three points, slope of any pair of points\nmust be same as other pair.\n\nFor example, slope of line joining (x2, y2)\nand (x3, y3), and line joining (x1, y1) and\n(x2, y2) must be same.\n\n(y3 - y2)/(x3 - x2) = (y2 - y1)/(x2 - x1)\n\nIn other words, \n(y3 - y2)(x2 - x1) = (y2 - y1)(x3 - x2) "
},
{
"code": null,
"e": 6222,
"s": 6218,
"text": "C++"
},
{
"code": null,
"e": 6224,
"s": 6222,
"text": "C"
},
{
"code": null,
"e": 6229,
"s": 6224,
"text": "Java"
},
{
"code": null,
"e": 6236,
"s": 6229,
"text": "Python"
},
{
"code": null,
"e": 6239,
"s": 6236,
"text": "C#"
},
{
"code": null,
"e": 6243,
"s": 6239,
"text": "PHP"
},
{
"code": null,
"e": 6254,
"s": 6243,
"text": "Javascript"
},
{
"code": "// A C++ program// Slope based solution to check// if three points are collinear.#include <bits/stdc++.h>using namespace std; /* function to check ifpoint collinear or not*/void collinear(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) cout << \"Yes\" << endl; else cout << \"No\" << endl;} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 0, y1 = 1, y2 = 6, y3 = 9; collinear(x1, y1, x2, y2, x3, y3); return 0;} // The code is contributed by Gautam goel (gautamgoel962)",
"e": 6819,
"s": 6254,
"text": null
},
{
"code": "// Slope based solution to check// if three points are collinear.#include <stdio.h>#include <math.h> /* function to check ifpoint collinear or not*/void collinear(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) printf(\"Yes\"); else printf(\"No\");} // Driver Codeint main(){ int x1 = 1, x2 = 1, x3 = 0, y1 = 1, y2 = 6, y3 = 9; collinear(x1, y1, x2, y2, x3, y3); return 0;}",
"e": 7299,
"s": 6819,
"text": null
},
{
"code": "// Slope based solution to check// if three points are collinear. import java.io.*; class GFG { /* function to check ifpoint collinear or not*/static void cool_line(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver Code public static void main (String[] args) { int a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3); }}//This Code is Contributed by ajit",
"e": 7892,
"s": 7299,
"text": null
},
{
"code": "# Slope based solution to check if three# points are collinear. # function to check if# point collinear or notdef collinear(x1, y1, x2, y2, x3, y3): if ((y3 - y2)*(x2 - x1) == (y2 - y1)*(x3 - x2)): print (\"Yes\") else: print (\"No\") # Driver Codex1, x2, x3, y1, y2, y3 = 1, 1, 0, 1, 6, 9collinear(x1, y1, x2, y2, x3, y3); # This code is contributed# by Sachin Bisht",
"e": 8282,
"s": 7892,
"text": null
},
{
"code": "// Slope based solution to check// if three points are collinear.using System; class GFG{ /* function to check ifpoint collinear or not*/static void cool_line(int x1, int y1, int x2, int y2, int x3, int y3){ if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver Codestatic public void Main (){ int a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3);}} // This code is contributed by ajit",
"e": 8827,
"s": 8282,
"text": null
},
{
"code": "<?php// Slope based solution to check// if three points are collinear. /* function to check ifpoint collinear or not*/function collinear($x1, $y1, $x2, $y2, $x3, $y3){ if (($y3 - $y2) * ($x2 - $x1) == ($y2 - $y1) * ($x3 - $x2)) echo (\"Yes\"); else echo (\"No\");} // Driver Code$x1 = 1;$x2 = 1;$x3 = 0;$y1 = 1;$y2 = 6;$y3 = 9;collinear($x1, $y1, $x2, $y2, $x3, $y3); // This code is contributed by ajit?>",
"e": 9283,
"s": 8827,
"text": null
},
{
"code": "<script>// Slope based solution to check// if three points are collinear./* * function to check if point collinear or not */ function cool_line(x1 , y1 , x2 , y2 , x3 , y3) { if ((y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2)) document.write(\"Yes\"); else document.write(\"No\"); } // Driver Code var a1 = 1, a2 = 1, a3 = 0, b1 = 1, b2 = 6, b3 = 9; cool_line(a1, b1, a2, b2, a3, b3); // This code is contributed by aashish1995</script>",
"e": 9787,
"s": 9283,
"text": null
},
{
"code": null,
"e": 9798,
"s": 9787,
"text": "Output : "
},
{
"code": null,
"e": 9802,
"s": 9798,
"text": "No "
},
{
"code": null,
"e": 9824,
"s": 9802,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 9846,
"s": 9824,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10265,
"s": 9846,
"text": "This article is contributed by Pranav. 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. "
},
{
"code": null,
"e": 10272,
"s": 10265,
"text": "Sam007"
},
{
"code": null,
"e": 10278,
"s": 10272,
"text": "jit_t"
},
{
"code": null,
"e": 10291,
"s": 10278,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10303,
"s": 10291,
"text": "aashish1995"
},
{
"code": null,
"e": 10319,
"s": 10303,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 10329,
"s": 10319,
"text": "CoderSaty"
},
{
"code": null,
"e": 10345,
"s": 10329,
"text": "simranarora5sos"
},
{
"code": null,
"e": 10361,
"s": 10345,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 10375,
"s": 10361,
"text": "gautamgoel962"
},
{
"code": null,
"e": 10385,
"s": 10375,
"text": "Geometric"
},
{
"code": null,
"e": 10395,
"s": 10385,
"text": "Geometric"
},
{
"code": null,
"e": 10493,
"s": 10395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10542,
"s": 10493,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 10573,
"s": 10542,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 10631,
"s": 10573,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 10682,
"s": 10631,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 10729,
"s": 10682,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 10804,
"s": 10729,
"text": "Window to Viewport Transformation in Computer Graphics with Implementation"
},
{
"code": null,
"e": 10840,
"s": 10804,
"text": "Find K Closest Points to the Origin"
},
{
"code": null,
"e": 10889,
"s": 10840,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 10955,
"s": 10889,
"text": "Haversine formula to find distance between two points on a sphere"
}
] |
Python | Pandas Series.str.replace() to replace text in a series
|
18 Apr, 2022
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 that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Pandas series, .str has to be prefixed in order to differentiate it from the Python’s default replace method.
Syntax: Series.str.replace(pat, repl, n=-1, case=None, regex=True) Parameters: pat: string or compiled regex to be replaced repl: string or callable to replace instead of pat n: Number of replacement to make in a single string, default is -1 which means All. case: Takes boolean value to decide case sensitivity. Make false for case insensitivity regex: Boolean value, if True assume that the passed pattern is a regex Return Type: Series with replaced text values
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: Replacing values in age column In this example, all the values in age column having value 25.0 are replaced with “Twenty five” using str.replace() After that, a filter is created and passed in .where() method to only display the rows which have Age = “Twenty five”.
Python3
# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # overwriting column with replaced value of agedata["Age"]= data["Age"].replace(25.0, "Twenty five") # creating a filter for age column# where age = "Twenty five"filter = data["Age"]=="Twenty five" # printing only filtered columnsdata.where(filter).dropna()
Output: As shown in the output image, all the values in Age column having age=25.0 have been replaced by “Twenty five”. Example #2: Case Insensitivity In this example, team name Boston Celtics is replaced by New Boston Celtics. In the parameters, instead of passing Boston, boston is passed (with ‘b’ in lower case) and the case is set to False, which means case insensitive. After that only teams having team name “New Boston Celtics” are displayed using .where() method.
Python3
# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # overwriting column with replaced value of agedata["Team"]= data["Team"].str.replace("boston", "New Boston", case = False) # creating a filter for age column# where age = "Twenty five"filter = data["Team"]=="New Boston Celtics" # printing only filtered columnsdata.where(filter).dropna()
Output: As shown in the output image, Boston is replaced by New Boston irrespective of the lower case passed in the parameters. This is because the case parameter was set to False.
varshagumber28
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
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 489,
"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 that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Pandas series, .str has to be prefixed in order to differentiate it from the Python’s default replace method."
},
{
"code": null,
"e": 954,
"s": 489,
"text": "Syntax: Series.str.replace(pat, repl, n=-1, case=None, regex=True) Parameters: pat: string or compiled regex to be replaced repl: string or callable to replace instead of pat n: Number of replacement to make in a single string, default is -1 which means All. case: Takes boolean value to decide case sensitivity. Make false for case insensitivity regex: Boolean value, if True assume that the passed pattern is a regex Return Type: Series with replaced text values"
},
{
"code": null,
"e": 1427,
"s": 954,
"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. Example #1: Replacing values in age column In this example, all the values in age column having value 25.0 are replaced with “Twenty five” using str.replace() After that, a filter is created and passed in .where() method to only display the rows which have Age = “Twenty five”. "
},
{
"code": null,
"e": 1435,
"s": 1427,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # overwriting column with replaced value of agedata[\"Age\"]= data[\"Age\"].replace(25.0, \"Twenty five\") # creating a filter for age column# where age = \"Twenty five\"filter = data[\"Age\"]==\"Twenty five\" # printing only filtered columnsdata.where(filter).dropna()",
"e": 1846,
"s": 1435,
"text": null
},
{
"code": null,
"e": 2323,
"s": 1846,
"text": "Output: As shown in the output image, all the values in Age column having age=25.0 have been replaced by “Twenty five”. Example #2: Case Insensitivity In this example, team name Boston Celtics is replaced by New Boston Celtics. In the parameters, instead of passing Boston, boston is passed (with ‘b’ in lower case) and the case is set to False, which means case insensitive. After that only teams having team name “New Boston Celtics” are displayed using .where() method. "
},
{
"code": null,
"e": 2331,
"s": 2323,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # overwriting column with replaced value of agedata[\"Team\"]= data[\"Team\"].str.replace(\"boston\", \"New Boston\", case = False) # creating a filter for age column# where age = \"Twenty five\"filter = data[\"Team\"]==\"New Boston Celtics\" # printing only filtered columnsdata.where(filter).dropna()",
"e": 2773,
"s": 2331,
"text": null
},
{
"code": null,
"e": 2955,
"s": 2773,
"text": "Output: As shown in the output image, Boston is replaced by New Boston irrespective of the lower case passed in the parameters. This is because the case parameter was set to False. "
},
{
"code": null,
"e": 2970,
"s": 2955,
"text": "varshagumber28"
},
{
"code": null,
"e": 2991,
"s": 2970,
"text": "Python pandas-series"
},
{
"code": null,
"e": 3020,
"s": 2991,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 3034,
"s": 3020,
"text": "Python-pandas"
},
{
"code": null,
"e": 3041,
"s": 3034,
"text": "Python"
},
{
"code": null,
"e": 3139,
"s": 3041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3157,
"s": 3139,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3199,
"s": 3157,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3221,
"s": 3199,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3253,
"s": 3221,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3282,
"s": 3253,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3309,
"s": 3282,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3330,
"s": 3309,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3353,
"s": 3330,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3389,
"s": 3353,
"text": "Convert integer to string in Python"
}
] |
Python list | pop()
|
22 Jun, 2022
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
Syntax:
list_name.pop(index)
Parameter:
index (optional) – The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.
Returns: The last value or the given index value from the list.
Exception: When the index is out of range, it returns IndexError.
Python3
# Python3 program for pop() method list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last element from the listprint(list1.pop()) # Print list after removing last elementprint("New List after pop : ", list1, "\n") list2 = [1, 2, 3, ('cat', 'bat'), 4] # Pop last three elementprint(list2.pop())print(list2.pop())print(list2.pop()) # Print listprint("New List after pop : ", list2, "\n")
Output:
6
New List after pop : [1, 2, 3, 4, 5]
4
('cat', 'bat')
3
New List after pop : [1, 2]
Python3
# Python3 program showing pop() method# and remaining list after each pop list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last# element from the listprint(list1.pop(), list1) # Pops and removes the 0th index# element from the listprint(list1.pop(0), list1)
Output:
6 [1, 2, 3, 4, 5]
1 [2, 3, 4, 5]
Python3
# Python3 program for error in pop() method list1 = [ 1, 2, 3, 4, 5, 6 ]print(list1.pop(8))
Output:
Traceback (most recent call last):
File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in
print(list1.pop(8))
IndexError: pop index out of range
A list of the fruit contains fruit_name and property saying its fruit. Another list consume has two items juice and eat. With the help of pop() and append() we can do something interesting.
Python3
# Python3 program demonstrating# practical use of list pop() fruit = [['Orange','Fruit'],['Banana','Fruit'], ['Mango', 'Fruit']]consume = ['Juice', 'Eat']possible = [] # Iterating item in list fruitfor item in fruit : # Iterating use in list consume for use in consume : item.append(use) possible.append(item[:]) item.pop(-1)print(possible)
Output:
[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'],
['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'],
['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]
Time Complexity :
Complexity of all above examples is constant O(1) in both average and amortized case
nidhi_biet
pavelu786
AmiyaRanjanRout
simmytarika5
devendrasalunke
Python-Built-in-functions
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 184,
"s": 53,
"text": "Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value."
},
{
"code": null,
"e": 192,
"s": 184,
"text": "Syntax:"
},
{
"code": null,
"e": 213,
"s": 192,
"text": "list_name.pop(index)"
},
{
"code": null,
"e": 225,
"s": 213,
"text": "Parameter: "
},
{
"code": null,
"e": 366,
"s": 225,
"text": "index (optional) – The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed."
},
{
"code": null,
"e": 430,
"s": 366,
"text": "Returns: The last value or the given index value from the list."
},
{
"code": null,
"e": 496,
"s": 430,
"text": "Exception: When the index is out of range, it returns IndexError."
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Python3"
},
{
"code": "# Python3 program for pop() method list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last element from the listprint(list1.pop()) # Print list after removing last elementprint(\"New List after pop : \", list1, \"\\n\") list2 = [1, 2, 3, ('cat', 'bat'), 4] # Pop last three elementprint(list2.pop())print(list2.pop())print(list2.pop()) # Print listprint(\"New List after pop : \", list2, \"\\n\")",
"e": 892,
"s": 504,
"text": null
},
{
"code": null,
"e": 901,
"s": 892,
"text": "Output: "
},
{
"code": null,
"e": 992,
"s": 901,
"text": "6\nNew List after pop : [1, 2, 3, 4, 5] \n\n4\n('cat', 'bat')\n3\nNew List after pop : [1, 2] "
},
{
"code": null,
"e": 1000,
"s": 992,
"text": "Python3"
},
{
"code": "# Python3 program showing pop() method# and remaining list after each pop list1 = [ 1, 2, 3, 4, 5, 6 ] # Pops and removes the last# element from the listprint(list1.pop(), list1) # Pops and removes the 0th index# element from the listprint(list1.pop(0), list1)",
"e": 1261,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1269,
"s": 1261,
"text": "Output:"
},
{
"code": null,
"e": 1302,
"s": 1269,
"text": "6 [1, 2, 3, 4, 5]\n1 [2, 3, 4, 5]"
},
{
"code": null,
"e": 1310,
"s": 1302,
"text": "Python3"
},
{
"code": "# Python3 program for error in pop() method list1 = [ 1, 2, 3, 4, 5, 6 ]print(list1.pop(8))",
"e": 1402,
"s": 1310,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1402,
"text": "Output: "
},
{
"code": null,
"e": 1569,
"s": 1411,
"text": "Traceback (most recent call last):\n File \"/home/1875538d94d5aecde6edea47b57a2212.py\", line 5, in \n print(list1.pop(8))\nIndexError: pop index out of range"
},
{
"code": null,
"e": 1760,
"s": 1569,
"text": "A list of the fruit contains fruit_name and property saying its fruit. Another list consume has two items juice and eat. With the help of pop() and append() we can do something interesting. "
},
{
"code": null,
"e": 1768,
"s": 1760,
"text": "Python3"
},
{
"code": "# Python3 program demonstrating# practical use of list pop() fruit = [['Orange','Fruit'],['Banana','Fruit'], ['Mango', 'Fruit']]consume = ['Juice', 'Eat']possible = [] # Iterating item in list fruitfor item in fruit : # Iterating use in list consume for use in consume : item.append(use) possible.append(item[:]) item.pop(-1)print(possible)",
"e": 2150,
"s": 1768,
"text": null
},
{
"code": null,
"e": 2159,
"s": 2150,
"text": "Output: "
},
{
"code": null,
"e": 2334,
"s": 2159,
"text": "[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'],\n ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'],\n ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]"
},
{
"code": null,
"e": 2353,
"s": 2334,
"text": "Time Complexity : "
},
{
"code": null,
"e": 2439,
"s": 2353,
"text": "Complexity of all above examples is constant O(1) in both average and amortized case "
},
{
"code": null,
"e": 2450,
"s": 2439,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2460,
"s": 2450,
"text": "pavelu786"
},
{
"code": null,
"e": 2476,
"s": 2460,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 2489,
"s": 2476,
"text": "simmytarika5"
},
{
"code": null,
"e": 2505,
"s": 2489,
"text": "devendrasalunke"
},
{
"code": null,
"e": 2531,
"s": 2505,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2543,
"s": 2531,
"text": "python-list"
},
{
"code": null,
"e": 2565,
"s": 2543,
"text": "python-list-functions"
},
{
"code": null,
"e": 2572,
"s": 2565,
"text": "Python"
},
{
"code": null,
"e": 2584,
"s": 2572,
"text": "python-list"
}
] |
How to build an array of all combinations of two NumPy arrays?
|
05 Sep, 2020
Sometimes we need to find the combination of elements of two or more arrays. Numpy has a function to compute the combination of 2 or more Numpy arrays named as “numpy.meshgrid()“. This function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing.
Syntax:
numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
Example 1: Computing combinations of elements of Two NumPy arrays
Python3
# importing Numpy packageimport numpy as np # creating 2 numpy arraysarray_1 = np.array([1, 2])array_2 = np.array([4, 6]) print("Array-1")print(array_1) print("\nArray-2")print(array_2) # combination of elements of array_1 and array_2# using numpy.meshgrid().T.reshape()comb_array = np.array(np.meshgrid(array_1, array_2)).T.reshape(-1, 2) print("\nCombine array:")print(comb_array)
Output:
In the above example, we combine elements of ‘array_1‘ and ‘array_2‘ using numpy.meshgrid().T.reshape()
Example 2: Computing combinations of elements of Three NumPy arrays
Python3
# importing Numpy packageimport numpy as np # creating 3 numpy arraysarray_1 = np.array([1, 2, 3])array_2 = np.array([4, 6, 4])array_3 = np.array([3, 6]) print("Array-1")print(array_1) print("Array-2")print(array_2) print("Array-3")print(array_3) # combination of elements of array_1,# array_2 and array_3 using # numpy.meshgrid().T.reshape()comb_array = np.array( np.meshgrid(array_1, array_2, array_3)).T.reshape(-1, 3) print("\nCombine array:")print(comb_array)
Output:
In the above example, we combine elements of ‘array_1‘, ‘array_2‘ and ‘array_3‘ using numpy.meshgrid().T.reshape()
Example 3: Computing combinations of elements of Four NumPy arrays
Python3
# importing Numpy packageimport numpy as np # creating 4 numpy arraysarray_1 = np.array([50, 21])array_2 = np.array([4, 4])array_3 = np.array([1, 10])array_4 = np.array([7, 14]) print("Array-1")print(array_1) print("Array-2")print(array_2) print("Array-3")print(array_3) print("Array-4")print(array_4) # combination of elements of array_1, # array_2, array_3 and array_4# using numpy.meshgrid().T.reshape()comb_array = np.array(np.meshgrid( array_1, array_2, array_3, array_4)).T.reshape(-1, 4) print("\nCombine array:")print(comb_array)
Output:
In the above example, we combine elements of ‘array_1‘, ‘array_2‘, ‘array_3‘ and ‘array_4‘ using numpy.meshgrid().T.reshape()
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 380,
"s": 53,
"text": "Sometimes we need to find the combination of elements of two or more arrays. Numpy has a function to compute the combination of 2 or more Numpy arrays named as “numpy.meshgrid()“. This function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing."
},
{
"code": null,
"e": 388,
"s": 380,
"text": "Syntax:"
},
{
"code": null,
"e": 449,
"s": 388,
"text": "numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')\n"
},
{
"code": null,
"e": 515,
"s": 449,
"text": "Example 1: Computing combinations of elements of Two NumPy arrays"
},
{
"code": null,
"e": 523,
"s": 515,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating 2 numpy arraysarray_1 = np.array([1, 2])array_2 = np.array([4, 6]) print(\"Array-1\")print(array_1) print(\"\\nArray-2\")print(array_2) # combination of elements of array_1 and array_2# using numpy.meshgrid().T.reshape()comb_array = np.array(np.meshgrid(array_1, array_2)).T.reshape(-1, 2) print(\"\\nCombine array:\")print(comb_array)",
"e": 911,
"s": 523,
"text": null
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Output:"
},
{
"code": null,
"e": 1024,
"s": 919,
"text": "In the above example, we combine elements of ‘array_1‘ and ‘array_2‘ using numpy.meshgrid().T.reshape() "
},
{
"code": null,
"e": 1092,
"s": 1024,
"text": "Example 2: Computing combinations of elements of Three NumPy arrays"
},
{
"code": null,
"e": 1100,
"s": 1092,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating 3 numpy arraysarray_1 = np.array([1, 2, 3])array_2 = np.array([4, 6, 4])array_3 = np.array([3, 6]) print(\"Array-1\")print(array_1) print(\"Array-2\")print(array_2) print(\"Array-3\")print(array_3) # combination of elements of array_1,# array_2 and array_3 using # numpy.meshgrid().T.reshape()comb_array = np.array( np.meshgrid(array_1, array_2, array_3)).T.reshape(-1, 3) print(\"\\nCombine array:\")print(comb_array)",
"e": 1574,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1582,
"s": 1574,
"text": "Output:"
},
{
"code": null,
"e": 1697,
"s": 1582,
"text": "In the above example, we combine elements of ‘array_1‘, ‘array_2‘ and ‘array_3‘ using numpy.meshgrid().T.reshape()"
},
{
"code": null,
"e": 1764,
"s": 1697,
"text": "Example 3: Computing combinations of elements of Four NumPy arrays"
},
{
"code": null,
"e": 1772,
"s": 1764,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating 4 numpy arraysarray_1 = np.array([50, 21])array_2 = np.array([4, 4])array_3 = np.array([1, 10])array_4 = np.array([7, 14]) print(\"Array-1\")print(array_1) print(\"Array-2\")print(array_2) print(\"Array-3\")print(array_3) print(\"Array-4\")print(array_4) # combination of elements of array_1, # array_2, array_3 and array_4# using numpy.meshgrid().T.reshape()comb_array = np.array(np.meshgrid( array_1, array_2, array_3, array_4)).T.reshape(-1, 4) print(\"\\nCombine array:\")print(comb_array)",
"e": 2324,
"s": 1772,
"text": null
},
{
"code": null,
"e": 2332,
"s": 2324,
"text": "Output:"
},
{
"code": null,
"e": 2458,
"s": 2332,
"text": "In the above example, we combine elements of ‘array_1‘, ‘array_2‘, ‘array_3‘ and ‘array_4‘ using numpy.meshgrid().T.reshape()"
},
{
"code": null,
"e": 2485,
"s": 2458,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 2498,
"s": 2485,
"text": "Python-numpy"
},
{
"code": null,
"e": 2505,
"s": 2498,
"text": "Python"
},
{
"code": null,
"e": 2603,
"s": 2505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2635,
"s": 2603,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2662,
"s": 2635,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2693,
"s": 2662,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2716,
"s": 2693,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2737,
"s": 2716,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2793,
"s": 2737,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2835,
"s": 2793,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2877,
"s": 2835,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2916,
"s": 2877,
"text": "Python | Get unique values from a list"
}
] |
Python | Pandas Series.str.slice()
|
24 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.slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python’s basic principal of slicing objects that works on [start:stop:step] which means it requires three parameters, where to start, where to end and how much elements to skip.Since this is a pandas string method, .str has to be prefixed every time before calling this method. Otherwise, it gives an error.
Syntax: Series.str.slice(start=None, stop=None, step=None)
Parameters:start: int value, tells where to start slicingstop: int value, tells where to end slicingstep: int value, tells how much characters to step during slicing
Return type: Series with sliced substrings
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:In this example, the salary column has been sliced to get values before decimal. For example, we want to do some mathematical operations and for that we need integer data, so the salary column will be sliced till the 2nd last element(-2 position).Since the salary column is imported as float64 data type, it is first converted to string using the .astype() method.
# 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) # start stop and step variablesstart, stop, step = 0, -2, 1 # converting to string data typedata["Salary"]= data["Salary"].astype(str) # slicing till 2nd last elementdata["Salary (int)"]= data["Salary"].str.slice(start, stop, step) # displaydata.head(10)
Output:As shown in the output image, the string has been sliced and the string before decimal is stored in new column.Note:This method doesn’t have any parameters to handle null values and hence they were already removed using .dropna() method. Example #2:In this example, the name column is sliced and step parameter is kept 2. Hence it will be stepping two characters during slicing.
# 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) # start stop and step variablesstart, stop, step = 0, -2, 2 # slicing till 2nd last elementdata["Name"]= data["Name"].str.slice(start, stop, step) # displaydata.head(10)
Output:As it can be seen in the output image, the Name was sliced and 2 characters were skipped during slicing.
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.
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": "\n24 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": 673,
"s": 242,
"text": "Pandas str.slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python’s basic principal of slicing objects that works on [start:stop:step] which means it requires three parameters, where to start, where to end and how much elements to skip.Since this is a pandas string method, .str has to be prefixed every time before calling this method. Otherwise, it gives an error."
},
{
"code": null,
"e": 732,
"s": 673,
"text": "Syntax: Series.str.slice(start=None, stop=None, step=None)"
},
{
"code": null,
"e": 898,
"s": 732,
"text": "Parameters:start: int value, tells where to start slicingstop: int value, tells where to end slicingstep: int value, tells how much characters to step during slicing"
},
{
"code": null,
"e": 941,
"s": 898,
"text": "Return type: Series with sliced substrings"
},
{
"code": null,
"e": 987,
"s": 941,
"text": "To download the CSV used in code, click here."
},
{
"code": null,
"e": 1510,
"s": 987,
"text": "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:In this example, the salary column has been sliced to get values before decimal. For example, we want to do some mathematical operations and for that we need integer data, so the salary column will be sliced till the 2nd last element(-2 position).Since the salary column is imported as float64 data type, it is first converted to string using the .astype() method."
},
{
"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) # start stop and step variablesstart, stop, step = 0, -2, 1 # converting to string data typedata[\"Salary\"]= data[\"Salary\"].astype(str) # slicing till 2nd last elementdata[\"Salary (int)\"]= data[\"Salary\"].str.slice(start, stop, step) # displaydata.head(10)",
"e": 1992,
"s": 1510,
"text": null
},
{
"code": null,
"e": 2378,
"s": 1992,
"text": "Output:As shown in the output image, the string has been sliced and the string before decimal is stored in new column.Note:This method doesn’t have any parameters to handle null values and hence they were already removed using .dropna() method. Example #2:In this example, the name column is sliced and step parameter is kept 2. Hence it will be stepping two characters during slicing."
},
{
"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) # start stop and step variablesstart, stop, step = 0, -2, 2 # slicing till 2nd last elementdata[\"Name\"]= data[\"Name\"].str.slice(start, stop, step) # displaydata.head(10)",
"e": 2774,
"s": 2378,
"text": null
},
{
"code": null,
"e": 2886,
"s": 2774,
"text": "Output:As it can be seen in the output image, the Name was sliced and 2 characters were skipped during slicing."
},
{
"code": null,
"e": 2907,
"s": 2886,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2936,
"s": 2907,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2950,
"s": 2936,
"text": "Python-pandas"
},
{
"code": null,
"e": 2975,
"s": 2950,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2982,
"s": 2975,
"text": "Python"
},
{
"code": null,
"e": 3080,
"s": 2982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3112,
"s": 3080,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3139,
"s": 3112,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3160,
"s": 3139,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3183,
"s": 3160,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3239,
"s": 3183,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3270,
"s": 3239,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3312,
"s": 3270,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3354,
"s": 3312,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3393,
"s": 3354,
"text": "Python | Get unique values from a list"
}
] |
Check if a number is in given base or not
|
22 Jun, 2022
Given a number as a string and a base, check if the given number is in the given base or not.Examples:
Input : str = "1010", base = 2
Output : Yes
Input : str = "1015", base = 2
Output : No
Input : str = "AF87", base = 16
Output : Yes
The idea is to one by one check if all digits are in the given base range. If yes, return true, else return false.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if given// number is in given base or not.#include <cstring>#include <iostream>using namespace std; bool isInGivenBase(string str, int base){ // Allowed bases are till 16 (Hexadecimal) if (base > 16) return false; // If base is below or equal to 10, then all // digits should be from 0 to 9. else if (base <= 10) { for (int i = 0; i < str.length(); i++) if (!(str[i] >= '0' and str[i] < ('0' + base))) return false; } // If base is below or equal to 16, then all // digits should be from 0 to 9 or from 'A' else { for (int i = 0; i < str.length(); i++) if (! ((str[i] >= '0' && str[i] < ('0' + base)) || (str[i] >= 'A' && str[i] < ('A' + base - 10)) )) return false; } return true;} // Driver codeint main(){ string str = "AF87"; if (isInGivenBase(str, 16)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if given// number is in given base or not.class Geeks { static boolean isInGivenBase(String str, int base){ // Allowed bases are till 16 (Hexadecimal) if (base > 16) return false; // If base is below or equal to 10, then all // digits should be from 0 to 9. else if (base <= 10) { for (int i = 0; i < str.length(); i++) if (!(str.charAt(i) >= '0' && str.charAt(i) < ('0' + base))) return false; } // If base is below or equal to 16, then all // digits should be from 0 to 9 or from 'A' else { for (int i = 0; i < str.length(); i++) if (! ((str.charAt(i) >= '0' && str.charAt(i) < ('0' + base)) || (str.charAt(i) >= 'A' && str.charAt(i) < ('A' + base - 10)) )) return false; } return true;} // Driver Classpublic static void main(String args[]) { String str = "AF87"; if (isInGivenBase(str, 16) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by ankita_saini
# Python3 program to check if given# number is in given base or not. def isInGivenBase(Str, base): # Allowed bases are till 16 (Hexadecimal) if (base > 16): return False # If base is below or equal to 10, # then all digits should be from 0 to 9. elif (base <= 10): for i in range(len(Str)): if (Str[i].isnumeric() and (ord(Str[i]) >= ord('0') and ord(Str[i]) < (ord('0') + base)) == False): return False # If base is below or equal to 16, then all # digits should be from 0 to 9 or from 'A' else: for i in range(len(Str)): if (Str[i].isnumeric() and ((ord(Str[i]) >= ord('0') and ord(Str[i]) < (ord('0') + base)) or (ord(Str[i]) >= ord('A') and ord(Str[i]) < (ord('A') + base - 10))) == False): return False return True # Driver codeStr = "AF87"if (isInGivenBase(Str, 16)): print("Yes")else: print("No") # This code is contributed by Mohit Kumar
// C# program to check if given// number is in given base or not.using System; class GFG{static bool isInGivenBase(String str, int bas){ // Allowed base are // till 16 (Hexadecimal) if (bas > 16) return false; // If bas is below or equal // to 10, then all digits // should be from 0 to 9. else if (bas <= 10) { for (int i = 0; i < str.Length; i++) if (!(str[i] >= '0' && str[i] < ('0' + bas))) return false; } // If base is below or equal // to 16, then all digits should // be from 0 to 9 or from 'A' else { for (int i = 0; i < str.Length; i++) if (! ((str[i] >= '0' && str[i] < ('0' + bas)) || (str[i] >= 'A' && str[i] < ('A' + bas - 10)) )) return false; } return true;} // Driver Codepublic static void Main(String []args){ String str = "AF87"; if (isInGivenBase(str, 16) == true) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed// by ankita_saini
<?php// PHP program to check if given// number is in given base or not. function isInGivenBase($str, $base){ // Allowed bases are till // 16 (Hexadecimal) if ($base > 16) return false; // If base is below or equal to // 10, then all digits should // be from 0 to 9. else if ($base <= 10) { for ($i = 0; $i < strlen($str); $i++) if (!($str[$i] >= '0' and $str[$i] < ('0' + $base))) return false; } // If base is below or equal to 16, // then all digits should be from // 0 to 9 or from 'A' else { for ($i = 0; $i < strlen($str); $i++) if (! (($str[$i] >= '0' && $str[$i] < ('0' + $base)) || ($str[$i] >= 'A' && $str[$i] < ('A' + $base - 10)) )) return false; } return true;} // Driver code$str = "AF87"; if (isInGivenBase($str, 16)) echo "Yes";else echo "No"; // This code is contributed by jit_t?>
<script> // Javascript program to check if given // number is in given base or not. function isInGivenBase(str, bas) { // Allowed base are // till 16 (Hexadecimal) if (bas > 16) return false; // If bas is below or equal // to 10, then all digits // should be from 0 to 9. else if (bas <= 10) { for (let i = 0; i < str.length; i++) if (!(str[i].charCodeAt() >= '0'.charCodeAt() && str[i].charCodeAt() < ('0'.charCodeAt() + bas))) return false; } // If base is below or equal // to 16, then all digits should // be from 0 to 9 or from 'A' else { for (let i = 0; i < str.length; i++) if (! ((str[i].charCodeAt() >= '0'.charCodeAt() && str[i].charCodeAt() < ('0'.charCodeAt() + bas)) || (str[i].charCodeAt() >= 'A'.charCodeAt() && str[i].charCodeAt() < ('A'.charCodeAt() + bas - 10)) )) return false; } return true; } let str = "AF87"; if (isInGivenBase(str, 16) == true) document.write("Yes"); else document.write("No"); </script>
Yes
Time complexity: O(n), where n is the length of the given string.Auxiliar Space:O(1)
ankita_saini
jit_t
mohit kumar 29
divyesh072019
hasani
base-conversion
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Convert string to char array in C++
Check whether two strings are anagram of each other
Reverse words in a given string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 157,
"s": 52,
"text": "Given a number as a string and a base, check if the given number is in the given base or not.Examples: "
},
{
"code": null,
"e": 293,
"s": 157,
"text": "Input : str = \"1010\", base = 2\nOutput : Yes\n\nInput : str = \"1015\", base = 2\nOutput : No\n\nInput : str = \"AF87\", base = 16\nOutput : Yes\n "
},
{
"code": null,
"e": 408,
"s": 293,
"text": "The idea is to one by one check if all digits are in the given base range. If yes, return true, else return false."
},
{
"code": null,
"e": 412,
"s": 408,
"text": "C++"
},
{
"code": null,
"e": 417,
"s": 412,
"text": "Java"
},
{
"code": null,
"e": 425,
"s": 417,
"text": "Python3"
},
{
"code": null,
"e": 428,
"s": 425,
"text": "C#"
},
{
"code": null,
"e": 432,
"s": 428,
"text": "PHP"
},
{
"code": null,
"e": 443,
"s": 432,
"text": "Javascript"
},
{
"code": "// CPP program to check if given// number is in given base or not.#include <cstring>#include <iostream>using namespace std; bool isInGivenBase(string str, int base){ // Allowed bases are till 16 (Hexadecimal) if (base > 16) return false; // If base is below or equal to 10, then all // digits should be from 0 to 9. else if (base <= 10) { for (int i = 0; i < str.length(); i++) if (!(str[i] >= '0' and str[i] < ('0' + base))) return false; } // If base is below or equal to 16, then all // digits should be from 0 to 9 or from 'A' else { for (int i = 0; i < str.length(); i++) if (! ((str[i] >= '0' && str[i] < ('0' + base)) || (str[i] >= 'A' && str[i] < ('A' + base - 10)) )) return false; } return true;} // Driver codeint main(){ string str = \"AF87\"; if (isInGivenBase(str, 16)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 1491,
"s": 443,
"text": null
},
{
"code": "// Java program to check if given// number is in given base or not.class Geeks { static boolean isInGivenBase(String str, int base){ // Allowed bases are till 16 (Hexadecimal) if (base > 16) return false; // If base is below or equal to 10, then all // digits should be from 0 to 9. else if (base <= 10) { for (int i = 0; i < str.length(); i++) if (!(str.charAt(i) >= '0' && str.charAt(i) < ('0' + base))) return false; } // If base is below or equal to 16, then all // digits should be from 0 to 9 or from 'A' else { for (int i = 0; i < str.length(); i++) if (! ((str.charAt(i) >= '0' && str.charAt(i) < ('0' + base)) || (str.charAt(i) >= 'A' && str.charAt(i) < ('A' + base - 10)) )) return false; } return true;} // Driver Classpublic static void main(String args[]) { String str = \"AF87\"; if (isInGivenBase(str, 16) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by ankita_saini",
"e": 2648,
"s": 1491,
"text": null
},
{
"code": "# Python3 program to check if given# number is in given base or not. def isInGivenBase(Str, base): # Allowed bases are till 16 (Hexadecimal) if (base > 16): return False # If base is below or equal to 10, # then all digits should be from 0 to 9. elif (base <= 10): for i in range(len(Str)): if (Str[i].isnumeric() and (ord(Str[i]) >= ord('0') and ord(Str[i]) < (ord('0') + base)) == False): return False # If base is below or equal to 16, then all # digits should be from 0 to 9 or from 'A' else: for i in range(len(Str)): if (Str[i].isnumeric() and ((ord(Str[i]) >= ord('0') and ord(Str[i]) < (ord('0') + base)) or (ord(Str[i]) >= ord('A') and ord(Str[i]) < (ord('A') + base - 10))) == False): return False return True # Driver codeStr = \"AF87\"if (isInGivenBase(Str, 16)): print(\"Yes\")else: print(\"No\") # This code is contributed by Mohit Kumar",
"e": 3706,
"s": 2648,
"text": null
},
{
"code": "// C# program to check if given// number is in given base or not.using System; class GFG{static bool isInGivenBase(String str, int bas){ // Allowed base are // till 16 (Hexadecimal) if (bas > 16) return false; // If bas is below or equal // to 10, then all digits // should be from 0 to 9. else if (bas <= 10) { for (int i = 0; i < str.Length; i++) if (!(str[i] >= '0' && str[i] < ('0' + bas))) return false; } // If base is below or equal // to 16, then all digits should // be from 0 to 9 or from 'A' else { for (int i = 0; i < str.Length; i++) if (! ((str[i] >= '0' && str[i] < ('0' + bas)) || (str[i] >= 'A' && str[i] < ('A' + bas - 10)) )) return false; } return true;} // Driver Codepublic static void Main(String []args){ String str = \"AF87\"; if (isInGivenBase(str, 16) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed// by ankita_saini",
"e": 4836,
"s": 3706,
"text": null
},
{
"code": "<?php// PHP program to check if given// number is in given base or not. function isInGivenBase($str, $base){ // Allowed bases are till // 16 (Hexadecimal) if ($base > 16) return false; // If base is below or equal to // 10, then all digits should // be from 0 to 9. else if ($base <= 10) { for ($i = 0; $i < strlen($str); $i++) if (!($str[$i] >= '0' and $str[$i] < ('0' + $base))) return false; } // If base is below or equal to 16, // then all digits should be from // 0 to 9 or from 'A' else { for ($i = 0; $i < strlen($str); $i++) if (! (($str[$i] >= '0' && $str[$i] < ('0' + $base)) || ($str[$i] >= 'A' && $str[$i] < ('A' + $base - 10)) )) return false; } return true;} // Driver code$str = \"AF87\"; if (isInGivenBase($str, 16)) echo \"Yes\";else echo \"No\"; // This code is contributed by jit_t?>",
"e": 5841,
"s": 4836,
"text": null
},
{
"code": "<script> // Javascript program to check if given // number is in given base or not. function isInGivenBase(str, bas) { // Allowed base are // till 16 (Hexadecimal) if (bas > 16) return false; // If bas is below or equal // to 10, then all digits // should be from 0 to 9. else if (bas <= 10) { for (let i = 0; i < str.length; i++) if (!(str[i].charCodeAt() >= '0'.charCodeAt() && str[i].charCodeAt() < ('0'.charCodeAt() + bas))) return false; } // If base is below or equal // to 16, then all digits should // be from 0 to 9 or from 'A' else { for (let i = 0; i < str.length; i++) if (! ((str[i].charCodeAt() >= '0'.charCodeAt() && str[i].charCodeAt() < ('0'.charCodeAt() + bas)) || (str[i].charCodeAt() >= 'A'.charCodeAt() && str[i].charCodeAt() < ('A'.charCodeAt() + bas - 10)) )) return false; } return true; } let str = \"AF87\"; if (isInGivenBase(str, 16) == true) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 7211,
"s": 5841,
"text": null
},
{
"code": null,
"e": 7215,
"s": 7211,
"text": "Yes"
},
{
"code": null,
"e": 7300,
"s": 7215,
"text": "Time complexity: O(n), where n is the length of the given string.Auxiliar Space:O(1)"
},
{
"code": null,
"e": 7313,
"s": 7300,
"text": "ankita_saini"
},
{
"code": null,
"e": 7319,
"s": 7313,
"text": "jit_t"
},
{
"code": null,
"e": 7334,
"s": 7319,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7348,
"s": 7334,
"text": "divyesh072019"
},
{
"code": null,
"e": 7355,
"s": 7348,
"text": "hasani"
},
{
"code": null,
"e": 7371,
"s": 7355,
"text": "base-conversion"
},
{
"code": null,
"e": 7379,
"s": 7371,
"text": "Strings"
},
{
"code": null,
"e": 7387,
"s": 7379,
"text": "Strings"
},
{
"code": null,
"e": 7485,
"s": 7387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7530,
"s": 7485,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 7587,
"s": 7530,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 7662,
"s": 7587,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 7698,
"s": 7662,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 7736,
"s": 7698,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 7797,
"s": 7736,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 7842,
"s": 7797,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 7878,
"s": 7842,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 7930,
"s": 7878,
"text": "Check whether two strings are anagram of each other"
}
] |
Java Program for efficiently print all prime factors of a given number
|
19 Oct, 2021
Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”. Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.
Java
// Program to print all prime factorsimport java.io.*;import java.lang.Math; class GFG { // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { System.out.print(i + " "); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main(String[] args) { int n = 315; primeFactors(n); }}
3 3 5 7
Time Complexity: O(n1/2)
Auxiliary Space: O(1)
How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers. Every composite number has at least one prime factor less than or equal to square root of itself. This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”. In step 2 of the above algorithm, we run a loop and do following in loop a) Find the least prime factor i (must be less than √n, ) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.Please refer complete article on Efficient program to print all prime factors of a given number for more details!
subhammahato348
rishavmahato348
Prime Number
prime-factor
Java Programs
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 666,
"s": 54,
"text": "Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”. Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue. 3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2. "
},
{
"code": null,
"e": 671,
"s": 666,
"text": "Java"
},
{
"code": "// Program to print all prime factorsimport java.io.*;import java.lang.Math; class GFG { // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { System.out.print(2 + \" \"); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { System.out.print(i + \" \"); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main(String[] args) { int n = 315; primeFactors(n); }}",
"e": 1589,
"s": 671,
"text": null
},
{
"code": null,
"e": 1597,
"s": 1589,
"text": "3 3 5 7"
},
{
"code": null,
"e": 1624,
"s": 1599,
"text": "Time Complexity: O(n1/2)"
},
{
"code": null,
"e": 1646,
"s": 1624,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2986,
"s": 1646,
"text": "How does this work? The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers. Every composite number has at least one prime factor less than or equal to square root of itself. This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”. In step 2 of the above algorithm, we run a loop and do following in loop a) Find the least prime factor i (must be less than √n, ) b) Remove all occurrences i from n by repeatedly dividing n by i. c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.Please refer complete article on Efficient program to print all prime factors of a given number for more details! "
},
{
"code": null,
"e": 3002,
"s": 2986,
"text": "subhammahato348"
},
{
"code": null,
"e": 3018,
"s": 3002,
"text": "rishavmahato348"
},
{
"code": null,
"e": 3031,
"s": 3018,
"text": "Prime Number"
},
{
"code": null,
"e": 3044,
"s": 3031,
"text": "prime-factor"
},
{
"code": null,
"e": 3058,
"s": 3044,
"text": "Java Programs"
},
{
"code": null,
"e": 3071,
"s": 3058,
"text": "Mathematical"
},
{
"code": null,
"e": 3084,
"s": 3071,
"text": "Mathematical"
},
{
"code": null,
"e": 3097,
"s": 3084,
"text": "Prime Number"
},
{
"code": null,
"e": 3195,
"s": 3097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3233,
"s": 3195,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 3290,
"s": 3233,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 3319,
"s": 3290,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 3400,
"s": 3319,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 3432,
"s": 3400,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 3462,
"s": 3432,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 3505,
"s": 3462,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3565,
"s": 3505,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 3580,
"s": 3565,
"text": "C++ Data Types"
}
] |
How to access popup login window in selenium using Python
|
23 Sep, 2021
Many websites use sign-in using social media to make the login process easy for users. In most cases, if the button is clicked then a new popup window is opened where user has to enter their user credentials. Manually one can switch windows in a browser and enter the required credentials to log in. But in case of unattended web access using webdriver, the driver can not just switch the windows automatically. We need to change the window handle in the driver to enter the login credentials in the popup window. Selenium have the function to switch the window to access multiple windows using the same driver.First, we have to get the current window handle from a webdriver which can be done by:
driver.current_window_handle
We need to save it in order to get the to the current window handle. After the popup window appears we have to get the list of all the window handles available right now.
driver.window_handles
Then we can get the window handle of the login page from this list and then switch the control. To switch window handle, use:
driver.swtich_to.window(login_page)
After successful login we can use the same switch_to method to change control to the previous page. Note: To run this code selenium library and geckodriver for firefox is required. The installation of selenium can be done using Python third-party library installer pip. To install selenium run this command
pip install selenium
For geckodriver, download the file and add it’s path to the OS PATH variable, so that it can be activated from anywhere in file directory.Let’s see the code for login on zomato.com using Facebook.
Python3
# import the libsfrom selenium import webdriverfrom time import sleep # create the initial windowdriver = webdriver.Firefox() # go to the home pagedriver.get('https://www.zomato.com') # storing the current window handle to get back to dashboardmain_page = driver.current_window_handle # wait for page to load completelysleep(5) # click on the sign in tabdriver.find_element_by_xpath('//*[@id ="signin-link"]').click() sleep(5) # click to log in using facebookdriver.find_element_by_xpath('//*[@id ="facebook-login-global"]/span').click() # changing the handles to access login pagefor handle in driver.window_handles: if handle != main_page: login_page = handle # change the control to signin page driver.switch_to.window(login_page) # user input for email and passwordprint('Enter email id : ', end ='')email = input().strip()print('Enter password : ', end ='')password = input().strip() # enter the emaildriver.find_element_by_xpath('//*[@id ="email"]').send_keys(email) # enter the passworddriver.find_element_by_xpath('//*[@id ="pass"]').send_keys(password) # click the login buttondriver.find_element_by_xpath('//*[@id ="u_0_0"]').click() # change control to main pagedriver.switch_to.window(main_page) sleep(10)# print user namename = driver.find_element_by_xpath('/html/body/div[4]/div/div[1]/header/div[2]/div/div/div/div/span').textprint('Your user name is : {}'.format(name)) # closing the windowdriver.quit()
Output:
anikakapoor
python-utility
selenium
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
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 728,
"s": 28,
"text": "Many websites use sign-in using social media to make the login process easy for users. In most cases, if the button is clicked then a new popup window is opened where user has to enter their user credentials. Manually one can switch windows in a browser and enter the required credentials to log in. But in case of unattended web access using webdriver, the driver can not just switch the windows automatically. We need to change the window handle in the driver to enter the login credentials in the popup window. Selenium have the function to switch the window to access multiple windows using the same driver.First, we have to get the current window handle from a webdriver which can be done by: "
},
{
"code": null,
"e": 757,
"s": 728,
"text": "driver.current_window_handle"
},
{
"code": null,
"e": 930,
"s": 757,
"text": "We need to save it in order to get the to the current window handle. After the popup window appears we have to get the list of all the window handles available right now. "
},
{
"code": null,
"e": 952,
"s": 930,
"text": "driver.window_handles"
},
{
"code": null,
"e": 1080,
"s": 952,
"text": "Then we can get the window handle of the login page from this list and then switch the control. To switch window handle, use: "
},
{
"code": null,
"e": 1116,
"s": 1080,
"text": "driver.swtich_to.window(login_page)"
},
{
"code": null,
"e": 1425,
"s": 1116,
"text": "After successful login we can use the same switch_to method to change control to the previous page. Note: To run this code selenium library and geckodriver for firefox is required. The installation of selenium can be done using Python third-party library installer pip. To install selenium run this command "
},
{
"code": null,
"e": 1446,
"s": 1425,
"text": "pip install selenium"
},
{
"code": null,
"e": 1644,
"s": 1446,
"text": "For geckodriver, download the file and add it’s path to the OS PATH variable, so that it can be activated from anywhere in file directory.Let’s see the code for login on zomato.com using Facebook. "
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Python3"
},
{
"code": "# import the libsfrom selenium import webdriverfrom time import sleep # create the initial windowdriver = webdriver.Firefox() # go to the home pagedriver.get('https://www.zomato.com') # storing the current window handle to get back to dashboardmain_page = driver.current_window_handle # wait for page to load completelysleep(5) # click on the sign in tabdriver.find_element_by_xpath('//*[@id =\"signin-link\"]').click() sleep(5) # click to log in using facebookdriver.find_element_by_xpath('//*[@id =\"facebook-login-global\"]/span').click() # changing the handles to access login pagefor handle in driver.window_handles: if handle != main_page: login_page = handle # change the control to signin page driver.switch_to.window(login_page) # user input for email and passwordprint('Enter email id : ', end ='')email = input().strip()print('Enter password : ', end ='')password = input().strip() # enter the emaildriver.find_element_by_xpath('//*[@id =\"email\"]').send_keys(email) # enter the passworddriver.find_element_by_xpath('//*[@id =\"pass\"]').send_keys(password) # click the login buttondriver.find_element_by_xpath('//*[@id =\"u_0_0\"]').click() # change control to main pagedriver.switch_to.window(main_page) sleep(10)# print user namename = driver.find_element_by_xpath('/html/body/div[4]/div/div[1]/header/div[2]/div/div/div/div/span').textprint('Your user name is : {}'.format(name)) # closing the windowdriver.quit()",
"e": 3098,
"s": 1652,
"text": null
},
{
"code": null,
"e": 3108,
"s": 3098,
"text": "Output: "
},
{
"code": null,
"e": 3122,
"s": 3110,
"text": "anikakapoor"
},
{
"code": null,
"e": 3137,
"s": 3122,
"text": "python-utility"
},
{
"code": null,
"e": 3146,
"s": 3137,
"text": "selenium"
},
{
"code": null,
"e": 3153,
"s": 3146,
"text": "Python"
},
{
"code": null,
"e": 3251,
"s": 3153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3269,
"s": 3251,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3311,
"s": 3269,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3333,
"s": 3311,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3368,
"s": 3333,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3394,
"s": 3368,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3426,
"s": 3394,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3455,
"s": 3426,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3482,
"s": 3455,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3503,
"s": 3482,
"text": "Python OOPs Concepts"
}
] |
Output of C Program | Set 24
|
22 Feb, 2022
Predict the output of following C programs:Difficulty Level: Rookie Question 1
C
#include<stdio.h>int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf ("ptr2 - ptr1 = %d\n", ptr2 - ptr1); printf ("(char*)ptr2 - (char*) ptr1 = %d", (char*)ptr2 - (char*)ptr1); getchar(); return 0;}
Output:
ptr2 - ptr1 = 5
(char*)ptr2 - (char*) ptr1 = 20
In C, array name gives address of the first element in the array. So when we do ptr1 = arr, ptr1 starts pointing to address of first element of arr. Since array elements are accessed using pointer arithmetic, arr + 5 is a valid expression and gives the address of 6th element. Predicting value ptr2 – ptr1 is easy, it gives 5 as there are 5 integers between these two addresses. When we do (char *)ptr2, ptr2 is typecasted to char pointer. In expression “(int*)ptr2 – (int*)ptr1”, pointer arithmetic happens considering character pointers. Since size of a character is one byte, we get 5*sizeof(int) (which is 20) as difference of two pointers. As an exercise, predict the output of following program.
C
#include<stdio.h>int main(){ char arr[] = "geeksforgeeks"; char *ptr1 = arr; char *ptr2 = ptr1 + 3; printf ("ptr2 - ptr1 = %d\n", ptr2 - ptr1); printf ("(int*)ptr2 - (int*) ptr1 = %d", (int*)ptr2 - (int*)ptr1); getchar(); return 0;}
Question 2
C
#include<stdio.h> int main(){ char arr[] = "geeks\0 for geeks"; char *str = "geeks\0 for geeks"; printf ("arr = %s, sizeof(arr) = %d \n", arr, sizeof(arr)); printf ("str = %s, sizeof(str) = %d", str, sizeof(str)); getchar(); return 0;}
Output:
arr = geeks, sizeof(arr) = 17
str = geeks, sizeof(str) = 4
Let us first talk about first output “arr = geeks”. When %s is used to print a string, printf starts from the first character at given address and keeps printing characters until it sees a string termination character, so we get “arr = geeks” as there is a \0 after geeks in arr[]. Now let us talk about output “sizeof(arr) = 17”. When a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\0′ (See this Gfact), that is why size of arr is 17. Explanation for printing “str = geeks” is same as printing “arr = geeks”. Talking about value of sizeof(str), str is just a pointer (not array), so we get size of a pointer as output (which can also be equal to 8 in case you are using a 64 bit machine).Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above
jyotibaby101
varshagumber28
simmytarika5
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of Java Program | Set 3
Output of C++ programs | Set 47 (Pointers)
Output of Java Programs | Set 12
Output of Java Program | Set 7
Output of C Programs | Set 3
Output of C programs | Set 59 (Loops and Control Statements)
unsigned specifier (%u) in C with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 135,
"s": 54,
"text": "Predict the output of following C programs:Difficulty Level: Rookie Question 1 "
},
{
"code": null,
"e": 137,
"s": 135,
"text": "C"
},
{
"code": "#include<stdio.h>int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf (\"ptr2 - ptr1 = %d\\n\", ptr2 - ptr1); printf (\"(char*)ptr2 - (char*) ptr1 = %d\", (char*)ptr2 - (char*)ptr1); getchar(); return 0;}",
"e": 401,
"s": 137,
"text": null
},
{
"code": null,
"e": 411,
"s": 401,
"text": "Output: "
},
{
"code": null,
"e": 463,
"s": 411,
"text": " ptr2 - ptr1 = 5\n (char*)ptr2 - (char*) ptr1 = 20"
},
{
"code": null,
"e": 1167,
"s": 463,
"text": "In C, array name gives address of the first element in the array. So when we do ptr1 = arr, ptr1 starts pointing to address of first element of arr. Since array elements are accessed using pointer arithmetic, arr + 5 is a valid expression and gives the address of 6th element. Predicting value ptr2 – ptr1 is easy, it gives 5 as there are 5 integers between these two addresses. When we do (char *)ptr2, ptr2 is typecasted to char pointer. In expression “(int*)ptr2 – (int*)ptr1”, pointer arithmetic happens considering character pointers. Since size of a character is one byte, we get 5*sizeof(int) (which is 20) as difference of two pointers. As an exercise, predict the output of following program. "
},
{
"code": null,
"e": 1169,
"s": 1167,
"text": "C"
},
{
"code": "#include<stdio.h>int main(){ char arr[] = \"geeksforgeeks\"; char *ptr1 = arr; char *ptr2 = ptr1 + 3; printf (\"ptr2 - ptr1 = %d\\n\", ptr2 - ptr1); printf (\"(int*)ptr2 - (int*) ptr1 = %d\", (int*)ptr2 - (int*)ptr1); getchar(); return 0;}",
"e": 1424,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1436,
"s": 1424,
"text": "Question 2 "
},
{
"code": null,
"e": 1438,
"s": 1436,
"text": "C"
},
{
"code": "#include<stdio.h> int main(){ char arr[] = \"geeks\\0 for geeks\"; char *str = \"geeks\\0 for geeks\"; printf (\"arr = %s, sizeof(arr) = %d \\n\", arr, sizeof(arr)); printf (\"str = %s, sizeof(str) = %d\", str, sizeof(str)); getchar(); return 0;}",
"e": 1680,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1690,
"s": 1680,
"text": "Output: "
},
{
"code": null,
"e": 1753,
"s": 1690,
"text": " arr = geeks, sizeof(arr) = 17\n str = geeks, sizeof(str) = 4"
},
{
"code": null,
"e": 2702,
"s": 1753,
"text": "Let us first talk about first output “arr = geeks”. When %s is used to print a string, printf starts from the first character at given address and keeps printing characters until it sees a string termination character, so we get “arr = geeks” as there is a \\0 after geeks in arr[]. Now let us talk about output “sizeof(arr) = 17”. When a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\\0′ (See this Gfact), that is why size of arr is 17. Explanation for printing “str = geeks” is same as printing “arr = geeks”. Talking about value of sizeof(str), str is just a pointer (not array), so we get size of a pointer as output (which can also be equal to 8 in case you are using a 64 bit machine).Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 2715,
"s": 2702,
"text": "jyotibaby101"
},
{
"code": null,
"e": 2730,
"s": 2715,
"text": "varshagumber28"
},
{
"code": null,
"e": 2743,
"s": 2730,
"text": "simmytarika5"
},
{
"code": null,
"e": 2752,
"s": 2743,
"text": "C-Output"
},
{
"code": null,
"e": 2767,
"s": 2752,
"text": "Program Output"
},
{
"code": null,
"e": 2865,
"s": 2767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2880,
"s": 2865,
"text": "Runtime Errors"
},
{
"code": null,
"e": 2921,
"s": 2880,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 2951,
"s": 2921,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 2982,
"s": 2951,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 3025,
"s": 2982,
"text": "Output of C++ programs | Set 47 (Pointers)"
},
{
"code": null,
"e": 3058,
"s": 3025,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 3089,
"s": 3058,
"text": "Output of Java Program | Set 7"
},
{
"code": null,
"e": 3118,
"s": 3089,
"text": "Output of C Programs | Set 3"
},
{
"code": null,
"e": 3179,
"s": 3118,
"text": "Output of C programs | Set 59 (Loops and Control Statements)"
}
] |
Python | Replace multiple occurrence of character by single
|
29 Dec, 2020
Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character.
Examples:
Input : Geeksforgeeks, ch = 'e'
Output : Geksforgeks
Input : Wiiiin, ch = 'i'
Output : Win
Approach #1 : Naive ApproachThis method is a brute force approach in which we take another list ‘new_str’. Use a for loop to check if the given character is repeated or not. If repeated multiple times, append the character single time to the list. Other characters(Not the given character) are simply appended to the list without any alteration.
# Python program to replace multiple # occurrences of a character by a single character def replace(s, ch): new_str = [] l = len(s) for i in range(len(s)): if (s[i] == ch and i != (l-1) and i != 0 and s[i + 1] != ch and s[i-1] != ch): new_str.append(s[i]) elif s[i] == ch: if ((i != (l-1) and s[i + 1] == ch) and (i != 0 and s[i-1] != ch)): new_str.append(s[i]) else: new_str.append(s[i]) return ("".join(i for i in new_str)) # Driver code s = 'Geeksforgeeks'char = 'e'print(replace(s, char))
Geksforgeks
Approach #2 : Using Python Regex
import re # Function to replace multiple occurrences # of a character by a single characterdef replace(string, char): pattern = char + '{2,}' string = re.sub(pattern, char, string) return string # Driver code string = 'Geeksforgeeks'char = 'e'print(replace(string, char))
Geksforgeks
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character."
},
{
"code": null,
"e": 171,
"s": 161,
"text": "Examples:"
},
{
"code": null,
"e": 264,
"s": 171,
"text": "Input : Geeksforgeeks, ch = 'e'\nOutput : Geksforgeks\n\nInput : Wiiiin, ch = 'i'\nOutput : Win\n"
},
{
"code": null,
"e": 612,
"s": 266,
"text": "Approach #1 : Naive ApproachThis method is a brute force approach in which we take another list ‘new_str’. Use a for loop to check if the given character is repeated or not. If repeated multiple times, append the character single time to the list. Other characters(Not the given character) are simply appended to the list without any alteration."
},
{
"code": "# Python program to replace multiple # occurrences of a character by a single character def replace(s, ch): new_str = [] l = len(s) for i in range(len(s)): if (s[i] == ch and i != (l-1) and i != 0 and s[i + 1] != ch and s[i-1] != ch): new_str.append(s[i]) elif s[i] == ch: if ((i != (l-1) and s[i + 1] == ch) and (i != 0 and s[i-1] != ch)): new_str.append(s[i]) else: new_str.append(s[i]) return (\"\".join(i for i in new_str)) # Driver code s = 'Geeksforgeeks'char = 'e'print(replace(s, char))",
"e": 1262,
"s": 612,
"text": null
},
{
"code": null,
"e": 1275,
"s": 1262,
"text": "Geksforgeks\n"
},
{
"code": null,
"e": 1309,
"s": 1275,
"text": " Approach #2 : Using Python Regex"
},
{
"code": "import re # Function to replace multiple occurrences # of a character by a single characterdef replace(string, char): pattern = char + '{2,}' string = re.sub(pattern, char, string) return string # Driver code string = 'Geeksforgeeks'char = 'e'print(replace(string, char))",
"e": 1593,
"s": 1309,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1593,
"text": "Geksforgeks\n"
},
{
"code": null,
"e": 1628,
"s": 1606,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1641,
"s": 1628,
"text": "python-regex"
},
{
"code": null,
"e": 1648,
"s": 1641,
"text": "Python"
},
{
"code": null,
"e": 1664,
"s": 1648,
"text": "Python Programs"
}
] |
Using throw, catch and instanceof to handle Exceptions in Java
|
06 Feb, 2019
Prerequisite : Try-Catch Block in JavaIn Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the ‘try’ block may be vulnerable to more than one exceptions. For example, take a look at the following sample code:
// A sample Java code with a try catch block// where the try block has only one catch block// to handle all possible exceptions // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array y[x] = 10; } catch (Exception e) { System.out.println("Exception occurred"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}
Output in case of either of the exceptions:
Exception occurred
As you can see from the above code, there is a possibility that either of the two exceptions mentioned above can occur. In order to handle them both, the catch statement is made to accept any exception that can occur by passing a reference to the Exception class, that is the parent of all exception classes. However, this catch statement does the same thing for all kinds of exceptions.
Specify Custom Actions for different Exceptions
In order to specify custom actions in such cases, programmers usually put multiple catch statements, such as in the following example:
// A sample Java code with one try block// having multiple catch blocks to catch// different exceptions // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array y[x] = 10; } catch (ArithmeticException e) { System.out.println("Dividing by 0"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("That index doesn't exist"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}
Output:
a) In case of ArithmeticException: Dividing by 0
b) In case of ArrayIndexOutOfBoundsException: That index doesn't exist
Specify Custom Actions for different Exceptions using instanceof
However, there is a way to do the same thing by using only one catch block. To do so, java provides an operator: instanceof.By using this operator, we can specify custom actions for the different exceptions that occur. The following program demonstrates how:
// Java program to demonstrate the use of// instanceof to specify different actions for// different exceptions using only one catch block // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; y[x] = 10; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array System.out.println("No exception arose"); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println("Can't divide by 0"); if (e instanceof ArrayIndexOutOfBoundsException) System.out.println("This index doesn't exist in this array"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}
Output:
a) In case of ArithmeticException:
Can't divide by 0
b) In case of ArrayIndexOutOfBoundsException:
This index doesn't exist in this array
c) In case of no exception: No exception arose
By using the instanceof operator in exception handling, it is easy to achieve the aforementioned objective and at the same time, it makes your code less complicated. One thing that has to be noted here is that as soon as the try block encounters an exception, the control will directly jump to the catch block, to handle, thereby, preventing the rest of the body of the try block from executing. As a result, even though there may be possibility of more than one exceptions occurring, the try block will only throw one exception, before shifting control to the catch block.
Java-Exception Handling
Java-Exceptions
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": "\n06 Feb, 2019"
},
{
"code": null,
"e": 416,
"s": 52,
"text": "Prerequisite : Try-Catch Block in JavaIn Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the ‘try’ block may be vulnerable to more than one exceptions. For example, take a look at the following sample code:"
},
{
"code": "// A sample Java code with a try catch block// where the try block has only one catch block// to handle all possible exceptions // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array y[x] = 10; } catch (Exception e) { System.out.println(\"Exception occurred\"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}",
"e": 1176,
"s": 416,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1176,
"text": "Output in case of either of the exceptions:"
},
{
"code": null,
"e": 1239,
"s": 1220,
"text": "Exception occurred"
},
{
"code": null,
"e": 1627,
"s": 1239,
"text": "As you can see from the above code, there is a possibility that either of the two exceptions mentioned above can occur. In order to handle them both, the catch statement is made to accept any exception that can occur by passing a reference to the Exception class, that is the parent of all exception classes. However, this catch statement does the same thing for all kinds of exceptions."
},
{
"code": null,
"e": 1675,
"s": 1627,
"text": "Specify Custom Actions for different Exceptions"
},
{
"code": null,
"e": 1810,
"s": 1675,
"text": "In order to specify custom actions in such cases, programmers usually put multiple catch statements, such as in the following example:"
},
{
"code": "// A sample Java code with one try block// having multiple catch blocks to catch// different exceptions // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array y[x] = 10; } catch (ArithmeticException e) { System.out.println(\"Dividing by 0\"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(\"That index doesn't exist\"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}",
"e": 2669,
"s": 1810,
"text": null
},
{
"code": null,
"e": 2677,
"s": 2669,
"text": "Output:"
},
{
"code": null,
"e": 2797,
"s": 2677,
"text": "a) In case of ArithmeticException: Dividing by 0\nb) In case of ArrayIndexOutOfBoundsException: That index doesn't exist"
},
{
"code": null,
"e": 2862,
"s": 2797,
"text": "Specify Custom Actions for different Exceptions using instanceof"
},
{
"code": null,
"e": 3121,
"s": 2862,
"text": "However, there is a way to do the same thing by using only one catch block. To do so, java provides an operator: instanceof.By using this operator, we can specify custom actions for the different exceptions that occur. The following program demonstrates how:"
},
{
"code": "// Java program to demonstrate the use of// instanceof to specify different actions for// different exceptions using only one catch block // importing class Random to generate a random number as inputimport java.util.Random;class A { void func(int n) { try { // this will throw ArithmeticException if n is 0 int x = 10 / n; int y[] = new int[n]; y[x] = 10; // this will throw ArrayIndexOutOfBoundsException // if the value of x surpasses // the highest index of this array System.out.println(\"No exception arose\"); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println(\"Can't divide by 0\"); if (e instanceof ArrayIndexOutOfBoundsException) System.out.println(\"This index doesn't exist in this array\"); } } public static void main(String a[]) { new A().func(new Random().nextInt(10)); }}",
"e": 4133,
"s": 3121,
"text": null
},
{
"code": null,
"e": 4141,
"s": 4133,
"text": "Output:"
},
{
"code": null,
"e": 4328,
"s": 4141,
"text": "a) In case of ArithmeticException: \nCan't divide by 0\nb) In case of ArrayIndexOutOfBoundsException: \nThis index doesn't exist in this array\nc) In case of no exception: No exception arose"
},
{
"code": null,
"e": 4902,
"s": 4328,
"text": "By using the instanceof operator in exception handling, it is easy to achieve the aforementioned objective and at the same time, it makes your code less complicated. One thing that has to be noted here is that as soon as the try block encounters an exception, the control will directly jump to the catch block, to handle, thereby, preventing the rest of the body of the try block from executing. As a result, even though there may be possibility of more than one exceptions occurring, the try block will only throw one exception, before shifting control to the catch block."
},
{
"code": null,
"e": 4926,
"s": 4902,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 4942,
"s": 4926,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4947,
"s": 4942,
"text": "Java"
},
{
"code": null,
"e": 4961,
"s": 4947,
"text": "Java Programs"
},
{
"code": null,
"e": 4966,
"s": 4961,
"text": "Java"
}
] |
Floating point error in Python
|
11 Nov, 2019
As it is know that 1.2 - 1.0 = 0.2 . But when you try to the same in python you will surprised by results:
>>> 1.2 - 1.0
Output:
0.199999999999999996
This can be considered as a bug in Python, but it is not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers. It’s a normal case encountered when handling floating-point numbers internally in a system. It’s a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.
We know similar cases in decimal math, there are many results that can’t be represented with a fixed number of decimal digits,Example
10 / 3 = 3.33333333.......
In this case, taking 1.2 as an example, the representation of 0.2 in binary is 0.00110011001100110011001100...... and so on.It is difficult to store this infinite decimal number internally. Normally a float object’s value is stored in binary floating-point with a fixed precision (typically 53 bits).
So we represent 1.2 internally as,
1.0011001100110011001100110011001100110011001100110011
Which is exactly equal to :
1.1999999999999999555910790149937383830547332763671875
Still, you thinking why python is not solving this issue, actually it has nothing to do with python. It happens because it is the way the underlying c platform handles floating-point numbers and ultimately with the inaccuracy, we’ll always have been writing down numbers as a string of fixed number of digits.
Note that this is in the very nature of binary floating-point: this is not a bug either in Python or C, and it is not a bug in your code either. You’ll see the same kind of behaviors in all languages that support our hardware’s floating-point arithmetic although some languages may not display the difference by default, or in all output modes). We have to consider this behavior when we do care about math problems with needs exact precisions or using it inside conditional statements.Check floating point section in python documentation for more such behaviours.
Compiler Design
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "As it is know that 1.2 - 1.0 = 0.2 . But when you try to the same in python you will surprised by results:"
},
{
"code": null,
"e": 176,
"s": 161,
"text": ">>> 1.2 - 1.0\n"
},
{
"code": null,
"e": 184,
"s": 176,
"text": "Output:"
},
{
"code": null,
"e": 205,
"s": 184,
"text": "0.199999999999999996"
},
{
"code": null,
"e": 744,
"s": 205,
"text": "This can be considered as a bug in Python, but it is not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers. It’s a normal case encountered when handling floating-point numbers internally in a system. It’s a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors."
},
{
"code": null,
"e": 878,
"s": 744,
"text": "We know similar cases in decimal math, there are many results that can’t be represented with a fixed number of decimal digits,Example"
},
{
"code": null,
"e": 905,
"s": 878,
"text": "10 / 3 = 3.33333333......."
},
{
"code": null,
"e": 1206,
"s": 905,
"text": "In this case, taking 1.2 as an example, the representation of 0.2 in binary is 0.00110011001100110011001100...... and so on.It is difficult to store this infinite decimal number internally. Normally a float object’s value is stored in binary floating-point with a fixed precision (typically 53 bits)."
},
{
"code": null,
"e": 1241,
"s": 1206,
"text": "So we represent 1.2 internally as,"
},
{
"code": null,
"e": 1298,
"s": 1241,
"text": "1.0011001100110011001100110011001100110011001100110011 "
},
{
"code": null,
"e": 1326,
"s": 1298,
"text": "Which is exactly equal to :"
},
{
"code": null,
"e": 1381,
"s": 1326,
"text": "1.1999999999999999555910790149937383830547332763671875"
},
{
"code": null,
"e": 1691,
"s": 1381,
"text": "Still, you thinking why python is not solving this issue, actually it has nothing to do with python. It happens because it is the way the underlying c platform handles floating-point numbers and ultimately with the inaccuracy, we’ll always have been writing down numbers as a string of fixed number of digits."
},
{
"code": null,
"e": 2256,
"s": 1691,
"text": "Note that this is in the very nature of binary floating-point: this is not a bug either in Python or C, and it is not a bug in your code either. You’ll see the same kind of behaviors in all languages that support our hardware’s floating-point arithmetic although some languages may not display the difference by default, or in all output modes). We have to consider this behavior when we do care about math problems with needs exact precisions or using it inside conditional statements.Check floating point section in python documentation for more such behaviours."
},
{
"code": null,
"e": 2272,
"s": 2256,
"text": "Compiler Design"
},
{
"code": null,
"e": 2279,
"s": 2272,
"text": "Python"
},
{
"code": null,
"e": 2377,
"s": 2279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2435,
"s": 2377,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 2468,
"s": 2435,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 2499,
"s": 2468,
"text": "Data flow analysis in Compiler"
},
{
"code": null,
"e": 2569,
"s": 2499,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 2609,
"s": 2569,
"text": "Runtime Environments in Compiler Design"
},
{
"code": null,
"e": 2637,
"s": 2609,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2687,
"s": 2637,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2709,
"s": 2687,
"text": "Python map() function"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.