середу, 23 жовтня 2013 р.

Подсчёт символов в LibreOffice Writer

Макрос для подсчёта количества символов в текстовом редакторе:
REM  *****  BASIC  *****

Sub Main

' для Lemojoe:
' Имеется текст. Необходим вывод на информационной табличке статистических данных:
' количество знаков с пробелами, количество знаков без пробелов. Чтобы подсчет
' можно было произвести в любой момент работы над документом.

   Dim doc as object
   Dim controller as object
   Dim textviewcursor as object ' всякие объекты там... не важно
   Dim letters as String ' выделенная строка с текстом
   Dim gap as Integer ' число пробелов
   Dim cursign as String ' текущий значок
   dim break as Integer ' число переносов строк
   Dim i as Integer ' счетчик
   gap = 0
   break = 0

   ' получаем current document -> controller -> view cursor
   doc = ThisComponent
   controller = doc.getCurrentController()
   textviewcursor = controller.getViewCursor()


   letters = textviewcursor.getString ' забираем выделенный текст

   For i = 1 To Len(letters)

       cursign = Mid (letters, i, 1)

       If cursign = chr(32) Then ' Считаем пробелы
           gap = gap + 1 ' один да один - два

       ElseIf cursign = chr(10) Or cursign = chr(9)  Then ' Считаем переносы строк
           break = break + 1
       End If

   Next
   msgbox "Всего знаков: " & Len(letters) - break & chr(13) & "Знаков без пробелов: " & Len(letters) - gap - break

End Sub
 Спасибо, Рыбка Рио

понеділок, 21 жовтня 2013 р.

Некоторые настройки Xorg

В последнее время как-то изменился формат конфигурационных файлов Xorg. Точнее, не сам формат, а порядок расположения. Теперь части файла /etc/X11/[org.conf находятся в папке /etc/X/xorg.conf.d:

cat 10-evdev.conf
Section "InputClass"
        Identifier "evdev pointer catchall"
        MatchIsPointer "on"
        MatchDevicePath "/dev/input/event*"
        Driver "evdev"
EndSection

Section "InputClass"
        Identifier "evdev touchpad catchall"
        MatchIsTouchpad "on"
        MatchDevicePath "/dev/input/event*"
        Driver "evdev"
EndSection

Section "InputClass"
        Identifier "evdev tablet catchall"
        MatchIsTablet "on"
        MatchDevicePath "/dev/input/event*"
        Driver "evdev"
EndSection

Section "InputClass"
        Identifier "evdev touchscreen catchall"
        MatchIsTouchscreen "on"
        MatchDevicePath "/dev/input/event*"
        Driver "evdev"
EndSection
cat 20-keyboard.conf 
Section "InputClass"
    Identifier "evdev keyboard catchall"
    MatchIsKeyboard "on"
    MatchDevicePath "/dev/input/event*"
    Driver "evdev"
   
    Option "XkbLayout" "us,ua(winkeys),ru"
    Option "XkbOptions" "grp:ctrl_shift_toggle"
EndSection

cat 10-monitor.conf
Section "Screen"
    Identifier             "Screen0"
    Device                 "Intel GMA3600"              # for AOD270
    Monitor                "Monitor0"
EndSection

Section "Monitor"
    Identifier             "Monitor0"
    DisplaySize            221 130    # In millimeters # for AOD270
EndSection

cat 10-synaptics.conf
Section "InputClass"
        Identifier "touchpad"                            # for AOD270
        MatchIsTouchpad "on"                           # for AOD270
        MatchDevicePath "/dev/input/event*"   # for AOD270
        Driver "synaptics"                                 # for AOD270
        Option "TapButton1" "1"                        # for AOD270
        Option "VertEdgeScroll" "on"                 # for AOD270
EndSection

cat 50-device.conf
Section "Device"
    Identifier             "Intel GMA3600"              # for AOD270
    Driver                 "fbdev"                           # for AOD270
EndSection

пʼятницю, 18 жовтня 2013 р.

SSH-туннель из Windows-клиента

1) Установить SSH (напр., OpenSSH)
2) Создать пару ключей:
ssh-keygen -t rsa -f <username>
3) Скопировать публичный ключ на сервер
cp <username>.pub -> linux-server
3) Создать коммандный файл tunnel.cmd:
ssh -l <username> -L 1234:srv_destination:3389 linux-server
4) Запустить туннель:
start /b tunnel.cmd
5) Запустить клиентскую программку (напр. rdesktop)

четвер, 17 жовтня 2013 р.

1С-Предприятие 8.2 на Linux (gentoo)

1) Редактируем файл /etc/layman/layman.cfg
[overlays]
overlays: http://...
+             http://iglast.kh.ua/daks.hg.xml
2) Добавляем оверлей:
layman -a daks
3) Добавляем тег "1C" в файл /etc/make.conf:
USE="... 1C"
PORTDIR_OVERLAY="/var/lib/layman/daks"
4) копируем готовый ebild в ebild с нужным номером
cp -v ./xxx-yyy-ver-build1.ebuild ./xxx-yyy-ver-build2.ebuild
ebuild xxx-yyy-ver-build2.ebuild digest
5) Скачать дистрибутивные файлы deb в DISTDIR

Установка PostgreSQL для 1C

Рецепт установки PostgreSQL для работы с сервером 1С под Linux-ом:

1) Установим mercurial:
equo install dev-vcs/mercurial
или
emerge -av dev-vcs/mercurial
2) Добавляем репозиторий, который содержит оверлей daks в файл /etc/make.conf:
 PORTDIR_OVERLAY="/var/lib/daks-overlay"
3) Удаляем возможно существующий оверлей:
install -d /var/lib/daks-overlay
4) Устанавливаем оверлей:
cd /var/lib

hg clone https://code.google.com/p/daks-overlay

Вход по SSH без пароля

Как часто бывает, есть linux-станции, на которые достаточно часто заходишь, и пароль постоянно вводить напрягает. А ведь есть способ входа БЕЗ введения пароля. Запишу рецептик здесь, что бы не вспоминать мучительно долго.

1. Генерируем пару ключей для станции с которой будем ходить на другую станцию:
sergio@local-host$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sergio/.ssh/id_rsa):[Enter key]
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Pess enter key]
Your identification has been saved in /home/sergio/.ssh/id_rsa.
Your public key has been saved in /home/sergio/.ssh/id_rsa.pub.
The key fingerprint is:
33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9 sergio@local-host
2. Публичный ключ нужно снести в файл ~/.ssh/authorized_keys на станции-пациенте. Легче всего сделать воспользовавшись спец. утилитой ssh-copy-id:
sergio@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub [remote-user@]remote-host
sergio@remote-host's password:
Now try logging into the machine, with "ssh 'remote-host'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

Sabayon: обновление

Есть у меня девненько установленный linux Sabayon. Ставил его где-то в 2010. Сейчас появилась необходимость обновить его.

"Нахрапом", по-простому не получается :(

1. Обновление репозитаривев.
Старый список не доступен для обновления :(
sabayon root# equo update
>>  @@ Синхронизация репозитория ...
>>   # Sabayon Linux Official Repository
>>   # Repository URL: http://svn.sabayonlinux.org/entropy/standard/sabayonlinux.org/database/x86/5
>>   # Repository local path: /var/lib/entropy/client/database/x86/sabayonlinux.org/standard/x86/5
>>   # Repository API: 2
>>     Downloading repository ...
>>     Внимание: repository does not exist online.
>>     [F]: 0.0/0.0 kB <->   0% [>         ] => 0.0b/сек. : ЕТА: 0s
Все правильно -  домен за 2 года "ищез":
nslookup svn.sabayonlinux.org
Server:        8.8.8.8
Address:    8.8.8.8#53

** server can't find svn.sabayonlinux.org: NXDOMAIN
Хорошо, что "под рукой" есть точно такая же машинка с живым Сабайоном. Меняю старые сведения о репозитории на новые. В файле  /etc/entropy/repositories.conf отключаю старй репозиторий:
# Sabayon Linux Official Repository
#repository|sabayonlinux.org|Sabayon Linux Official Repository|http://svn.sabayonlinux.org/entropy|http://svn.sabayonlinux.org/entropy#bz2
#repository|sabayonlinux.org||http://mirrors.cs.wmich.edu/sabayon/entropy|
#repository|sabayonlinux.org||http://ftp.cc.uoc.gr/mirrors/linux/SabayonLinux/entropy|
#repository|sabayonlinux.org||http://mirror.dun.nu/sabayonlinux/entropy|
#repository|sabayonlinux.org||http://mirror.holland.sabayonlinux.org/entropy|
#repository|sabayonlinux.org||http://cross-lfs.sabayonlinux.org/entropy|
#repository|sabayonlinux.org||http://ftp.surfnet.nl/pub/os/Linux/distr/sabayonlinux/entropy|
#repository|sabayonlinux.org||http://na.mirror.garr.it/mirrors/sabayonlinux/entropy|
заменяю их строками с "живого" Сабайона:
# Sabayon Linux Official Repository
repository|sabayonlinux.org|Sabayon Linux Official Repository|http://cerberus.itti.ifce.edu.br/entropy|http://pkg.sabayon.org,sabayon.org
repository|sabayonlinux.org||http://riksun.riken.go.jp/pub/pub/Linux/sabayon/entropy|
repository|sabayonlinux.org||http://ftp.sh.cvut.cz/MIRRORS/sabayon/entropy|
repository|sabayonlinux.org||http://ftp2.cz.freebsd.org/pub/sabayon/entropy|
repository|sabayonlinux.org||http://debian.mirror.dkm.cz/sabayon/entropy|
repository|sabayonlinux.org||http://mirror.us.sabayon.org/sabayon/entropy|
repository|sabayonlinux.org||http://mirror.umoss.org/sabayonlinux/entropy|
repository|sabayonlinux.org||ftp://ftp.klid.dk/sabayonlinux/entropy|
repository|sabayonlinux.org||http://ftp.fsn.hu/pub/linux/distributions/sabayon/entropy|
repository|sabayonlinux.org||ftp://ftp.fsn.hu/pub/linux/distributions/sabayon/entropy|
repository|sabayonlinux.org||http://mirrors.cs.wmich.edu/sabayon/entropy|
repository|sabayonlinux.org||http://ftp.surfnet.nl/pub/os/Linux/distr/sabayonlinux/entropy|
repository|sabayonlinux.org||ftp://ftp.nluug.nl/pub/os/Linux/distr/sabayonlinux/entropy|
repository|sabayonlinux.org||http://ftp.cc.uoc.gr/mirrors/linux/SabayonLinux/entropy|
repository|sabayonlinux.org||http://mirror.dun.nu/sabayonlinux/entropy|
repository|sabayonlinux.org||http://ftp.rnl.ist.utl.pt/pub/sabayon ftp://ftp.rnl.ist.utl.pt/pub/sabayon|
repository|sabayonlinux.org||http://mirror.internode.on.net/pub/sabayonlinux/entropy|
repository|sabayonlinux.org||http://cross-lfs.sabayonlinux.org/entropy|
repository|sabayonlinux.org||http://na.mirror.garr.it/mirrors/sabayonlinux/entropy|
Теперь должен пройти equo update. Запускаю, - поехали!!
Всего пару секунд радостного настроения и -- на тебе :(
equo update
>>  @@ Синхронізація репозиторію ...
>>   # Sabayon Linux Official Repository
>>   # Repository URL: http://pkg.sabayon.org/standard/sabayonlinux.org/database/x86/5
>>   # Repository local path: /var/lib/entropy/client/database/x86/sabayonlinux.org/standard/x86/5
>>   # Repository API: 2
>>     Downloading repository ...
>>     Завантаження контрольної суми packages.db.dumplight.bz2.md5 ...
>>     packages.db.meta: ура, є!.
>>       << розпакований мета-файл: 00-sabayon.package.keywords
>>       << розпакований мета-файл: 00-sabayon.package.mask
>>       << розпакований мета-файл: 00-sabayon.package.unmask
>>       << розпакований мета-файл: 00-sabayon.package.use
>>       << розпакований мета-файл: eapi
>>       << розпакований мета-файл: make.conf
>>       << розпакований мета-файл: make.profile
>>       << розпакований мета-файл: packages.db.critical
>>       << розпакований мета-файл: packages.db.fallback_mirrors
>>       << розпакований мета-файл: packages.db.keywords
>>       << розпакований мета-файл: packages.db.lic_whitelist
>>       << розпакований мета-файл: packages.db.mask
>>       << розпакований мета-файл: packages.db.mirrors
>>       << розпакований мета-файл: packages.db.post_update.sh
>>       << розпакований мета-файл: packages.db.post_upgrade.sh
>>       << розпакований мета-файл: packages.db.restricted
>>       << розпакований мета-файл: packages.db.revision
>>       << розпакований мета-файл: packages.db.system_mask
>>       << розпакований мета-файл: packages.db.webservices
>>       << розпакований мета-файл: parent
>>       << розпакований мета-файл: signature.asc
>>     packages.db.meta.asc: ура, є!.
>>     notice.rss: ура, є!.
>>     Перевірка репозиторію: 2814
>>     Downloaded repository status: Гаразд
>>     GPG key already installed for: sabayonlinux.org
>>     Make sure to verify the imported key and set an appropriate trust level:
>>     $ gpg --homedir '/etc/entropy/client-gpg-keys' --edit-key '6EF0055F8538092B13B449EC691428D9EE88C3A7'
>>     @@ Verified GPG signature of: packages.db.meta
>>     @@ Verified GPG signature of: packages.db.dumplight.bz2
>>     Розпакування бази даних у packages.db.dumplight ...
>>     Додається обсяг завантаженого packages.db.dumplight, зачекайте, будь-ласка ...
>>     Індексування мета-інформації репозиторію ...
>> Hi. My name is Bug Reporter. I am sorry to inform you that Equo crashed. Well, you know, shit happens.
>> Але при цьому Ви могли б дещо посприяти тому, щоб Equo став меншглючною програмою.
>> -- EVEN IF I DON'T WANT YOU TO SUBMIT THE SAME REPORT MULTIPLE TIMES --
Индексирование.... Ну, правильно, - формат баз, скорее всего, поменялся, а наш старенький equo ни сном, ни духом....

Пробую зайти с другой стороны. Так как Сабайон - бинарный дистрибутив на базе Gentoo, обновим пакеты "основного дистрибутива:
emerge --sync
>>> Starting rsync with rsync://88.198.51.10/gentoo-portage...
>>> Checking server timestamp ...
Welcome to swan.gentoo.org / rsync.gentoo.org
...
 
Ждем... Наконец-то.
По просьбам обновления делаю
emerge portage

!!! Your current profile is deprecated and not supported anymore.
!!! Use eselect profile to update your profile.
!!! Please upgrade to the following profile if possible:
        default/linux/x86/13.0/desktop
А... ну да:
ls -l /etc | grep make.profile
lrwxrwxrwx  1 root    root        54 бер 19  2010 make.profile -> ../usr/portage/profiles/default/linux/x86/10.0/desktop
lrwxrwxrwx  1 root    root        56 бер 30  2009 make.profile.entropy_old -> ../usr/portage/profiles/default-linux/x86/2007.0/desktop
Поправляю профиль:
mv /etc/make.profile /etc/make.profile.old;ln -s ../usr/portage/profiles/default/linux/x86/13.0/desktop /etc/make.profile
ls -l /etc | grep make.profile
lrwxrwxrwx  1 root    root        54 жов 17 11:07 make.profile -> ../usr/portage/profiles/default/linux/x86/13.0/desktop
lrwxrwxrwx  1 root    root        56 бер 30  2009 make.profile.entropy_old -> ../usr/portage/profiles/default-linux/x86/2007.0/desktop
lrwxrwxrwx  1 root    root        54 бер 19  2010 make.profile.old -> ../usr/portage/profiles/default/linux/x86/10.0/desktop
Повторно
time emerge portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '5': '/usr/portage/profiles/default/linux/x86/13.0/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
Рано :( Обновим пакеты с новым профилем:
emerge --sync
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '5': '/usr/portage/profiles/default/linux/x86/13.0/eapi'
>>> Starting rsync with rsync://209.177.148.226/gentoo-portage...
>>> Checking server timestamp ...
Welcome to magpie.gentoo.org / rsync.gentoo.org
emerge -uav portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '5': '/usr/portage/profiles/default/linux/x86/13.0/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
Опять никак :( Что же делать??
Попытка №3
mv /etc/make.profile /etc/make.profile.new; mv /etc/make.profile.old /etc/make.profile
emerge -av1 portage 
emerge: there are no ebuilds to satisfy "dev-lang/python:2.7".
(dependency required by "sys-apps/portage-2.2.7" [ebuild])
(dependency required by "portage" [argument])
Требует python-2.7.
Нашел подсказку
"Это значит что Вы давно не обновляли систему и версия портежей устарела настолько, что не умеет работать с EAPI 5. Отредактируйте файл, на который он ругается, вписав 4, вместо 5. Обновите портежи emerge portage, после этого верните значение 5."
Пробую:
emerge -av1 portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '5': '/usr/portage/profiles/default/linux/x86/13.0/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
mcedit /usr/portage/profiles/default/linux/x86/13.0/eapi
emerge -av1 portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '4': '/usr/portage/profiles/default/linux/x86/13.0/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
mcedit /usr/portage/profiles/default/linux/x86/13.0/eapi

emerge -av1 portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '5': '/usr/portage/profiles/eapi-5-files/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
mcedit /usr/portage/profiles/eapi-5-files/eapi

emerge -av1 portage
!!! Unable to parse profile: '/etc/make.profile'
!!! ParseError: Profile contains unsupported EAPI '4': '/usr/portage/profiles/eapi-5-files/eapi'
!!! If you have just changed your profile configuration, you should revert
!!! back to the previous configuration. Due to your current profile being
!!! invalid, allowed actions are limited to --help, --info, --sync, and
!!! --version.
mcedit /usr/portage/profiles/eapi-5-files/eapi
В результете, получилось, что нужно установить "3" вместо "5" в двух файлах.

После некоторых "экспериментов" с подстановками разных профилей пришёл к выводу, что для обновления portage крайне необходимы последние версии python:2.7 и python:3.2. Но они устанавливаются при EAPI=5. Выход следующий: "обмануть пакеты о требуемом EAPI, установить, переключиться на python:2.7, обновиться, снова установить с правильным EAPI:
mcedit /usr/portage/dev-lang/python/python-2.7.5-r3.ebuild mcedit /usr/portage/dev-lang/python/python-3.2.5-r3.ebuild
EAPI="4" меняем на EAPI="3"
cd /usr/portage/dev-lang/pythonebuild python-2.7.5-r3.ebuild digestebuild python-3.2.5-r3.ebuild digest
Далее устанавливаем:
emerge -av1 python:2.7 --nodeps
emerge -av1 python:3.2 --nodeps
Сразу же будет ошибка, что сумма не совпадает, - подмениваем суммы в Manifest.
После этих манипуляций python устанавливается. Далее
eselect python list
Available Python interpreters:
  [1]   python2.5
  [2]   python2.6 *
  [3]   python2.7
eselect python set 3
Питон установлен, теперь обновляемся, устанавливаем правильный portage и снова устанавливаем питоны:
emerge --sync
emerge -av1 python:2.7 --nodeps
emerge -av1 python:3.2 --nodeps
emerge -av1 portage
Всё, установлен нормальный portage.
Следующим шагом нужно обновить equo и entropy. Но, т.к. установленная система очень и очень старая обновить entropy с первого раза не удаётся:
emerge -av1 equo

 * IMPORTANT: 4 news items need reading for repository 'gentoo'.
 * Use eselect news to read news items.


These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] dev-python/python-exec-2.0-r1:2  PYTHON_TARGETS="(jython2_5) (jython2_7) (pypy2_0) (python2_6) (python2_7) (python3_2) (python3_3)" 79 kB
[ebuild     U  ] sys-apps/entropy-218::sabayon [0.99.50.2::sabayon] PYTHON_SINGLE_TARGET="python2_7%*" PYTHON_TARGETS="python2_7%*" 17,996 kB
[ebuild     U  ] app-admin/equo-218::sabayon [0.99.50.2::sabayon] USE="(-bash-completion%*)" PYTHON_SINGLE_TARGET="python2_7%*" PYTHON_TARGETS="python2_7%*" 0 kB

Total: 3 packages (2 upgrades, 1 new), Size of downloads: 18,075 kB

!!! Multiple package instances within a single package slot have been pulled
!!! into the dependency graph, resulting in a slot conflict:

sys-apps/entropy:0

  (sys-apps/entropy-218::sabayon, ebuild scheduled for merge) pulled in by
    ~sys-apps/entropy-218[python_targets_python2_7(-)?,python_single_target_python2_7(+)?] required by (app-admin/equo-218::sabayon, ebuild scheduled for merge)

Для "надёжности" удалим все три программы
emerge --unmerge sys-apps/entropy  app-admin/equo app-admin/sulfur
и установим equo и entropy "с нуля":
emerge -av  sys-apps/entropy  app-admin/equo
Наконец-то имеем полноценную equo для обновления системы!

Здесь должен был быть "хэппи энд", но, после вполне успешного "equo up", последующий "equo u" оставленный на ночь преподнёс массу сюрпризов :(. Спасает только то, что удалённая машинка не выключается, но браузеры уже не запускаются, equo работать не хочет и все программки требуют разные версии glibc ((.

Python 2.7 тоже не работает, "переключился" на python:2.6. Сборка любой программки подвисает на обработке gtkconfig (не помню), затем идут ошибки и, в конце, нехватка памяти :(.

Все, удаленную машинку перезагрузили и доступ утрачен :(