J1N1Q

                Jimi Hendrix Experience (1966): 
                Learning by caching.

## PROBLEMS FOR TODAY

Problem 1. Need to test software with Google Chrome on miniPi.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Solution:

Google: install chrome on debian 9

  https://www.itzgeek.com/how-tos/linux/debian
  /simple-way-to-install-google-chrome-on-debian-9.html

Download the Google signing key and install it.

  # wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | \
    sudo apt-key add -

Set up Google Chrome repository.

  # echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list

Update repository index.

  # apt-get update

Install Google Chrome using the below command.

  # apt-get -y install google-chrome-stable
  
Removing Firefox

  # apt-get autoremove --purge firefox-esr

Problem 2. What is the meaning of the next sentence?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  "..from origin 'null' has been blocked by CORS policy"*
  
*)  https://stackoverflow.com/questions/41965066
    /access-to-image-from-origin-null-has-been-blocked-by-cors-policy

Recreating Problem.

  Google: 
  $ git clone https://github.com/mrdoob/three.js/
  cd examples/
  google-chrome index.html --> loader / kmz
  
Solution:
    
Google: CORS error

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served*.

*) https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Now CORS somehow (previous cases experiance) correlates with SOP (memorise unknown abbreviations using MEM, for me its **********)

In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number.* 

*) https://en.wikipedia.org/wiki/Same-origin_policy

Host this cloned filetree behind the DocumentRoot. Find minimal files set for the next examples

  build/ examples/

------------------------------------------------------------------------

J1H7U

        Задача: В одиночку убрать мусор от взорванного здания.
        Есть экскаватор, лопата, самосвал, рюкзак.
        Свалка в двадцати километрах от стройплощадки.
        Оплата сдельная. Срок окончания работы ограничен.

        Фильтр (экскаватор) + Скрипт (самосвал). Короче, как говорил
        Никлаус Вирт: Алгоритмы + структуры данных = программы.

## DIAGNOSIS FOR A DAEMON (LINUX/BSD III AND IV INTRO)
------------------------------------------------------

Filtreerime selleks, et leida.
 
   Hästi ettevalmistatud andmed: DB, SQL 
   Loetavad (tekstifailid) indekseeritud andmed: locate
   Tekstifailid: find, grep, regex.
  
Skript selleks, et mitte teha mitu korda sama asja.

   sh, awk, c ...
   
Фильтр для того, чтобы найти.
 
  Хорошо подготовленные данные: БД SQL
  Удобочитаемые индексированные данные: locate
  Текстовые файлы: find, grep, regex.
  
Скрипт для того, чтобы не делать много раз одно и то же.

  sh, awk, c ...
  

## WHAT ARE WE DEALING WITH?

  cat /etc/issue
  uname -a
  free
  df, du
  fstab, mount 
  dmesg | less

Where are log files?

  /var/log/...

Where are configuration files?

  /etc/...
  
Daemons

  # systemctl
  # service 
  # /etc/init.d/...

Proc

  # cat /proc/...
  
Network

  # ip a
  # ifconfig
  # route
  # resolv.conf
  
Search

Find files containing both of two or more patterns:

  $ for i in `grep -l 'patch' *.txt`; do grep -Hni 'diff' $i; done

Find files containing single pattern: 

  # find . -name '*.txt' -exec grep -H -B 5 -A 5 '()()' {} \;
  # find . -name '*.txt' -exec grep -H -B 5 -A 5 '()()' {} +
  
  find -- search for ..
  .             -- starting from folder . (current folder)
  -name '*.txt' -- in all txt files
  -exec grep    -- start grep on each file found by 'find' command.
  -B 5          -- show 5 rows Before
  -A 5          -- show 5 rows After
  '()()'        -- pattern (regex) we are looking for
  {}            -- variable name containing item found by 'find' utility
  \             -- backslash, wormhole to bypass to extended alphabet
                   with special control symbols ( like ( ) { [ | + ? )
                   
  ;             -- terminator, 'exec' arguments are finished.
                   returns true only if command returns 0.
                    
  +             -- The result of the action always returns true.
  
  my_number % variants
  
Note: 0 variant must be defined.
 
find in given files (solved):

0. 'Σ' and '√' on the same line, sequense unknown (may be '√' and 'Σ') 

  $ find . -name '*.txt' -exec grep -Hni '\(Σ.\+√\)\|\(√.\+Σ\)' {} \;
  
1. punane (est) in italian

  $ find . -name '*.txt' -exec grep -Hni 'rosso' {} \;
  ./txt/i0QA5-DATA.txt:12:  FF0000   RED      PUnane       Красный      Rot        Rosso

2. Orwell

  $ find . -name '*.txt' -exec grep -Hni 'Orwell' {} \;
  ./txt/E2C8U(java4microcontrollers).txt:203: [4]. http://sourceforge.net/projects/orwelldevcpp/

3. kut and unkut on the same row (with some text between) 

  $ find . -name '*.txt' -exec grep -Hni 'kut.\+unkut' {} \;
  ./txt/H32B5-nanonotes.txt:3:                Kut -- Unkut

4. Tatjana

  $ find . -name '*.txt' -exec grep -Hni 'Tatjana' {} \;
  ./txt/i0QA5-DATA.txt:1397:Tatjana  Tiia  Triina  Tähte

5. bullshit

  $ find . -name '*.txt' -exec grep -Hni 'bullshit' {} \;
  ./txt/iBGAP-mySQLish.txt:4:                      Down on Bullshit Avenue{*}

Exercises:

  0. Files with all english vowels (separated by space) in one row.

  1. Find file that contain both names Anna AND Kirill

  2. Find files that contain surnames Kassel OR Пушкин

  3. Find files where words учебники and справочники are on the same row

  4. Find files where the words копипаст and autocomplete stand near (less than 5 lines) 


## НАСТРОЙКА АРАСHE ДЛЯ ПОКАЗА ОШИБОК СКРИПТОВ НА PHP В БРАУЗЕРЕ (DEBIAN STRETCH, RASPBIAN DESKTOP)
## KONFIGUREERIME APACHE NII, ET NÄIDATA PHP-SKRIPTI VIGU BRAUSERIS (DEBIAN STRETCH, RASPBIAN DESKTOP)

1. Otsime, millises failis saab muuta display_errors ja error_reporting
1. Ищем в каком файле можно изменить display_errors и error_reporting

  # find /etc -name '*.*' -type f \
    -exec grep -Hn '\(display_errors\|error_reporting\)' {} \;

  ...
  /etc/php/7.0/apache2/php.ini:446:error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
  ...
  /etc/php/7.0/apache2/php.ini:464:display_errors = Off

On näha, et see on fail /etc/php/7.0/apache2/php.ini. Read 446 ja 464 parandame nii (developer mode):
Видно, что этот файл /etc/php/7.0/apache2/php.ini. Cтроки 446 и 464 исправим так (developer mode):

  # nano /etc/php/7.0/apache2/php.ini

ALT+SHIFT+3 teeme nähtavaks reanumbrid:
ALT+SHIFT+3 включаем нумерацию строк:

  441 ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
  442 ; Development Value: E_ALL
  443 ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
  444 ; http://php.net/error-reporting
  445 ; error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
  446 error_reporting = E_ALL
  ...
  459 ; Default Value: On
  460 ; Development Value: On
  461 ; Production Value: Off
  462 ; http://php.net/display-errors
  463 ; display_errors = Off
  464 display_errors = On

Restart apache2.service: 
Перезапустим демон apache2:

  systemctl restart apache2:

DocumentRoot kaustas ( vaikimisi /var/www/html/) tuleb luua faili nimega phpinfo.php
В папке DocumentRoot ( по умолчанию /var/www/html/) создадим файл phpinfo.php

  # cat /var/www/html/phpinfo.php 
  <?php phpinfo(); ?>

Käivitame brauseris localhost/phpinfo.php lehekülg ning loeme 
Запустим в браузере страничку localhost/phpinfo.php и читаем

  ..
  display_errors            On        On
  display_startup_errors    Off       Off
  doc_root                  no value  no value
  docref_ext                no value  no value
  docref_root               no value  no value
  enable_dl                 Off       Off
  enable_post_data_reading  On        On
  error_append_string       no value  no value
  error_log                 no value  no value
  error_prepend_string      no value  no value
  error_reporting           32767     32767
  ..

Et mõista, mis on 32767, tuleb käivitada terminalis selline kood (php)
Чтобы понять, что такое 32767 запустим в терминале такой код (php)

  <?php
    print(PHP_EOL. 
          'E_ALL='.decbin(E_ALL).PHP_EOL.
          'E_NOTICE='.decbin(E_NOTICE).PHP_EOL.
          'E_DEPRECATED='.decbin(E_DEPRECATED).PHP_EOL.
          'E_STRICT='.decbin(E_STRICT).PHP_EOL);
  ?>

Edasi digitaaltehnika: maskid, loogilised toimingud, ülekanne ühest arvusüsteemist teise.
Дальше дигиталка: маски, логические операции, перевод из одной системы счисления в другую..

## LINKS

  1. How can I list all enabled services from systemctl?

    https://askubuntu.com/questions/795226
    /how-to-list-all-enabled-services-from-systemctl

  2. Redhat style (systemv)

    https://www.cyberciti.biz/faq
      /check-running-services-in-rhel-redhat-fedora-centoslinux/

  3. classics (/etc/init.d/..)

    https://unix.stackexchange.com/questions/108591
      /list-of-available-services
      
  4.  Õpikud, üleanded, veebikeelte kirjandus (vene)
      Учебники, задачники, справочники по web языкам (по русски)

    http://code.mu
    
     Regulaar avaldised
     Регулярки
     
    http://code.mu/tasks/php/regular
    /rabota-s-regulyarnymi-vyrazeniyami-v-php-glava-1.html
    http://code.mu/tasks/php/regular
    /rabota-s-regulyarnymi-vyrazeniyami-v-php-glava-2.html
    http://code.mu/tasks/php/regular
    /rabota-s-regulyarnymi-vyrazeniyami-v-php-glava-3.html
    http://code.mu/tasks/php/regular
    /rabota-s-regulyarnymi-vyrazeniyami-v-php-glava-4.html

## draft

How can I list all enabled services from systemctl?

  https://askubuntu.com/questions/795226
  /how-to-list-all-enabled-services-from-systemctl

This excellent question (and its answers) is an interesting example of how systemd violates the long-standing (and brilliant) design principles of Unix & Co.

  systemctl list-unit-files | grep enabled 
  
will list all enabled ones.

If you want which ones are currently running, you need

  systemctl list-unit-files --state=running

Use the one you're looking for. Enabled, doesn't mean it's running. And running doesn't mean it's enabled. They are two different things.

Enabled means the system will run the service on the next boot. So if you enable a service, you still need to manually start it, or reboot and it will start.

Running means it's actually running right now, but if it's not enabled, it won't restart when you reboot.
  
man systemctl states:

    --state=

    The argument should be a comma-separated list of unit LOAD, SUB, or ACTIVE states. When listing units, show only those in the specified states. Use --state=failed to show only failed units.

Explanation:

LOAD: Reflects whether the unit definition was properly loaded.

ACTIVE: The high-level unit activation state, i.e. generalization of SUB.

SUB: The low-level unit activation state, values depend on unit type.

Though you can also use this to only show enabled units with:

  systemctl list-unit-files --state=enabled

If a unit is enabled that means that the system will start it on startup. Though setting something to enabled doesn't actually also start it so you will need to do that manually, or reboot the system after setting it to enabled.

To list all the systemd service which are in state=active and sub=running

  systemctl list-units --type=service --state=running

To list all the systemd serice which are in state=active and sub either running or exited

  systemctl list-units --type=service --state=active

To see 'enabled' services including these that are still under upstart/init run:

  systemctl list-unit-files --type service --state enabled,generated

To see all of the currently running services run:

  systemctl list-units --type service --state running

------------------------------------------------------------------------

REDHAT

  https://www.cyberciti.biz/faq
    /check-running-services-in-rhel-redhat-fedora-centoslinux/
    
List running services using service command on a CentOS/RHEL 6.x or older

The syntax is as follows for CentOS/RHEL 6.x and older (pre systemd systems):

  service --status-all
  service --status-all | more
  service --status-all | grep ntpd
  service --status-all | less

Print the status of any service

To print the status of apache (httpd) service:

  service httpd status
  
List all known services (configured via SysV)

  chkconfig --list

List service and their open ports

  netstat -tulpn

Turn on / off service

  ntsysv
  chkconfig service off
  chkconfig service on
  chkconfig httpd off
  chkconfig ntpd on

To list systemd services on CentOS/RHEL 7.x+ use

The syntax is:

  systemctl
  systemctl | more
  systemctl | grep httpd
  systemctl list-units --type service
  systemctl list-units --type mount

To list all services:

  systemctl list-unit-files

------------------------------------------------------------------------

/etc/init.d/..

  https://unix.stackexchange.com/questions/108591
    /list-of-available-services

/etc/init.d contains scripts used by the System V init tools (SysVinit).

List executable:

  ls -F /etc/init.d/ | grep '*$'

..Since you are aware of chkconfig,service, and may be ntsysv,rcconf,

  https://unix.stackexchange.com/questions/82378
  /what-is-the-recommended-way-of-checking-running-services

  rcconf and ntsysv
  
------

## мысли..

Часто обновляемый текстовый файл с r/o доступом удобно просматривать

  Сhrome->refresh

---

Знание Математики это перевернутая 
пирамида стоящая на острие аксиом.
В начале 20-го века казалось интересным 
"спилить дерево у корня" -- (Рассел, Кантор)
Вот только после "операции" пирамида не рухнула, 
а ее рост даже ускорился. Почему?
(комментарий Линуксоида. То не пирамида а дерево --
 ну а корень (root) вверху, конечно же)

---

Главная опасность создания простого и самодостаточного 
учебника информатики -- это то, что он сможет стать
пригодным для обучения ботов.
