Mar. 9th, 2010
а вот ещё джавный прикол
Mar. 9th, 2010 03:36 pmБеру строку (json), строю объект, потом обратно в строку превращаю - получается строка да не та. Меняет местами два атрибута. Если ещё раз применить - меняет обратно. Инверсия типа. Ну в принципе-то, теоретически-то, всё равно; но для тестов - pain in the ass.
Но откуда такая фигня? А вот откуда: это у меня джава-то маразматическая, 1.4 ME, там hashmap нету, а есть hashtable; но не уверен и насчёт hashmap уже. Короче, атрибуты сложены в hashtable, по именам. Т.к. hashtable, то номер слота определяется хашкодом атрибута (строка), по модулю размера. Первые два атрибута имеют одинаковый хашкод (по модулю размера таблицы, естественно). А так как каждый слот - (недавно изобретенный китайцами) linkedlist, то, понятное дело, добавляем в голову. А потом, когда листаем, то берём с головы ж. Ну и это, порядок меняется на обратный.
Ну как решить конкретно мою задачу понятно (инвариант должен быть инвариантен!), но в целом-то смешно, правда ведь!
Но откуда такая фигня? А вот откуда: это у меня джава-то маразматическая, 1.4 ME, там hashmap нету, а есть hashtable; но не уверен и насчёт hashmap уже. Короче, атрибуты сложены в hashtable, по именам. Т.к. hashtable, то номер слота определяется хашкодом атрибута (строка), по модулю размера. Первые два атрибута имеют одинаковый хашкод (по модулю размера таблицы, естественно). А так как каждый слот - (недавно изобретенный китайцами) linkedlist, то, понятное дело, добавляем в голову. А потом, когда листаем, то берём с головы ж. Ну и это, порядок меняется на обратный.
Ну как решить конкретно мою задачу понятно (инвариант должен быть инвариантен!), но в целом-то смешно, правда ведь!
за гранью реальности
Mar. 9th, 2010 03:57 pmСамое нереальное, наверное, явление, какое у меня бывало в жизни, случилось у нас вчера.
В пол-двенадцатого проснулись оттого, что в ванной горел, вполнакала, свет. Чтобы его привести в такое состояние, нужно выключатель вывести на почти среднее положение. Понятно, что сам он так не выползет; и тиристор не настолько безумен, чтобы в нижнем положении вдруг сам по себе... короче, горел свет.
Пошел, выключил. Легли спать. Раздался стук. На втором этаже.
И больше ничего не было, так что мы мирно заснули.
Но два же свидетеля.
В пол-двенадцатого проснулись оттого, что в ванной горел, вполнакала, свет. Чтобы его привести в такое состояние, нужно выключатель вывести на почти среднее положение. Понятно, что сам он так не выползет; и тиристор не настолько безумен, чтобы в нижнем положении вдруг сам по себе... короче, горел свет.
Пошел, выключил. Легли спать. Раздался стук. На втором этаже.
И больше ничего не было, так что мы мирно заснули.
Но два же свидетеля.
class OurTestCase
Mar. 9th, 2010 04:41 pmBeing tired of having to repeat all the small cheap unittesting gadgets here and there, introduced
OurTestCase extends TestCase
where I stuff all kinds of stuff, like, e.g., this:protected void assertJsonEquals(String message, String x, String y) { JSONObject jsonX = jsonFor(message, x); JSONObject jsonY = jsonFor(message, y); assertEquals(message, jsonX, jsonY); } private JSONObject jsonFor(String message, String x) throws AssertionFailedError { try { return new JSONObject(x); } catch (JSONException e) { throw new AssertionFailedError(message + ": bad json: " + e + "\n" + x); } } protected void assertEquals(JSONObject x, JSONObject y) { assertEquals("failed", x, y); } protected void assertEquals(String message, JSONObject x, JSONObject y) { assertNotNull(message, x); assertNotNull(message, y); if (x.equals(y)) return; for (Enumeration e = x.keys(); e.hasMoreElements();) { String key = e.nextElement().toString(); assertTrue(message + ": key " + key + " missing in " + y, y.has(key)); } for (Enumeration e = y.keys(); e.hasMoreElements();) { String key = e.nextElement().toString(); assertTrue(message + ": key " + key + " missing in " + x, x.has(key)); } for (Enumeration e = x.keys(); e.hasMoreElements();) { String key = e.nextElement().toString(); try { Object itemX = x.get(key); Object itemY = y.get(key); if (itemX != itemY) { String newMessage = message + ".key=" + key; if (itemX instanceof JSONObject && itemY instanceof JSONObject) { assertEquals(newMessage, (JSONObject) itemX, (JSONObject) itemY); } else { assertEquals(newMessage, x.get(key), y.get(key)); } } } catch (JSONException ex) { fail(message + ": key=" + key + ": " + ex.getMessage()); } } }
и снова о христианских младенцах
Mar. 9th, 2010 05:01 pmsource
Кори, активистка из Олимпии, штат Вашингтон, закончила свою жизнь в в Газе под вражеским бульдозером.
Можно, конечно, вспомнить ребят из Москвы, из Тегерана, из Вильнюса.
Но репортаж немножко смущает своей противоречивостью.
"The army report, obtained by the Guardian in April 2003, said she "was struck as she stood behind a mound of earth that was created by an engineering vehicle operating in the area and she was hidden from the view of the vehicle's operator who continued with his work. Corrie was struck by dirt and a slab of concrete resulting in her death."" - ну это, знамо дело, израильская пропаганда.
Вот что пишут правильные очевидцы:
"The bulldozer drove toward Rachel slowly, gathering earth in its scoop as it went. She knelt there, she did not move. The bulldozer reached her and she began to stand up, climbing onto the mound of earth. She appeared to be looking into the cockpit. The bulldozer continued to push Rachel, so she slipped down the mound of earth, turning as she went. Her faced showed she was panicking and it was clear she was in danger of being overwhelmed. All the activists were screaming at the bulldozer to stop and gesturing to the crew about Rachel’s presence. We were in clear view as Rachel had been, they continued. They pushed Rachel, first beneath the scoop, then beneath the blade, then continued till her body was beneath the cockpit. They waited over her for a few seconds, before reversing. They reversed with the blade pressed down, so it scraped over her body a second time. Every second I believed they would stop but they never did."
Казалось бы, два раза прокатиться по комиссарскому телу гусеницами, что останется?
"I ran for an ambulance, she was gasping and her face was covered in blood from a gash cutting her face from lip to cheek. She was showing signs of brain hemorrhaging. She died in the ambulance a few minutes later of massive internal injuries. She was a brilliant, bright and amazing person, immensely brave and committed. She is gone and I cannot believe it."
А вот и правильное решение конфликта, предложенное видным активистом:
"Abu Hussein, a leading human rights lawyer in Israel, said there was evidence from witnesses that soldiers saw Corrie at the scene, with other activists, well before the incident and could have arrested or removed her from the area before there was any risk of her being killed."
Арестовать её надо было! Её не арестовали, вот она и погибла. Злобная израильская военщина не соизволила арестовать активистку, а вместо этого позволила ей погибнуть под бульдозером.
У меня есть предложение. Последовать совету Абу Хусейна, да и арестовать всех на хер. Дело ж мужик говорит. Его, кстати, самого то ли арестовали, то ли просто не выпускают - он почему-то возражает. Непонятно.
Кори, активистка из Олимпии, штат Вашингтон, закончила свою жизнь в в Газе под вражеским бульдозером.
Можно, конечно, вспомнить ребят из Москвы, из Тегерана, из Вильнюса.
Но репортаж немножко смущает своей противоречивостью.
"The army report, obtained by the Guardian in April 2003, said she "was struck as she stood behind a mound of earth that was created by an engineering vehicle operating in the area and she was hidden from the view of the vehicle's operator who continued with his work. Corrie was struck by dirt and a slab of concrete resulting in her death."" - ну это, знамо дело, израильская пропаганда.
Вот что пишут правильные очевидцы:
"The bulldozer drove toward Rachel slowly, gathering earth in its scoop as it went. She knelt there, she did not move. The bulldozer reached her and she began to stand up, climbing onto the mound of earth. She appeared to be looking into the cockpit. The bulldozer continued to push Rachel, so she slipped down the mound of earth, turning as she went. Her faced showed she was panicking and it was clear she was in danger of being overwhelmed. All the activists were screaming at the bulldozer to stop and gesturing to the crew about Rachel’s presence. We were in clear view as Rachel had been, they continued. They pushed Rachel, first beneath the scoop, then beneath the blade, then continued till her body was beneath the cockpit. They waited over her for a few seconds, before reversing. They reversed with the blade pressed down, so it scraped over her body a second time. Every second I believed they would stop but they never did."
Казалось бы, два раза прокатиться по комиссарскому телу гусеницами, что останется?
"I ran for an ambulance, she was gasping and her face was covered in blood from a gash cutting her face from lip to cheek. She was showing signs of brain hemorrhaging. She died in the ambulance a few minutes later of massive internal injuries. She was a brilliant, bright and amazing person, immensely brave and committed. She is gone and I cannot believe it."
А вот и правильное решение конфликта, предложенное видным активистом:
"Abu Hussein, a leading human rights lawyer in Israel, said there was evidence from witnesses that soldiers saw Corrie at the scene, with other activists, well before the incident and could have arrested or removed her from the area before there was any risk of her being killed."
Арестовать её надо было! Её не арестовали, вот она и погибла. Злобная израильская военщина не соизволила арестовать активистку, а вместо этого позволила ей погибнуть под бульдозером.
У меня есть предложение. Последовать совету Абу Хусейна, да и арестовать всех на хер. Дело ж мужик говорит. Его, кстати, самого то ли арестовали, то ли просто не выпускают - он почему-то возражает. Непонятно.
два вопроса в одном флаконе
Mar. 9th, 2010 06:17 pm1. А что, действительно бмв так уж хороши, что только тупые (типа меня) ездят на приусах, а настоящие мужчины на бмв рассекают да на саабах? Или это очередные глюки с зивана?
2. If we have x and y on 2d, it is called "position"; if we have x, y, x', y', what's the right name for these four, the coordinates in what I know as phase space? Any good name?
2. If we have x and y on 2d, it is called "position"; if we have x, y, x', y', what's the right name for these four, the coordinates in what I know as phase space? Any good name?