Раунд 2, бокс!

November 6, 2009

Я сегодня прошел аттестацию, и теперь являюсь аспирантом 2-го года обучения. Ура! На носу – публикация препринта по структуре сети ПНЦ, плюс работа над прошлогодними измерениями фона тепловых нейтронов (недавно обработали – получили офигительные результаты) и доработка динамики высокоширотной границы радиационного пояса Земли.

А еще у нас почти готов софт для анализа данных, которые приходят с “Татьяны-2″ (приборы ДУФИК и МТЕЛ). Сами данные пока идут ненадежно, с перебоями. В скором времени к ним добавятся данные с некоторых экспериментов на Метеор-М. А еще где-то через полгода полетит в общем-то уникальная штуковина – орбитальный радиотелескоп Радиоастрон. С ней я тоже работаю :-)


Татьяна-2

October 20, 2009

В октябре до нас пока результаты сеансов связи не долетали; отлаживаем софт на пяти подтрамвайных сеансах конца сентября.

Сегодня дошла информация, что на борту сбой с питанием; вроде отказали батареи, но точно ничего не могу сказать. Пока так.


Just for fun

October 1, 2009

Предлагаю развлечься: пойти в ресторан Eat & Talk, когда у них будет масса посетителей, и расставить по столам таблички с надписью “Когда я ем – я глух и нем!”


And not a moment too soon…

April 15, 2009

Over a year ago, I had a pretty interesting conversation with Richard Stallman, the founder of the Free Software Foundation. In this conversation, I asked him among other things about applicability of free software terms to web applications; while he initially resisted the idea, I managed to convince him that it was an issue of GPL being unsuitable for web applications as it was. And over a year since then he made a public statement (also reported on Slashdot in a complete agreement with my proposition… except that he never gives me the credit for bringing the problem to his attention and logically proving his previous attitude wrong. My inquiries on the subject were left without a reply.

So long, and thanks for all the fish, Richard! It’s disgusting to see one of the greatest programmers of our time to become just another politician: incompetent enough so he cannot even use a browser, shady enough so he plagiarizes ideas and doesn’t even drop a word about where he got them. Oh, and read the conversation itself if you have the time: you will surely find many interesting statements made by RMS that would lead many companies withdraw any financial support of FSF should they learn about them…


С днем космонавтики!

April 12, 2009

Всех космонавтов, операторов ЦУПа, сотрудников космодромов, ракетчиков, инженеров, программистов, и всех-всех-всех

С ПРАЗДНИКОМ!


Finding cursor position in a contenteditable div

January 6, 2009

Several days ago (last year, actually) I started researching the problem of implementing a browser-based rich text editor. Among other questions that need to be answered there is the following one: if we use a div element as the text editor or a text display widget (e.g. when capturing user input with a hidden textarea), how shall we track the current caret position?

As usual, there are two solutions: for Internet Explorer and everything else :-) Both involve installing keyup and click event handlers:

<div id="test" contenteditable="true" onclick="getCursorPos();" onkeyup="getCursorPos();">Lots of text for testing</div>

As a rule, cursor position and the current selection are tightly wired together: when nothing is selected, the current selection begins and ends at the cursor position. So, we retrieve the selection range (in the code below, we assume that there is only one selection range in the window. I leave proper handling of the situation where multiple selection ranges exist as an exercise for the reader).
Now, the actual findNode function depends on the method you build the text editor and on your algorithmic skills. When you use a single long text node which includes all the text in the editor, it will be different from the case when every character is a separate text node. Besides, you are welcome to use optimized search algorithms if you are going to work with large documents. The important part here is that the anchorNode property references the first character in the selection, and you will only need to find its index among the other characters [1]. An example findNode() function is given below.
The cursor position and the selection display some dexterity in their mutual dependency. The quirk is that when you click on a character, the cursor is sometimes positioned by different math than the selection’s anchor. For instance, the cursor is positioned before the character if you click on its left 50% and after the character if you click on its right 50%, while if it is included in the selection or not depends on its geometry or the percentages are merely different. So, in order to reflect this, we add the selection object’s anchorOffset (actually, the selection length in characters) [2] to the value returned by the findNode function.
To make things work for Internet Explorer, we have to rely on a proprietary undocumented possibility. It appears that the second Unicode character in the bookmark of the selection range contains the value we need plus 11. Currently, I don’t know the meaning of this number, and whether its exact value changes depending on circumstances and can be calculated somehow.

function getCursorPos() {
var cursorPos;
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
cursorPos =  findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode
) + selObj.anchorOffset;
/* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
alert(cursorPos);
}
else if (document.selection) {
var range = document.selection.createRange();
var bookmark = range.getBookmark();
/* FIXME the following works wrong when the document is longer than 65535 chars */
cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
alert(cursorPos);
}
}

function findNode(list, node) {
for (var i = 0; i < list.length; i++) {
if (list[i] == node) {
return i;
}
}
return -1;
}

Well, that’s all. Solution tested in Firefox 3, Opera 9, Google Chrome, Safari 3.1 and IE7.


Антошка, Антошка…

October 17, 2008

Позавчера вечером решили мы с Верой пообедать. Недалеко от нашего корпуса расположен батальон всевозможных киосков продовольственного назначения: хот-доги, слойки, шаурма, мороженое – в общем, фаст-фуд на любой вкус. Среди прочих ларьков затаилась и “Крошка-Картошка”.

Картофан печеный (с салатом), вид сбоку

Именно в ней и было решено отовариться с означенной целью. Были приобретены две порции картошки с салатами, плюс бутылочка кваса. Непосредственно по возвращении в лабораторию и вскрытии упаковки было установлено, что салаты, входящие в состав блюда, съедобными не являются т.к. по всей видимости просрочены и источают неприятное амбре. Дальнейших вариантов действий рассматривалось три: звонок в санэпиднадзор, донос лично тов.Онищенко, и попытка вернуть некондиционный товар с возвратом финансовых средств. По стечению обстоятельств был выбран именно третий вариант.

Подошли, включили мобильники на аудиозапись, поздоровались. Объяснили суть проблемы. Тетеньки в ларьке очень удивились, стали рассказывать, что у них холодильник и вообще строгий контроль качества, даже предложили обнюхать емкость с одним из салатов (естественно, уже перезаряженную новой порцией). Однако в конце концов поверили, что нам достался товар ненадлежащего качества, и оформили возврат.

Итог

  • Факт продажи испорченных овощей: -5 баллов кармы (далее БК)
  • Факт возврата денег после пятиминутного разговора (4:27, если быть точным): +15 БК

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

Будьте зорки и бдительны!


Enraging people

October 9, 2008

Сервис-центр – просто чудо. Сказали, что мастера сегодня нет и не будет, дали визитку с телефоном, который пока что “абонент не абонент”. Если не удастся за сегодня связаться и договориться с мастером, буду требовать возврата.

Да, а с отсутствующим в комплектации видеокабелем меня просто послали, сказав, что его там и не должно быть, и посоветовали почитать на сайте ещё раз. Что ж, тем проще будет оформлять возврат.


Irritating people

October 9, 2008

Продолжаем знакомиться с дефектами N82. Выяснилось, что корпус скрипит при нажатии на левую его часть. У меня вообще сложилось впечатление, что телефон хорошенько обо что-то приложили, прежде чем продать мне. Это объясняет и дребезжание динамика (где-то трещина есть), и люфт.

Плюс ко всему комплектация неполная: не хватает кабеля microUSB с выходом на телевизор. Хотя он мне нафиг не нужен, всё равно обидно. Сейчас поеду в сервис воевать.