вторник, 15 ноября 2011 г.

How to generate tags for any project for navigating in VIM?

$ ctags -R

среда, 9 ноября 2011 г.

How to install jdk 6 on Ubuntu 11.10

$ sudo add-apt-repository ppa:ferramroberto/java
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk sun-java6-plugin

вторник, 8 ноября 2011 г.

PostgreSQL cheatsheet

sudo apt-get install postgresql
# Install a pgadmin gui
$ sudo apt-get install pgadmin3

# Set a password to "postgres" database
\password postgres

# Create database
$ sudo -u postgres createdb mydb


# Create yourself a superuser database account
$ sudo -u postgres createuser --superuser $USER
$ sudo -u postgres psql

# Next change your password
$ psql
\password $USER


# Create a db with the same name as your login name
createdb $USER

# To create additional databases:
create database somedbname;


# To restart the server
$ sudo /etc/init.d/postgresql restart

# To show created table
\d tablename

# To show all tables
\d

# Quit
\q

# Help
\h AND \?

# Import sql from file
\i filename

# Show query buffer
\p

# Show databases
\l

# Show db permissions
\z








вторник, 1 ноября 2011 г.

Hot to install rescuetime Linux uploader in Ubuntu 11.10


1. Download rescuetime linux uploader from here
2. Extract archive and go to the location in terminal
Next:
$ python setup.py build
$ sudo python setup.py install

Next you should be able to start it with
$ rescuetime_linux_uploader
I prefer to add it to startup applications.

суббота, 29 октября 2011 г.

How to sync open tabs and search engines in Chrome

1) Visit chrome://flags/
2) Enable syncing search engines and open tabs
3) Go to chrome://settings/personal, click Advanced
4) Make sure the new options are selected
5) Use the same search engine shortcuts everywhere!

четверг, 20 октября 2011 г.

How to install hamster indicator for timetracking in Ubuntu Unity?

% sudo add-apt-repository ppa:albertomilone/hamster-indicator
% sudo apt-get update
% sudo apt-get install hamster-indicator
 
% gconftool-2 --set "/apps/hamster-indicator/show_label" --type bool "true"
% gconftool-2 --set "/apps/hamster-indicator/label_length" --type int "20"

# Optionl - icon glow
% gconftool-2 --set "/apps/hamster-indicator/icon_glow" --type bool "true"   
 
After that, add "hamster-indicator" to startup applications. 

понедельник, 10 октября 2011 г.

50 советов по экономии времени для пользователей Ubuntu

1. Укоротите время показа меню загрузки
Если вы сыты по горло ожиданием начала загрузки вашей любимой операционной системы, откройте в текстовом редакторе "/boot/grub/menu.lst", найдите строчку, начинающуюся со слова "timeout" и просто уменьшите число справа. Это число - количество секунд, в течение которых система меню будет ждать перед началом загрузки операционной системы по умолчанию (значения 0 и 1 не рекомендуются).

2. Отслеживайте производительность загрузки
Bootchart - одна из лучших утилит для проверки производительности системы. После установки и перезагрузки bootchart создаст комплексный график всего, что запускается и потребляет ресурсы во время загрузки вашей системы, и помещает изображения графика в директорию /var/log/bootgraph.

3. Ускорьте загрузку
Когда появится загрузочное меню (вы должны были нажать "Ecs"), выберите опции загрузки по умолчанию и нажмите "e". Переместите курсор на строчку, начинающуюся со слова "kernel", и снова нажмит "e". Сейчас вы редактируете параметры загрузки, и вам нужно нажать пробел и добавить слово "profile". Нажмите "Enter" и "b", чтобы загрузиться. Доступ к диску в процессе последовательной загрузки сейчас будет профилированным и она станет быстрее, чем раньше.

4. Урежьте нежелательные службы
Стандартная установленная Ubuntu отличается предусмотрительностью по отношению к фоновым службам. К примеру, утилиты для bluetooth будут работать, даже если у вас нет соответствующего оборудования. Отключите не нужные вам службы, открыв окно "Службы" (Services) в меню "Система"->"Администрирование" (System->Administration). Будьте внимательны и не отключите службы, которыми вы пользуетесь.

5. Отслеживайте использование процессора
Вы можете думать, что программы для мониторинга процессора - это чисто для гиков, пытающихся выжать ещё несколько лишних циклов из своих разогнанных процессоров. Но это не правда. Дискретный монитор процессора - лучший способ определить непредсказуемый процесс, который замедляет работу всей системы. Щёлкните правой кнопкой мыши на панели рабочего стола и выберите "Системный монитор" (System Monitor). Для KDE есть похожий апплет.

6. Управляйте процессами
Если вы определите процесс, который использует больше процессорных циклов, чем реально должен, вам нужно остановить его, чтобы высвободить эти циклы. Сохраните всю работу и запустите менеджер процессов Ubuntu. Это часть инструментария системного мониторинга, он может быть открыт через меню "Система"->"Администрирование" (System->Administration).

7. Будьте внимательны друг к другу
Если вы используете системный монитор для управления текущими задачами, вы могли бы заметить колонку "nice". "Nice" это обычно приоритет задачи, который ранжируется от -20 до 19. Если у вас выполняется "тяжёлая" для процессора задача, такая, как, например, трёхмерные вычисления, увеличение значения "nice" уменьшит её приоритет и поможет вашей системе быть более отзывчивой. (Здесь игра слов: nice - "отзывчивый", "внимательный" и responsive - "отзывчивый" - прим.пер.)
Рабочий стол GNOME

8. Включите автоматический вход в систему
Многие из нас являются единственными пользователями своих компьютеров, так что ввод имени пользователя и пароля каждый раз перед тем как попасть в систему выглядит бессмысленным. Вы можете настроить автоматический вход в систему для основного пользователя, выбрав "Окно входа" (Login Window) в меню "Система"->"Администрирование" (System->Adminisration). Переключитесь на страницу "Безопасность" (Security), включите "Автоматический вход" (Automatic Login) и выберите пользователя.

9. Упростите меню
Чем больше приложений вы устанавливаете, тем более громоздким становится меню запуска. Но вы можете включить в него наиболее часто используемые приложения, нажав правой кнопкой мыши на пиктограмму, которая прячет меню, и выбрав пункт "Редактировать меню" (Edit Menus). Появившееся приложение позволит вам включить или отключить пункты меню.

10. Удалите задержку перед появлением меню
Гуру HCI (Human-computer interaction, человеко-компьютерное взаимодействие - прим.пер.) настаивают на том, что между щелчком по меню и его появлением должна быть задержка, но если она вас раздражает, вы можете избавиться от неё. Откройте терминал и напечатайте "nano ~/.gtkrc-2.0", затем добавьте единственную строчку "gtk-menu-popup-delay=0", сохраните результат, нажав "Ecs" и "Y". После перезапуска приложения вы обнаружите, что меню работает ультрабыстро.

11. Добавьте больше рабочих столов
Рабочие столы - одна из лучших вещей в Linux: это прекрасный способ расположить ваши приложения в разных виртуальных экранах. По умолчанию Ubuntu устанавливает только два рабочих стола, но вы можете отрегулировать их количество, щёлкнув правой кнопкой мыши по переключателю рабочих столов в правом нижнем углу экрана и открыв окно "Настройки" (Preferences).

12. Используйте рабочие столы эффективнее
Используйте сочетание "Ctrl" и клавиши курсора "влево" или "вправо", чтобы переключаться между смежными рабочими столами. И если вы будете удерживать при этом "Shift", то активное окно также переместится на новый рабочий стол. Есть ещё один способ: нажмите правую кнопку мыши на верхней границе любого окна, чтобы открыть контекстное меню и из него выбрать, на какой рабочий стол передвинуть окно.

13. Не запускайте всё сразу
Среднестатистическая Ubuntu в начале работы запускает множество разных программ, включая системные службы. Вы можете удалить те из них, которые вам не нужны, в окне "Сеансы" (Sessions) в меню "Настройки" (Preferences). Если вы не используете, к примеру, поиск, выключите "Треккер" (Tracker). Другие возможные кандидаты на отключение - Bluetooth, Evolution Alarm Notifier и апплет Print Queue.

14. Запомните текущий сеанс
Ещё одной хорошей особенностью менеджера настроек является возможность сконфигурировать ваш компьютер так, чтобы он запомнил приложения, которые вы запускали перед выключением машины. Это отличный способ быстро погрузиться в свою рабочую среду. Чтобы сделать это, просто переключитесь на страницу "Параметры сеанса" (Session Options) и включите опцию "Автоматически запоминать" (Automatically Remember).

15. Тонкая настройка рабочего стола Gnome
Клавишные комбинации для приложений спрятаны в "гномовском" аналоге редактора реестра в Windows. Его вы можете запустить из командной строки, напечатав "gconf-editor". Но будьте осторожны: изменённые здесь настройки могут угробить весь рабочий стол. Если такое случится, восстановить его первоначальное состояние можно удалив директории .gconf и .gconfd в домашней директории.

16. Запускайте приложения с помощью клавиатурных комбинаций
Одной из настроек, спрятанных в Gconf, является возможность запускать приложения с помощью клавиатурных комбинаций. Перейдите в apps->metacity->key_binding_commands, дважды щёлкните по одной из строк "command_"и введите команду запуска приложения, которое вам нужно. Чтобы установить клавишу запуска, дважды щёлкните по той же строчке в apps->metacity->global_keybindings и нажмите клавишу. Удерживание комбинации Ctrl+Shift+Alt и этой клавиши запустит приложение.

17. Используйте индексированный поиск
Ubuntu поставляется с превосходными утилитами для поиска по содержанию файлов и электронных писем, но они по умолчанию отключены. В меню "Настройки" (Preferences) откройте окно "Поиск и индексирование" (Search and Indexing) и включите оба параметра - "индексирование" и "слежение". После того как ваши файлы будут проиндексированы, вы сможете искать по ним, используя утилиту Tracker Search Tool в меню "Приложения"->"Стандартные" (Applications->Accessories).

18. Переключитесь на более быстрый менеджер рабочего стола
Ubuntu по умолчанию использует рабочий стол Gnome, и это хорошее решение, потому что он мощен, функционален и популярен. Но он не модернизирован и не особенно рационален. Более быстрой альтернативой Gnome является XCFE - основа Xubuntu. Установить его вы можете через менеджер пакетов Synaptic, если поищете мета-пакет "xubuntu-desktop".
Рабочий стол KDE

19. Переключитесь на KDE
Если ни Gnome, ни XCFE не помогают вам увеличить производительность труда, попробуйте KDE. Это самая гибконастраиваемая графическая среда в Linux и часто отличается от других своим подходом к поиску и управлению файлами. В версии 4 чрезвычайно сильно улучшено окружение. KDE может быть установлен с помощью поиска "kubuntu-desktop" в Synaptic.

20. Настройте автоматический вход в систему в KDE
Если вы предпочитаете Kubuntu или рабочий стол KDE, то чтобы включить автоматический вход в систему, вам нужно использовать другую конфигурационную панель. Откройте приложение "Системные настройки KDE" (KDE's System Settings), перейдите на страницу "Дополнительно" и откройте "Менеджер учётных записей" (Login Manager). Введите пароль суперпользователя и переключитесь на страницу "Convenience". Отсюда вы можете выбрать пользователя для автоматического входа в систему.

21. Предварительно загрузите Konqueror
Если вы постоянно запускаете этот файловый и веб-браузер KDE, вы можете предварительно загрузить несколько его экземпляров, чтобы уменьшить время его запуска. Откройте окно "Настройки"->"Конфигурировать Konqueror" (Settings->Configure Konqueror) и перейдите на страницу "Производительность" (Performance). Увеличьте количество экземпляров с 1 до чего-нибудь вроде 4 или 5. Каждый экземпляр потребует дополнительной системной памяти, но зато каждый сеанс Konqueror будет запускаться почти мгновенно.

22. Используйте клавиатурные сокращения для Konqueror
Konqueror - это классный файловый и веб-браузер с множеством клавиатурных сокращений для продвинутых пользователей. Наше любимое - возможность использовать сокращения в адресной строке для он-лайн поиска. "Wp:linux" будет искать в "Википедии" слово "Linux", а "gg: linux" будет искать это слово в Google и Google Images.

ОБЩЕСИСТЕМНЫЕ НАСТРОЙКИ

23. Сделайте запуск OpenOffice.org быстрее
Стандартная конфигурация OpenOffice.org неудачна - из-за перестраховок: в ней 100 уровней команды "отменить" (undo), к примеру. Уменьшение этого числа уменьшит и количество используемой памяти. Соответствующие настройки можете найти в окне "Опции" (Options) на странице "Память" (Memory). Попробуйте уменьшить шаги отмены до 30.

24. Используйте панель быстрого запуска
И в Gnome, и в KDE вы можете перетаскивать приложения из меню запуска на рабочий стол и на панель инструментов. Быстрее получается щёлкнуть по этим пиктограммам для запуска наиболее используемых приложений, чем удерживать определённые клавиши.

25. Замените медленные предложения более быстрыми
В открытом ПО всегда есть альтернативные приложения - и это классно. Переключение на одно из них может чрезвычайно улучшить производительность вашей системы. Попробуйте использовать Abiword вместо OpenOffice.org Writer, Thunar вместо Nautilus и Opera вместо Firefox. Все они в целом совместимы друг с другом, но первые работают быстрее.

26. Стремительный запуск приложений
Если вы знаете название приложения или инструмента, с которым хотите поработать, то можете быстро запустить его, нажав Alt+F2. Эта комбинация вызовет отдельное окно с командной строкой, и в нём вы можете напечатать название приложения. Введите "firefox" - и появится его пиктограмма. Нажатие "Enter" запустит программу.

27. Сделайте снимок экрана
Чтобы сделать скриншот и сохранить его (с помощью появившегося диалогового окна), нажмите клавишу "Print". Возможность сделать скриншот в любой момент невероятно полезна. Например, для сохранения подробностей он-лайн заказа или наивысшего результата в Crack Attack. Нажатием клавиш Alt+Print вы сделаете скриншот текущего активного окна.

28. Перезапустите рабочий стол быстро
Время от времени вы можете обнаруживать, что ваш рабочий стол завис и использовать клавиатуру или мышь больше нельзя. К счастью, процесс рабочего стола полностью независим от остальной части операционной системы. Вы можете перезапустить рабочий стол, удерживая клавиши Ctrl+Alt+Backspace, но вместе с этим вы потеряете все несохранённые данные, так что будьте осторожны.

29. Переключитесь на консоль
Другой вариант действия в случае, если ваш рабочий стол "упал", это перейти в консоль. Нажатие комбинации Ctrl+Alt и F1-F6 переключит экран на одну из шести разных консолей. Отсюда вы можете войти в систему и попытаться убить создающий проблемы процесс, перед тем как снова переключиться на ваш рабочий стол (сделать это можно нажав Ctrl+Alt+F7).

30. Создайте отдельную домашнюю директорию
Когда вы соберётесь поставить Ubuntu на "свежий" компьютер, выберите в установщике ручную разбивку диска и создайте три разных раздела. Один нужен для корневой директории ("/") и должен быть размером где-то в 10-20Гб. Второй необходим для файла подкачки, его размер равен количеству установленной памяти. И наконец, третий раздел - это домашняя директория ("/home"), которая будет содержать все ваши личные файлы. Когда вы будете переустанавливать Ubuntu, снова выберите ручную разбивку диска и ваш раздел с домашней директорией не будет переформатирован и все ваши личные и конфигурационные файлы останутся в целости и сохранности.

31. Настройте карту Nvidia
С установленными проприетарными драйверами для Linux карты Nvidia обеспечивают исключительное трёх- и двухмерное ускорение. Чтобы точно отрегулировать оборудование Nvidia, установите приложение под названием "nvidia-settings": из него вы сможете редактировать настройки монитора, включать двойной экран и добавлять тень от курсора.

32. Найдите неиспользуемые большие файлы
Большие и разбросанные в беспорядке файлы могут замедлять работу вашего компьютера, так же как и работу приложений, читающих содержимое директории. Лучший инструмент для уплотнения и удаления неиспользуемых файлов, который мы нашли, называется Filelight. Чтобы показать, где находятся самые большие файлы, программа использует секторную диаграмму. Вы можете легко удалить директории с хламом из меню, вызываемого щелчком правой кнопкой мыши по диаграмме.

33. Включите вертикальную синхронизацию в Compiz
Compiz, приложение впечатляющих трёхмерны эффектов, может как пожирать ресурсы, так и служить инструментом для ускорения работы компьютера - это зависит от мощности вашего графического оборудования. Но после включения вертикальной синхронизации мы почти всегда получаем более быстрый отклик. Включить параметр можно на странице общих настроек в менеджере настроек Compiz (Compiz setting manager).

34. Некомпизный Compiz
С другой стороны, прекрасные эффекты, производимые Compiz, не могут быть названы действительно функциональными, хотя для некоторых они удобны в использовании. Вы можете высвободить огромную часть ресурсов системы, отключив эффекты рабочего стола на странице визуальных эффектов (Visual Effects) в окне "Настройки"->"Внешний вид" (Preferences->Appearance).

35. Вытащите пакеты с CD или DVD
Даже во времена проникающего всюду интернета время от времени вам нужно иметь возможность установить пакет без подключения к глобальной сети. К счастью, Synaptic может читать содержимое установочного диска Ubuntu и добавлять пакеты оттуда свою в базу для установки с этого носителя. Откройте "Источники ПО" (Software Sources) из меню "Администрирование" (Administration), перейдите на страницу "Третьестороннее ПО" (Third Party) и щёлкните по кнопке "Добавить CD-ROM" (Add CD-ROM).

36. Повысьте скорость загрузки с помощью Preload
Утилиту Preload вы можете установить с помощью менеджера пакетов Synaptic. Она будет работать в фоновом режиме и попытается угадать, какие библиотеки вы собираетесь использовать. Затем она загрузит их в память, так что ваши приложения станут запускаться быстрее. Эффект Preload, похоже, минимален в последних версиях Ubuntu, но утилиту стоит попробовать.

37. Используйте виртуальную машину
Если вы наслаждаетесь тем, что пробуете разные дистрибутивы, но их установка вызывает у вас отвращение, попробуйте использовать Virtual Box из официальных репозиториев Ubuntu. Приложение легко в использовании и позволяет устанавливать на вашем компьютере виртуальные версии почти всех дистрибутивов Linux (и даже Windows), которые работают практически на своих настоящих скоростях.

38. Загружайтесь в текстовый режим
Время от времени графическое окружение бывает ненужным, особенно если вы используете свою машину как сервер. Поэтому Ubuntu имеет версию под названием Server Edition. По умолчанию Server не имеет графического рабочего стола, но во всём остальном это всё тот же Ubuntu. Прекрасное решение для веб- или медиа-сервера.

39. Усыпите свою систему
Зачем ждать, пока система загрузится, если можно просто "разбудить" сессию? Это быстрее, чем загружаться с нуля, и вы можете продолжать работу с того места, где остановились. Однако всё зависит от вашего оборудования. Дайте компьютеру попытаться "заснуть", чтобы проверить, поддерживает ли он этот режим: щёлкните по кнопке "Выход" (Logout), и если появится опция "Спящий режим" (Hibernate), то он должен работать.

40. Подгоните ядро под себя
Если вы чувствуете себя достаточно уверенным (а мы никогда не порекомендовали бы это тому, у кого недостаточно набита рука), вы могли бы собрать собственное ядро. Это не так тяжело, как кажется, однако позволит вам добавить в ядро только те особенности и оборудование, которыми вы хотите пользоваться. Прекрасная пошаговая инструкция здесь: https://help.ubuntu.com/community/Kernel/Compile.
Командная строка

41. Попробуйте, это действительно неплохо
Командная строка - ваш настоящий друг. Открыв Тerminal из меню "Приложения"->"Стандартные" (Applications->Accessories) или Konsole в KDE, вы можете выполнять гораздо больше задач, нежели в GUI вашего рабочего стола. К примеру, чтобы скопировать директорию, напечатайте "cp -rf что куда"; переименуйте файл командой mv и отредактируйте текстовый файл, используя команду под названием nano.

42. Лёгкие консольные комбинации клавиш
Вы можете нажать Tab во время использования командной строки, чтобы автоматически дополнить названия команд и системные пути. Вы также можете перебирать команды, использовавшиеся вами ранее, а также пользоваться поиском (Ctrl+r), чтобы найти команды, начинающиеся с символов, которые вы введёте.

43. Замените тяжёлые графические приложения консольными аналогами
Для большинства графических приложений существуют консольные аналоги. Вы могли бы установить и пользоваться pine для чтения электронной почты и новостей, к примеру. Или попробовать веб-браузер lynx. Использовать wget или ncftp - для скачивания файлов. MC (сокращение от Midnight Commander) - это полноценный файловый менеджер. И все эти утилиты запускаются на компьютерах с практически любым количеством памяти и практически c любым процессором.

44. Создавайте образы CD или DVD
Вы можете создавать образы оптических носителей информации и большинства присоединённых устройств, используя одну-единственную консольную команду. Напечатайте "dd if=/dev/cdrom of=disk.iso bs=1024", чтобы сделать необработанную полную копию данных и записать её в файл disk.iso. Но вначале вам надо отмонтировать привод, напечатав "sudo umount /dev/cdrom".

45. Читайте образы дисков, не записывая их на болванки
Если вы скачали образ диска и хотите получить доступ к файлам на нём, не тратя оптический диск, вы можете создать из этого образа виртуальный диск, используя всего одну команду. Откройте терминал через меню "Стандартные" (Accessories). Напечатайте "sudo mkdir /mnt/image", далее - "sudo mount -o loop disk.iso /mnt/image". Теперь вы можете просматривать диск с помощью файл-браузера в директории /mnt/image.

46. Используйте команду screen
После того как вы привыкли к командной строке, время изучить одну из лучших команд - screen. Это консольный эквивалент виртуальных рабочих столов. Screen позволяет запускать несколько сессий сразу, так же как и "усыплять" и "пробуждать" сессии. Чтобы начать, напечатайте "screen", затем нажмите клавиши Ctrl+C, чтобы создать новую сессию. Ctrl+A и N или P будут переключать вас между активными сессиями. Команды Ctrl+A и Ctrl+D "отцепляют" от сессии, а "screen -r" возобновит её.

47. Имейте доступ к вашей машине с Ubuntu откуда угодно
Отличной особенностью консоли является то, что вы можете использовать её для безопасного доступа к своей машине через интернет, находясь где угодно. Инструмент для этого - нечто под названием "SSH" - безопасная оболочка. Установите с помощью Synaptic openssh-server. Для доступа к вашей учётной записи используйте утилиты putty (для Windows) и ssh (для Linux).

48. Перемещайте файлы между компьютерами быстро и безопасно
С установленным и запущенным SSH-сервером вы можете быстро и безопасно перемещать файлы на и с удалённого компьютера, используя команду sftp. Она работает по протоколу FTP и понимает команды put и get для перемещения файлов. Если вы предпочитаете графический интерфейс, мы рекомендуем использовать Filezilla под Windows или "sftp://" как протокол в KDE.

49. Избегайте sudo
Вы могли заменить, что почти каждую важную конфигурационную команду, которую вы вводите, необходимо предварять командой "sudo" и вашим паролем. Если вы вводите одну "sudo" за другой, это может обернуться настоящей головной болью. Чтобы избежать докучливой процедуры, напечатайте "sudo bash" - это заменит текущую оболочку новой - с полными администраторскими привилегиями.

50. Создайте учётную запись суперпользователя
Если вы заметили, что работа с администраторскими привилегиями занимает всё больше и больше времени, вы можете создать учётную запись суперпользователя. Просто напечатайте "sudo passwd root" и введите свой пароль, следом за ним - новый пароль для учётной записи суперпользователя. Теперь вы можете напечатать "sudo root" и войти в систему как суперпользователь. Но этот режим стоит использовать только для администрирования системы.

Источник

пятница, 30 сентября 2011 г.

Seven habbits of effective text editing by Bram Moolenaar

If you spend a lot of time typing plain text, writing programs or HTML, you can save much of that time by using a good editor and using it effectively. This paper will present guidelines and hints for doing your work more quickly and with fewer mistakes.
The open source text editor Vim (Vi IMproved) will be used here to present the ideas about effective editing, but they apply to other editors just as well. Choosing the right editor is actually the first step towards effective editing. The discussion about which editor is the best for you would take too much room and is avoided. If you don't know which editor to use or are dissatisfied with what you are currently using, give Vim a try; you won't be disappointed.
[Vim commands and options are printed in this font]

Part 1: edit a file

1. Move around quickly
Most time is spent reading, checking for errors and looking for the right place to work on, rather than inserting new text or changing it. Navigating through the text is done very often, thus you should learn how to do that quickly.
Quite often you will want to search for some text you know is there. Or look at all lines where a certain word or phrase is used. You could simply use the search command /pattern to find the text, but there are smarter ways:
  • If you see a specific word and want to search for other occurrences of the same word, use the * command. It will grab the word from under the cursor and search for the next one.
  • If you set the 'incsearch' option, Vim will show the first match for the pattern, while you are still typing it. This quickly shows a typo in the pattern.
  • If you set the 'hlsearch' option, Vim will highlight all matches for the pattern with a yellow background. This gives a quick overview of where the search command will take you. In program code it can show where a variable is used. You don't even have to move the cursor to see the matches.
In structured text there are even more possibilities to move around quickly. Vim has specific commands for programs in C (and similar languages like C++ and Java):
  • Use % to jump from an open brace to its matching closing brace. Or from a "#if" to the matching "#endif". Actually, % can jump to many different matching items. It is very useful to check if () and {} constructs are balanced properly.
  • Use [{ to jump back to the "{" at the start of the current code block.
  • Use gd to jump from the use of a variable to its local declaration.
There are many more, of course. The point is that you need to get to know these commands. You might object that you can't possibly learn all these commands - there are hundreds of different movement commands, some simple, some very clever - and it would take weeks of training to learn them all. Well, you don't need to; instead realize what your specific way of editing is, and learn only those commands that make your editing more effective.
There are three basic steps:
  1. While you are editing, keep an eye out for actions you repeat and/or spend quite a bit of time on.
  2. Find out if there is an editor command that will do this action quicker. Read the documentation, ask a friend, or look at how others do this.
  3. Train using the command. Do this until your fingers type it without thinking.
Let's use an example to show how it works:
  1. You find that when you are editing C program files, you often spend time looking for where a function is defined. You currently use the * command to search for other places where the function name appears, but end up going through a lot of matches for where the function is used instead of defined. You get the idea that there must be a way to do this faster.
  2. Looking through the quick reference you find a remark about jumping to tags. The documentation shows how this can be used to jump to a function definition, just what you were looking for!
  3. You experiment a bit with generating a tags file, using the ctags program that comes with Vim. You learn to use the CTRL-] command, and find you save lots of time using it. To make it easier, you add a few lines to your Makefile to automatically generate the tags file.
A couple of things to watch out for when you are using these three steps:
  • "I want to get the work done, I don't have time to look through the documentation to find some new command". If you think like this, you will get stuck in the stone age of computing. Some people use Notepad for everything, and then wonder why other people get their work done in half the time...
  • Don't overdo it. If you always try to find the perfect command for every little thing you do, your mind will have no time left to think about the work you were actually doing. Just pick out those actions that take more time than necessary, and train the commands until you don't need to think about it when using them. Then you can concentrate on the text.
In the following sections there will be suggestions for actions that most people have to deal with. You can use these as inspiration for using the three basic steps for your own work.
2. Don't type it twice
There is a limited set of words we type. And even a limited number of phrases and sentences. Especially in computer programs.  Obviously, you don't want to type the same thing twice.
Very often you will want to change one word into another. If this is to be done in the whole file, you can use the :s (substitute) command. If only a few locations needs changing, a quick method is to use the * command to find the next occurrence of the word and use cw to change the word. Then type n to find the next word and . (dot) to repeat the cw command.
The . command repeats the last change. A change, in this context, is inserting, deleting or replacing text. Being able to repeat this is a very powerful mechanism. If you organise your editing around it, many changes will become a matter of hitting just that . key. Watch out for making other changes in between, because it will replace the change that you were repeating. Instead you might want to mark the location with the m command, continue your repeated change and come back there later.
Some function and variable names can be awkward to type. Can you quickly type "XpmCreatePixmapFromData" without a typo and without looking it up? Vim has a completion mechanism that makes this a whole lot easier. It looks up words in the file you are editing, and also in #include'd files. You can type "XpmCr", then hit CTRL-N and Vim will expand it to "XpmCreatePixmapFromData" for you. Not only does this save quite a bit of typing, it also avoids making a typo and having to fix it later when the compiler gives you an error message.
When you are typing a phrase or sentence multiple times, there is an even quicker approach. Vim has a mechanism to record a macro. You type qa to start recording into register 'a'. Then you type your commands as usual and finally hit q again to stop recording. When you want to repeat the recorded commands you type @a. There are 26 registers available for this.
With recording you can repeat many different actions, not just inserting text. Keep this is mind when you know you are going to repeat something.
One thing to watch out for when recording is that the commands will be played back exactly as you typed them. When moving around you must keep in mind that the text you move over might be different when the command is repeated. Moving four characters left might work for the text where you are recording, but it might need to be five characters where you repeat the commands. It's often necessary to use commands to move over text objects (words, sentences) or move to a specific character.
When the commands you need to repeat are getting more complicated, typing them right at once is getting more difficult. Instead of recording them, you should then write a script or macro. This is very useful to make templates for parts of your code; for example, a function header. You can make this as clever as you like.
3. Fix it when it's wrong
It's normal to make errors while typing. Nobody can avoid it. The trick is to quickly spot and correct them. The editor should be able to help you with this. But you need to tell it what's wrong and what's right.
Very often you will make the same mistake again and again. Your fingers just don't do what you intended. This can be corrected with abbreviations. A few examples:
:abbr Lunix Linux
:abbr accross across
:abbr hte the
The words will be automatically corrected just after you typed them. The same mechanism can be used to type a long word with just a few characters. Especially useful for words that you find hard to type, and it avoids that you type them wrong. Examples:
:abbr pn penguin
:abbr MS Mandrake Software
However, these tend to expand to the full word when you don't want it, which makes it difficult when you really want to insert "MS" in your text. It is best to use short words that don't have a meaning of their own.
To find errors in your text Vim has a clever highlighting mechanism. This was actually meant to be used to do syntax highlighting of programs, but it can catch and highlight errors as well.
Syntax highlighting shows comments in colour. That doesn't sound like an important feature, but once you start using it you will find that it helps a lot. You can quickly spot text that should be a comment, but isn't highlighted as such (you probably forgot a comment marker).Or see a line of code highlighted as comment (you forgot to insert a "*/"). These are errors which are hard to spot in a B&W file and can waste a lot of time when trying to debug the code.
The syntax highlighting can also catch unbalanced braces. An unbalanced ")" is highlighted with a bright red background. You can use the % command to see how they match, and insert a "(" or ")" at the right position.
Other common mistakes are also quickly spotted, for example using "#included " instead of "#include ". You easily miss the mistake in B&W, but quickly spot that "include" is highlighted while "included" isn't.
A more complex example: for English text there is a long list of all words that are used. Any word not in this list could be an error. With a syntax file you can highlight all words that are not in the list. With a few extra macros you can add words to the wordlist, so that they are no longer flagged as an error. This works just as you would expect in a word processor. In Vim it is implemented with scripts and you can further tune it for your own use: for example, to only check the comments in a program for spelling errors.

Part 2: edit more files

4. A file seldom comes alone
People don't work on just one file. Mostly there are many related files, and you edit several after each other, or even several at the same time. You should be able to take advantage of your editor to make working with several files more efficient.
The previously mentioned tag mechanism also works for jumping between files. The usual approach is to generate a tags file for the whole project you are working on. You can then quickly jump between all files in the project to find the definitions of functions, structures, typedefs, etc. The time you save compared with manually searching is tremendous; creating a tags file is the first thing I do when browsing a program.
Another powerful mechanism is to find all occurrences of a name in a group of files, using the :grep command. Vim makes a list of all matches, and jumps to the first one. The :cn command takes you to each next match. This is very useful if you need to change the number of arguments in a function call.
Include files contain useful information. But finding the one that contains the declaration you need to see can take a lot of time. Vim knows about include files, and can search them for a word you are looking for. The most common action is to lookup the prototype of a function. Position the cursor on the name of the function in your file and type [I: Vim will show a list of all matches for the function name in included files. If you need to see more context, you can directly jump to the declaration. A similar command can be used to check if you did include the right header files.
In Vim you can split the text area in several parts to edit different files. Then you can compare the contents of two or more files and copy/paste text between them. There are many commands to open and close windows, jump between them, temporarily hide files, etc. Again you will have to use the three basic steps to select the set of commands you want to learn to use.
There are more uses of multiple windows. The preview-tag mechanism is a very good example. This opens a special preview window, while keeping the cursor in the file you are working on. The text in the preview window shows, for example, the function declaration for the function name that is under the cursor. If you move the cursor to another name and leave it there for a second, the preview window will show the definition of that name. It could also be the name of a structure or a function which is declared in an include file of your project.
5. Let's work together
An editor is for editing text. An e-mail program is for sending and receiving messages. An Operating System is for running programs. Each program has its own task and should be good at it. The power comes from having the programs work together.
A simple example: Select some structured text in a list and sort it: !sort. The external "sort" command is used to filter the text. Easy, isn't it? The sorting functionality could be included in the editor. But have a look at "man sort", it has a lot of options. And it's probably a nifty algorithm that does the sorting. Do you want to include all that in an editor? Also for other filter commands? It would grow huge.
It has always been the spirit of Unix to have separate programs that do their job well, and work together to perform a bigger task. Unfortunately, most editors don't work too well together with other programs - you can't replace the e-mail editor in Netscape with another one, for example. You end up using a crippled editor. Another tendency is to include all kinds of functionality inside the editor; Emacs is a good example of where this can end up. (Some call it an operating system that can also be used to edit text.)
Vim tries to integrate with other programs, but this is still a struggle. Currently it's possible to use Vim as the editor in MS-Developer Studio and Sniff. Some e-mail programs that support an external editor, like Mutt, can use Vim. Integration with Sun Workshop is being worked on. Generally this is an area that has to be improved in the near future. Only then will we get a system that's better than the sum of its parts.
6. Text is structured
You will often work with text that has some kind of structure, but different from what is supported by the available commands. Then you will have to fall back to the "building blocks" of the editor and create your own macros and scripts to work with this text. We are getting to the more complicated stuff here.
One of the simpler things is to speed up the edit-compile-fix cycle. Vim has the :make command, which starts your compilation, catches the errors it produces and lets you jump to the error locations to fix the problems. If you use a different compiler, the error messages will not be recognised. Instead of going back to the old "write it down" system, you should adjust the 'errorformat' option. This tells Vim what your errors look like and how to get the file name and line number out of them. It works for the complicated gcc error messages, thus you should be able to make it work for almost any compiler.
Sometimes adjusting to a type of file is just a matter of setting a few options or writing a few macros. For example, to jump around manual pages, you can write a macro that grabs the word under the cursor, clears the buffer and then reads the manual page for that word into the buffer. That's a simple and efficient way to lookup cross-references.
Using the three basic steps, you can work more effectively with any sort of structured file. Just think about the actions you want to do with the file, find the editor commands that do it and start using them. It's really as simple as it sounds. You just have to do it.

Part 3: sharpen the saw

7. Make it a habit
Learning to drive a car takes effort. Is that a reason to keep driving your bicycle? No, you realize you need to invest time to learn a skill. Text editing isn't different. You need to learn new commands and turn them into a habit.
On the other hand, you should not try to learn every command an editor offers. That would be a complete waste of time. Most people only need to learn 10 to 20 percent of the commands for their work. But it's a different set of commands for everybody. It requires that you lean back now and then, and wonder if there is some repetitive task that could be automated. If you do a task only once, and don't expect having to do it again, don't try to optimise it. But you probably realize you have been repeating something several times in the last hour. Then search the documentation for a command that can do it quicker. Or write a macro to do it.  When it's a larger task, like lining out a specific sort of text, you could look around in newsgroups or on the Internet to see if somebody already solved it for you.
The essential basic step is the last one. You can think of a repetitive task, find a nice solution for it and after the weekend you forgot how you did it. That doesn't work. You will have to repeat the solution until your fingers do it automatically. Only then will you reach the efficiency you need. Don't try to learn too many things at once. But doing a few at the same time will work well. For tricks you don't use often enough to get them in your fingers, you might want to write them down to be able to look them up later. Anyway, if you keep the goal in view, you will find ways to make your editing more and more effective.
One last remark to remind you of what happens when people ignore all the above: I still see people who spend half their day behind a VDU looking up at their screen, then down at two fingers, then up at the screen, etc. - and then wonder why they get so tired... Type with ten fingers! It's not just faster, it also is much less tiresome. Using a computer program for one hour each day, it only takes a couple of weeks to learn to touch-type.

Epilogue

The idea for the title comes from the successful book "The 7 habits of highly effective people" by Stephen R. Covey. I recommend it to everyone who wants to solve personal and professional problems (and who doesn't?). Although some of you will claim it came from the Dilbert book "Seven years of highly defective people" by Scott Adams (also recommended!). See http://iccf-holland.org/click1.html and go to "recommended books and CDs".

From here

вторник, 27 сентября 2011 г.

Midnight Commander shortcuts

Ctrl + r -- Refresh active panel
Ctrl + t -- Mark single file
Ctrl + x c -- Opens chmod dialog for marked file
Ctrl + x o -- Opens chown dialog for marked file
Alt + ? -- Opens search dialog
Ctrl-x a -- Open VFS list. If a ftp session times out, you can use this to free the open vfs so you can log in again.

Panel Functions
TAB -- Switch focus between left and right panel
Insert -- Marks or removes mark on file(s)
Alt + F1..F12 (opens dialog for F1..F12 menu)
Alt + g -- Marks first file or directory in active panel
Alt + r -- Marks middle file or directory in active panel
Alt + j -- Marks last file or directory in active panel
Alt + s -- Incremental search
Ctrl + / -- Look for filename given in last line of active panel (not whole screen), and jumps on first file
* (Asterisk) -- Marks removes marking for all files in active panel (not directories)
+ (Plus) -- Brings up the input box where it can be given regular expression. All files with names that fill condition(s) in regular expression will be marked.
\ (Backslash) -- Remove marking for more data (opposite to + )

Shell Functions
Alt + Enter -- Copies selected filename in command line
Ctrl + Shft + Enter -- Copies full path of selected file in the command line
Alt + H -- Shows command line history

Function Keys
F1 -- Help
F2 -- Opens user menu
F3 -- View selected file content
F4 -- Opens file in internal text editor
F5 -- Copies selected file. Default is to another panel, but it asks first.
F6 -- Moving file. Default is to another panel, but it asks first.
F7 -- Make directory.
F8 -- Delete file or directory.
F9 -- Opens main menu at the top of the screen.
F10 -- Ends current action; editor, viewer, dialog window or ends mc program.

воскресенье, 25 сентября 2011 г.

Hiw to diff local changes with remote revision with git ?


~/diff.py:
 
#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
 
 
 
$ chmod +x ~/diff.py 
$ git config --global diff.external ~/diff.py
$ git diff origin/master 


Git: comparing changes between commits

Comparing the differences in the whole project since last commit (or any other):

git diff HEAD~
you can also compare between current state and some older commits:
  • Two commits ago
git diff HEAD~2
  • Differences between two commits ago and three comits ago
git diff HEAD~2 HEAD~3
All of the above can be of course applied to a single unique file. For example:
git diff HEAD~2 HEAD~3 main.cpp
Instead of reference to head you can use a sha1 sum assigned to every commit or blob number or tags:
  • Single File or whole repo with a blob:
git diff d0403e0 9c20bb9 main.cpp
git diff d0403e0 9c20bb9
the same as can be done with sha1 hashes or tags.
Comparison can of course be done also in between branches.
git diff -b dev []
or even without -b parameter, comparing between state at current branch and the last commit of given one:
git diff []
In every situation instead of data change you can see what files really changed. This can be achieved with --name-only parameter passed to diff. For example, to see files changes between current state and last commit:
git diff HEAD~ --name-only
Sometimes you only have to check in which commits a single file has been changed, in that kind of situations "whatchanged" command can be very handy. It display in which commits a given file has been changed:
git whatchanged

Graphical diff/merge tools

Every of the above command will print the text diff acceptable by patch tool, but in case of very big diffs not very readable for humans. There is of course no problem to use any other diff tool of own kind. The command syntax remains the same except now we use difftool instead of diff, i.e.:
Launch graphical difftool meld and compare the contents of main.cpp between current state and last commit:
git difftool -t meld HEAD~ main.cpp
The same applies to merging, in those cases we use mergetool. The syntax is the same as above. For example, to merge data from file main.cpp on branch "dev" to current branch we use:
git mergetool -t meld dev main.cpp
This is not of course most convenient way. You can configure your favourite merge/diff tool (from the set which is currently supported by git, you can also add your own merge tool to git, but I wont cover this part) to be used as default by setting the merge.tool variable.:
git config --global merge.tool=meld
git config --global diff.tool=meld
From now on "meld" will be used as default diff/merge tool and theres no need to pass it with -t parameter to difftool/mergetool command.


пятница, 16 сентября 2011 г.

How to read a file line by line in C style?


#include < stdio.h >

int main ( void )
{
   static const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL ) {
      char line [ 128 ]; /* or other suitable maximum line size */

      while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         fputs ( line, stdout ); /* write the line */
      }
      fclose ( file );
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
   return 0;
}

Convert string to UPPERCASE


#include < string >
#include < stdio.h >
#include < ctype.h >

using namespace std;

void stoupper(string& s) {
    string::iterator i = s.begin();
    string::iterator end = s.end();

    while (i != end) {
        *i = toupper((unsigned char)*i);
        ++i;
    }
}

int main() {
    string str = "Some string";  
    stoupper(str);
}

Snippet for sorting map by values in C++

#include < algorithm >
#include < iostream >
#include < map >
#include < string >
#include < vector >

using namespace std;

typedef pair mypair;

struct IntCmp {
    bool operator()(const mypair &lhs, const mypair &rhs) {
        return lhs.second < rhs.second;
    }
};

int main() {
   map m;
   m["A"] = 5;
   m["B"] = 1;
   m["C"] = 2;
   m["D"] = 4;
   vector v(m.begin(), m.end());
   partial_sort(v.begin(), v.begin() + m.size() - 1, v.end(), IntCmp());

    for (int i = 0; i < m.size(); i++)  {
        cout << i << ": " << v[i].first << " --> " << v[i].second << "\n";
    }
}

четверг, 15 сентября 2011 г.

Snippet for splitting string in C++

#include < string >
#include < sstream >
#include < iostream >

using namespace std;

int main() {
    string s, word = "Hello world";

    stringstream ss(word);    

    while (getline(ss, s, ' ')) {
        cout << s << endl;
    }
}

Snippet for text file reading in C++

// reading a text file
#include < iostream >
#include < fstream >
#include < string >
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open()) {
    while (myfile.good()){
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

среда, 14 сентября 2011 г.

понедельник, 17 января 2011 г.

How to get and remove build dependencies in Ubuntu?

To get all dependencies, necessary for building we use
apt-get build-dep {packagename}
or
aptitude build-dep {packagename}
but how to remove it?
There is no built-in func for it, but I found an answer on launchpad :
sudo aptitude markauto $(apt-cache showsrc YOUR_APP_NAME | grep Build-Depends: | sed -e 's/Build-Depends:\|,\|([^)]*)//g')

Проблема c push в git

Недавно я столкнулся со следующей проблемой в git:
$ git stash
$ git checkout -b secbranch
$ git shash pop
$ git push

error: failed to push some refs to 'git@git.assembla.com:myspace.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again.  See the 'Note about
fast-forwards' section of 'git push --help' for details.

$ git push origin +HEAD:HEAD
И все заработало нормально.)

суббота, 15 января 2011 г.

How to install Django to Ubuntu 10.10 with installed LAMP

$sudo apt-get install python-django
$sudo apt-get install libapache2-mod-wsgi

now check django in python:
$python
import django

Must be

Python 2.5.2 (r252:60911, Jan  3 2011, 21:39:33)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django

else run
$export PYTHONPATH=$PYTHONPATH:/usr/lib/pymodules/python2.6/

mkdir ~/www/
vi django.wsgi

#!/usr/bin/env python

import os, sys

path = '/home/USER/www'
if path not in sys.path:
    sys.path.append(path)


os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' #point to settings.py file
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

django-admin startproject myproject
cd myproject
django-admin runapp myapp


cd /etc/apache2/conf.d/
sudo vi wsgi.conf

Listen 7080

      WSGIScriptAlias / /home/gennad/www/mysite/django.wsgi


ESC+:x

Now go to http://localhost:7080

воскресенье, 2 января 2011 г.

How to go to particular line in Emacs and Vim?

Emacs:
M-g-g [number]
Vim:
:[number]

Горячие клавиши BASH


CTRL-команды:
Ctrl + a - переход к началу строки
Ctrl + b - аналог стрелки влево  
Ctrl + c - отменить редактирование команды или прекратить работу  
Ctrl + d - аналог Delete. Если строка пустая - выход из shell
Ctrl + e - переход к концу строки
Ctrl + f - аналог стрелки вправо
Ctrl + g - выход из режима дополнения
Ctrl + h - аналог BackSpace
Ctrl + i - аналог Tab
Ctrl + k - удалить всё до конца строки
Ctrl + l - очистить экран (набранная строка и даже позиция курсора остаётся)
Ctrl + r -  поиск по истории набранных команд
Ctrl + R - поиск по истории набранных команд назад (это когда есть несколько вариантов и проскочили нужный)
Ctrl + t - поменять местами текущий символ с предыдущим
Ctrl + u - удалить всё до начала строки
Ctrl + v - преобразует следующую клавишу в её символьное отображение (Enter - ^M, Esc - ^[ и т.д.)
Ctrl + w - удалить от курсора до начала слова
Ctrl + x дважды - скачок между началом строки и текущей позицией курсора
Ctrl + x @ - Показывает возможные варианты дополнения доменного имени  
Ctrl + y - вставить из буфера (все удаляемое по горячим клавишам удаляется не просто так, а в буфер)
Ctrl + z - притормозить/остановить выполнение команды в фон
Ctrl + _ - отмена последнего изменения
ALT-команды
Alt + < - к первой команде в истории (вообще к самой первой в .bash_history) Alt + > - к последней команде в истории
Alt + ? - показать весь список вариантов дополнения (аналог 2Т - см. ниже)
Alt + * - вставить все возможные варианты дополнения
Alt + / - попытатся дополнить имя файла (из имеющихся в текущем каталоге)
Alt + . - вставить последний аргумент из предыдущей команды
Alt + b - влево на слово
Alt + c - сделать первую букву слова заглавной (и перейти к следующему слову)
Alt + d - удалить от текущей позиции до конца слова
Alt + f - вправо на слово
Alt + l - сделать первую букву слова строчной (и перейти к следующему слову)
Alt + n - искать по истории (но не сразу, а после полного ввода и нажатия Ентер)
Alt + p - искать по истории назад
Alt + r - очистить всю строку
Alt + t - поменять слова местами
Alt + u - сделать все буквы заглавными от текущей позиции до конца слова
Alt + BackSpace - Удалить от текущей позиции до начала слова
Esc-команды
Esc+d - удалить от курсора до конца слова
Esc+f - вправо на слово
Esc+b - влево на слово
Esc+t - поменять местами слова
Tab-команды
2T обозначает дважды нажатый Tab
2T - все доступные команды (это тоже все знают)
(string)2T - все доступные команды начинающиеся на string
/2T - все каталоги, включая скрытые. Для текущего надо набрать ./2Т
*2T - каталоги, кроме скрытых
~2T - все пользователи, присутствющие в /etc/passwd
~f2T - все пользователи, присутствющие в /etc/passwd, начинающиеся на f
$2T - все системные переменные
@2T - все записи в /etc/hosts
=2T - вывод наподобии ls или dir
Просто команды
!! - выполнить последнюю команду в истории
!abc - выполнить последнюю команду в истории, начинающуюся на abc
!a:p - напечатать последнюю команду в истории, начинающуюся на a
!n - выполнить n-ную команду в истории
!$ - посдедний аргумент последней команды
!^ - первый аргумент последней команды
^abc^xyz - заменить abc на xyz в последней команде и выполнить результат

How to run emacs in terminal in Ubuntu?


$emacs -nw


or


$alias emacs='emacs -nw'


or


$apt-get install emacs-snapshot-nox