Saturday, December 17, 2016

Get digit of an integer (int type) Java

  public int getDigit(int x){
    int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
    
    if(x < 0) x = Math.abs(x);
    
    for(int i = 0; ;i++){
      if(x < sizeTable[i])
        return i+1;
    }
  }

Wednesday, November 23, 2016

Changing '&amp; to '&' unless the '&' is used alone. (like &amp;laquo; --> &laquo; but &amp; is not changed to &)

I used the following SQL to change all "&amp;" to "&" except when "&amp;" is used just to express "&" alone. Because my website was showing "&laquo;" as "&amp;laquo;", which I don't like.

UPDATE `your_table`
SET `your_field` = REPLACE(`your_field`, '&amp;', '&')
WHERE `your_field` LIKE '%&amp;%' AND `your_field` NOT LIKE ' &amp; '

As a result:
&amp;laquo; --> &laquo;
&amp; --> &amp;

But please note, this doesn't work if a word to be replaced and a word to not be replaced are used in a same field at a same time. For example:
I &amp; my girlfriend went the zoo. See these pics &amp;raquo; http://www.blabla...
This has both of "&amp;" and "&amp;raquo;" in a same sentence, which means it mixedly has a word to be replaced and a word to not be replaced at a same time...So I guess "&amp;" would not replaced at all in this sentence.

Sunday, October 9, 2016

systemd and its "unit"

When the system is started, a unit called default.target is activated at first. The setting file for this unit is at a directory: /etc/systemd/system.

graphical.target is a unit which corresponds to runlevel 5. Although runlevel was used in SysVinit, units called target are used in systemd.

runlevel : target
0 : poweroff.target
1 : rescue.target
2, 3, 4 : multi-user.target
5 : graphical.target
6 : reboot.target

To manage services in systemd, "systemctl" command is used.

# systemctl [subcommand] [unit name] [-t unit type]

The followings are main sub command:
start: this starts a service.
stop: this stops a service.
restart: this restarts a service.
reload: reload (re-check) the setting of a service.
status: this is used to check the status of a service.
is-active: this checks if the service is active.
enable: when this is used to a service, the service is started automatically when the whole system starts.
disable: when this is used to a service, the service is NOT started automatically when the whole system starts.
list-unit-files: displays all units.
reboot: reboot the system.
poweroff: power off the system.


systemd

We have talked about SysVinit on
SysVinit
Run level
Set a default runlevel

But actually SysVinit is less popular than "systemd" recently. Now we will talk about systemd here and go through the features of systemd.

In a system which uses systemd, systemd process manages services instead of init process when the system is started. The following daemon[1] processes work together for the purpose.
systemd  : main process of systemd
systemd-journald  : this manages journals (logs)
systemd-logind  : this is a process to deal with log in
systemd-udevd  : this process detects devices dynamically
In systemd, a unit refers to any resource that the system knows how to operate on and manage. This is the primary object that the systemd tools know how to deal with. These resources are defined using configuration files called unit files.[2]

There are some types of unit like a unit to start some services or a unit to mount a file system. Unit's type can be seen by its extension. For example, "htttpd.service"  can be estimated to be a service to start httpd service (and it is really so).

main types of the unit:
service
device
mount
swap
target.
systemd can understand the system's dependence and order relationship unlike SysVinit[3]. systemd considers "in order to start service A, service B will be needed" and systemd starts services smartly. In the end, necessary time to start the whole system is much shorter than SysVinit.


[1] Daemon processes reside in memory and provice services.
[2] Cited from Understanding Systemd Units and Unit Files.
[3] SysVinit starts services just in order stated beforehand. So if some service doesn't work properly, SysVinit get stuck at the service and it might take a lot of time to start the whole services as a result.

Set a default runlevel

When Linux is started, "init" is started at first. And then the system is started at a runlevel stated at /etc/inittab. If you want to change the default runlevel, open "/etc/inittab".

And look for a sentence saying "Default runlevel. The runlevels used by RHS are." then change the following sentence:

id:3:initdefault:

to the following:

id:5:initdefault:
Then the default runlevel is changed to 5 from 3.


Run level

In Linux system, "Run level" provides necessary service (and don't provide unnecessary service) for each run level. For example, you can decide that GUI should be enabled for "run level 5" and also you can decide what service shouldn't be enable for run level 5.

Run level for Ubuntu Debian GNU/Linux
0: Halt
1: Single user mode
2: Multi user mode
3: Multi user mode
4: Multi user mode
5: Multi user mode
6: Re-start
S or s: Single user mode
Single user mode is a special mode which can be used by root users. Single user mode is used for special cases which normal users should not touch, like system maintenance, because normal users can't log in the single user mode.

To check the current run level, run level command is used.

# runlevel
N means Run level was not decided because it was just after system was started. After N, the run level became 2  and this is the current run level.

To change the run level, "init" command or "telinit" command is used. The following example changes the current run level to 1.

# init 1

While normal users are logged in, if you log in as a single user, those normal users become unable to do anything and get stuck. So normal users should be logged out before you log in as a single user. If you use "wall" command, you can send messages to certain user(s). "wall" displays the contents of file or, by default, its standard input, on the terminals of all currently logged in users.

$ wall << .
Hi guys. This system is going down to maintenance mode. Beware.
.


SysVinit

The flow chart to explain how Linux PC is started

PC gets powered on
BIOS/UEFI
Boot loader
Kernel
init or systemd

SysVinit (System Five Init) has been main stream for Unix OS so far. But recently, "systemd" is getting more popular for Linux to boot its system. Now the certificate LPIC requires both knowledge of systemd and SysVinit.

In Linux system, the process "init", which is firstly executed in the system, starts necessary services serially following the setting file locating at /etc/inittab. The flow will be as follows:

1, init reads /etc/inittab file.
2, init reads /etc/rc.sysinit script.
3, init executes /etc/rc script.
4, This /etc/rc script executes the scripts locating under /etc/rc<runlevel>.d

But in case your system is not using SysVinit, which was a main stream before, there might not be /etc/inittab file. Even if the file exists, if the system is not usnig SysVinit, the file etc/inittab can be blank.

SysVinit uses scripts locating under /etc/rc<runlevel>.d to start services needed for each runlevel. For example, /etc/rc3.d directory has script files used for runlevel 3. These can be seen by using the following command:

$ ls /etc/rc3.d

These scripts stored at /etc/rc3.d is used to start, for example, servers, system services, or to restart the PC. If you want to use httpd service for example, use a command as follows:

# /etc/init.d/httpd start

To stop the httpd, use a command as follows:

# /etc/init.d/httpd stop


shutdown command

Linux PC can be shut down by using "shutdown" command.

# shutdown

By using options, shutdown command is used for a variety of purposes.

  • -h  : shut down PC
  • -r   : Restart PC after shut down
  • -f   : fsck[1] is skipped when PC is re-started
  • -F  : fsck is forced when PC is re-started
  • -k  : Send warning messages as if the shutdown is real but PC isn't shutdown actually.
  • -c  : Cancel a pending shutdown. (This does not apply to "shutdown now", which does not wait before shutting down.)


The following command shutdowns PC in 15 minutes and sends a warning message saying "please prepare for the shutdown in 15 minutes." But you need to be root to perform this command.

# shutdown -h +15 "please prepare for the shutdown in 15 minutes."

If you just want to send warning messages as if the shutdown is real, use -k option. But you need to be root to perform this command also.

# shutdown -k now "please prepare for the shutdown."

The following command shuts down the PC at 22:00.

# shutdown -h 22:00

The following command restarts the PC immediately.

# shutdown -r now

Once shutdown command is executed, users can't log in the system since then until the system is actually shut down and get restarted. The closer the planned time to be shutdown becomes, the more the users get warning messages.

[1] Linux fsck utility is used to check and repair Linux filesystems


References
Computer Hope http://www.computerhope.com/unix/ushutdow.htm Visited on 9th October 2016

Tuesday, October 4, 2016

lspci and device information

Citation from wikipedia "device file"
In Unix-like operating systems, a device file orspecial file is an interface for a device driverthat appears in a file system as if it were an ordinary file. There are also special files inMS-DOSOS/2, and Microsoft Windows. They allow software to interact with a device driver using standard input/output system calls, which simplifies many tasks and unifies user-space I/O mechanisms.
Device files often provide simple interfaces to peripheral devices such as printers and serial ports, but they can also be used to access specific resources on those devices, such asdisk partitions. Finally, device files are useful for accessing system resources that have no connection with any actual device such asdata sinks and random number generators.

And... device information like PCI devices which Linux kernel is detecting can be seem by using lspci command:

$ lspci

The detail of lspci is:

Citation from https://linux.die.net/man/8/lspci
lspci is a utility for displaying information about PCI buses in the system and devices connected to them.

By default, it shows a brief list of devices. Use the options described below to request either a more verbose output or output intended for parsing by other programs.

If you are going to report bugs in PCI device drivers or in lspci itself, please include output of "lspci -vvx" or even better "lspci -vvxxx" (however, see below for possible caveats).

Some parts of the output, especially in the highly verbose modes, are probably intelligible only to experienced PCI hackers. For exact definitions of the fields, please consult either the PCI specifications or the header.h and/usr/include/linux/pci.h include files.

Access to some parts of the PCI configuration space is restricted to root on many operating systems, so the features of lspci available to normal users are limited. However, lspci tries its best to display as much as available and mark all other information with <access denied>text.

Options

Basic display modes

-m

Dump PCI device data in a backward-compatible machine readable form. See below for details.

-mm

Dump PCI device data in a machine readable form for easy parsing by scripts. See below for details.

-t

Show a tree-like diagram containing all buses, bridges, devices and connections between them.

Display options

-v

Be verbose and display detailed information about all devices.

-vv

Be very verbose and display more details. This level includes everything deemed useful.

-vvv

Be even more verbose and display everything we are able to parse, even if it doesn't look interesting at all (e.g., undefined memory regions).

Thursday, September 22, 2016

Many-worlds interpretation

Many-worlds interpretation is an interpretation of quantum mechanics that asserts the objective reality of the universal wavefunction and denies the actuality of wavefunction collapse.

Many-worlds interpretation says there are lots of worlds in reality. Here I will explain what many worlds interpretation is.

For example, suppose you are observing one electron which is inside a small box. If the box is as small as a sugar cube, this electron can be regarded as it is following the classical physics. But if the box is really small - almost as small as the electron's "orbit" or "orbital" - it is very difficult to determine where the electron is precisely.

Actually it's impossible to determine where the electron is in the orbit. Location of the electron is not determined until you open the small box and check the location of the electron (Only probability of where the electron is can be expected by calculation). When I say "the location is not determined," it is not really determined -  The electron exists just as "cloud of probability." [1][2] Thus electron's "orbit" is not really orbit anymore - this is the reason why it's called "orbital" in quantum physics.[3]

We can't expect where the electron really is before we open the box and check where the electron is. This is not because the theory is imperfect, on the contrary, the electron is really cloud of probability before being checked the state. The state of electron is described by wave function.

In many worlds interpretation, this wave function can be applied to the observer  (although in Copenhagen interpretation, you can't apply it to the observer). Our body consists of a lot of atoms and electrons which follow the physical rules. If we apply wave function to the body of the observer, state of the observer and the electron which is inside the small box should be uniquely determined.

If we apply wave function to the observer and the electron being inside the box, we will find that many states are existing simultaneously and every time we observe an object, branches of the state are spawned.


We suppose you would decide to go home from the laboratory if you find the electron at right side of the box, but decide to stay at the lab and keep studying there if you find the electron at left side of the box. Both of the states (or worlds) exist in reality. But you can perceive only one state out of the many states.


[1] Purdue university, Chemical Education Division Groups, http://chemed.chem.purdue.edu/genchem/history/schrodinger.html.
[2] "The life and death of stars", http://www.weinberg.northwestern.edu/web/faculty/, Weinberg college of arts and science.
[3] "What is the difference between an orbit and an orbital?", 2016, Quora, https://www.quora.com/What-is-the-difference-between-an-orbit-and-an-orbital

Reference
[1] Toshifumi Sakaguchi, http://quantum.la.coocan.jp/tutorial.html

Wave function

Citation from wikipedia:
For now, consider the simple case of a non-relativistic single particle, without spin, in one spatial dimension. More general cases are discussed below.

Position-space wave functionsEdit

The state of such a particle is completely described by its wave function,
\Psi (x,t)\,,
where x is position and t is time. This is acomplex-valued function of two real variablesx and t.
For one spinless particle in 1d, if the wave function is interpreted as a probability amplitude, the square modulus of the wave function, the positive real number
\left|\Psi (x,t)\right|^{2}={\Psi (x,t)}^{*}\Psi (x,t)=\rho (x,t),
is interpreted as the probability density that the particle is at x. The asterisk indicates thecomplex conjugate. If the particle's position ismeasured, its location cannot be determined from the wave function, but is described by aprobability distribution. The probability that its position x will be in the interval a ≤ x ≤ b is the integral of the density over this interval:
P_{a\leq x\leq b}(t)=\int \limits _{a}^{b}dx\,|\Psi (x,t)|^{2}
where t is the time at which the particle was measured. This leads to the normalization condition:
\int \limits _{-\infty }^{\infty }dx\,|\Psi (x,t)|^{2}=1\,,
because if the particle is measured, there is 100% probability that it will be somewhere.
For a given system, the set of all possible normalizable wave functions (at any given time) forms an abstract mathematical vector space, meaning that it is possible to add together different wave functions, and multiply wave functions by complex numbers (see vector space for details). Technically, because of the normalization condition, wave functions form a projective space rather than an ordinary vector space. This vector space is infinite-dimensional, because there is no finite set of functions which can be added together in various combinations to create every possible function. Also, it is a Hilbert space, because the inner product of two wave functions Î¨1 and Î¨2 can be defined as the complex number (at time t)[nb 1]
{\displaystyle (\Psi _{1},\Psi _{2})=\int \limits _{-\infty }^{\infty }dx\,\Psi _{1}^{*}(x,t)\Psi _{2}(x,t).}
More details are given below. Although the inner product of two wave functions is a complex number, the inner product of a wave function Î¨ with itself,
{\displaystyle (\Psi ,\Psi )=\|\Psi \|^{2}\,,}
is always a positive real number. The number||Ψ|| (not ||Ψ||2) is called the norm of the wave function Î¨, and is not the same as themodulus |Ψ|.
If (Ψ, Ψ) = 1, then Î¨ is normalized. If Î¨ is not normalized, then dividing by its norm gives the normalized function Î¨/||Ψ||. Two wave functions Î¨1 and Î¨2 are orthogonal if(Ψ1, Ψ2) = 0. If they are normalized andorthogonal, they are orthonormal. Orthogonality (hence also orthonormality) of wave functions is not a necessary condition wave functions must satisfy, but is instructive to consider since this guarantees linear independence of the functions. In a linear combination of orthogonal wave functions Î¨nwe have,
{\displaystyle \Psi =\sum _{n}a_{n}\Psi _{n}\,,\quad a_{n}={\frac {(\Psi _{n},\Psi )}{(\Psi _{n},\Psi _{n})}}}
If the wave functions Î¨n were nonorthogonal, the coefficients would be less simple to obtain.
In the Copenhagen interpretation, the modulus squared of the inner product (a complex number) gives a real number
{\displaystyle \left|(\Psi _{1},\Psi _{2})\right|^{2}=P\left(\Psi _{2}\rightarrow \Psi _{1}\right)\,,}
which, assuming both wave functions are normalized, is interpreted as the probability of the wave function Î¨2 "collapsing" to the new wave function Î¨1 upon measurement of an observable, whose eigenvalues are the possible results of the measurement, with Î¨1being an eigenvector of the resulting eigenvalue. This is the Born rule,[8] and is one of the fundamental postulates of quantum mechanics.
At a particular instant of time, all values of the wave function Î¨(xt) are components of a vector. There are uncountably infinitely many of them and integration is used in place of summation. In Bra–ket notation, this vector is written
{\displaystyle |\Psi (t)\rangle =\int dx\Psi (x,t)|x\rangle }
and is referred to as a "quantum state vector", or simply "quantum state".There are several advantages to understanding wave functions as representing elements of an abstract vector space:
  • All the powerful tools of linear algebra can be used to manipulate and understand wave functions. For example:
    • Linear algebra explains how a vector space can be given a basis, and then any vector in the vector space can be expressed in this basis. This explains the relationship between a wave function in position space and a wave function in momentum space, and suggests that there are other possibilities too.
    • Bra–ket notation can be used to manipulate wave functions.
  • The idea that quantum states are vectors in an abstract vector space is completely general in all aspects of quantum mechanics and quantum field theory, whereas the idea that quantum states are complex-valued "wave" functions of space is only true in certain situations.
The time parameter is often suppressed, and will be in the following. The x coordinate is a continuous index. The |x are the basis vectors, which are orthonormal so their inner product is a delta function;
{\displaystyle \langle x'|x\rangle =\delta (x'-x)}
thus
{\displaystyle \langle x'|\Psi \rangle =\int dx\Psi (x)\langle x'|x\rangle =\Psi (x')}
and
{\displaystyle |\Psi \rangle =\int dx|x\rangle \langle x|\Psi \rangle =\left(\int dx|x\rangle \langle x|\right)|\Psi \rangle }
which illuminates the identity operator
{\displaystyle I=\int dx|x\rangle \langle x|\,.}
Finding the identity operator in a basis allows the abstract state to be expressed explicitly in a basis, and more (the inner product between two state vectors, and other operators for observables, can be expressed in the basis).