Artem's blog

July 24, 2008

Puzzle with weights

Filed under: Mathematics — Tags: — Artem @ 9:55 PM

The following is a programming task from my childhood:

Assume, we have a weight of integer value (say, X) and an infinite set of weights 1, 3, 9, 27, … Assuming that we have ideal pharmaceutical scales. The task is to balance weight X using set of weights, if we can put any amount of weights on any scale.

The solution is to factor X in 3-nary presentation:

X = x_0 * 1 + x_1 * 3 + x_2 * 9 + … + x_n * 3^n

where all x_i are in {0, 1, 2} (i.e. in mod3 ring in mathematical terminology).

Let’s use [y] notation for integer part of y.

Let’s assume that we put X on scale A and the second scale has name B. Let’s denote Y sum of all weights on A and Z as sum of all weights on B.

We denote Y = y_0 * 3^0 + y_1 * 3^1 + … + y_n * 3^n

At the beginning we have Y = X and Z = 0;

The idea is to go from 0 to n (and, possibly n+1) and do the following (*):

  • if x_i = 0 we are fine, do nothing;
  • if x_i = 1, put 3^i on scale B;
  • if x_i = 2, put 3^i on scale A and now Y = Y + 3^i, which is, actually makes y_i = 0 and y_(i+1) = y_(i+1) + 1;

Now let’s prove that X will be balanced by this algorithm in not more than [log_3(X)]+1 steps by induction:

[

1) if n = 0, X in {0, 1, 2} by (*) we have

ether 0 on all scales in 1 step

or 1 on both scales in 1 step

or {X, 1} on scale A and 3 on scale B in 2 steps;

2) let's assume that the proposition is correct for any k <= n, and we have log_3 X = n+1, so, assuming that we've already done n steps (added or did not added 1 on level n+1)

we have now 4 possible situations:

a) y_(n+1) in {0, 1} on step n and [step do not add 1 to y_(n+1);

b)  y_(n+1) = 2 on step n and [step do not add 1 to y_(n+1);

c)  y_(n+1) in {0, 1} on step n and [step adds 1 to y_(n+1);

d)  y_(n+1) = 2 on step n and [step adds 1 to y_(n+1);

I) in cases a) - c) on step n+ 1 we have y_(n+1) in {0, 1, 2} and y_k = 0 for all k > (n+1); by (*) and like in 1) we can complete balancing in not more than 2 steps, so having total (n+2) steps at maximum;

II) in case d) on step n+1 we have y_ (n+1) = 0 and y_(n+2) = 1 which can we balanced by putting 3^(n+2) on B, which adds 2 more steps casing finish in (n+2) steps.

We also pay attention, that for each n we put 3^n only on A if y_n = 2 or on B if y_n = 1 and nowhere if y_n = 0. So we do not need more than 1 weight with value 3^n for all n.

]

This proposition arise 1 interesting question: What is the least amount of weights k^n for all n do we need to balance any X on such scales?

First of all, let’s point our attention, that the question is trivial if the only place we can put our weights (except X) is B. In this case we have to have k-1 weights of each k^i weight which represents X in k-nary system.

We have 2 cases k is even and k is odd.

I) If k is odd that in k-nary system x_i will be in {0, … , k-1} where k-1 is even. In this case let’s prove we need (k-1)/2 weights.

For each i if we have y_i <= (k-1)/2, we put y_i weight on B. if y_i >= (k-1)/2  (**) we have z = k – y_i  <= (k-1)/2 (***) is the amount s.t. (y_i + z) mod k = 0 and (y_i + z) div k = 1.

It means that z is the amount we can put on A to have 0 there and shift 1 to the next level.  And we can not have amount of weights < (k-1)/2 since (**) and (***) can reach equality.

II) if k is even, k-1 is odd, let’s denote k-1 = 2l+1,  [(k-1)/2] = l weights is not enough since there is a middle value [(k-1)/2] + 1 = l+1which is strictly greater than [(k-1)/2] = l  and l is not enough to shift it to next level, since (l+1) + l = 2l + 1 = k-1 <k, but [(k-1)/2]+1 = l + 1 weight is enough, since, we can up on B amounts up to l + 1 and z = 2l – (l + 1) = l – 1 < l + 1, so we have enough amount of weights to shift to the next level. By the way, [(k-1)/2] + 1 = l + 1 = (2l + 2)/2 = k/2

To summarize, we have the following:

The least amount of k^i weights for each i to balance scales  is (k-1)/2 is k is odd and k/2 if k is even. Or, simply, [k/2]

In our proposition we had odd situation so we had (3-1)/2 = 1 weight enough to balance.

 

May 26, 2008

Mythical Great Developer

Filed under: Software — Tags: — Artem @ 12:05 AM

Nowadays a lot of guys are curious how to find “Great Developer” but, do not specify what do they mean by this words. How can we find something if we do not know what we are looking for? Let us at first find out is this instance exists. Probably, you are looking for a guy, who is:

  1. Knows everything on technologies she/he supposed to work with during her/his job at your company;
  2. Can create perfect easy-to-understand, scalable, maintainable architecture/code;
  3. Team player;
  4. Has nice leadership skills.

If you do, I can surely tell you that you are on the wrong way. Let me explain why.

  1. Usually, a regular human can not know every detail of every technology. Good professionals know key points and some details, not all. It means that it could make no sense to ask person for a particular details of that particular technology. Professionals usually know how to find this detail quickly, not all the details.
  2. I pointed my attention that roughly speaking all people could be divided into 3 categories:
    1. people with good memory but bad analytical skills and
    2. people who have good analytical skills and not very good memory
    3. people who have perfect analytical skills, perfect memory but do not care of your business, since whey could be perfect chess players and think about chess all the day instead of working on you
  3. On 2 I would say that usually code either easy to understand or scalable/maintainable, not both. So there are people, who writes first or second types of code.
  4. Next bad news is that usually person either hacker or team player. I knew 1 hacker on 1 project was so negative that it would be better that this guy just never participated at the project at all;
  5. And at the end leader persons are rarely good developers themselves;
  6. And now imagine of 2 hackers on the team hating each other!

We usually do not think about it when building our perfect team, yeah?

And there is even a theory called socionics that explains all types of characters and intertype relations.

Roughly speaking it tells us the next:

  • Person is either thinker of feeler, meaning either good abstract thinker or good team player;
  • Person is either sensing or intuitive type, meaning either stable worker and leader or gifted hacker, who can learn in seconds and do job better an faster than others;
  • Person either perceiving or judging meaning either strategist or tactician.

More of that, even hacker performs better if works with “bad worker” of appropriate type. And the whole team performs better if all members has non conflicting intertype relations. It is what Tom DeMarco and Timothy Lister were talking about in their peopleware than they told us about “unproductive” people on successful teams and on successful teams participating in selection of their colleagues. Does your team do it?

Even more, the Joel’s method of finding “Great Developers” on conferences could fail for Introverts, which would prefer writing code and learning new technology to participating on some conference.

But everything is not so bad. Some people advance their skills in areas they are not best in. So there is a chance you can find appropriate person or Guru. Don’t forget to ask person what area she or he is the best, what is easy and what she/he is working on.

Good luck in building your team!

 

May 25, 2008

Problems with outsourcing in software development

Filed under: Software — Tags: — Artem @ 9:09 PM

I actually was on the both sides. So I know how it looks like from inside and outside. I’m going to describe several problems, which you can, probably, face to, starting to work with some software development outsourcing.

1. Guys there think another way. They, probably, did not read peopleware and other books, you’ve read. They could be surprised by schedule you provide them or have in mind, but they could say nothing. Some that guys think that as they are pay hourly, it is not their problems to correct your schedule. You are lucky if have experienced team lead/PM on site to let you know about project risks. The usual rule applies: more expensive teams/companies/developers could cost you less overall.
Actually the main problem here is integration. Let me tell you about 2 projects I worked for. One from outsourcing side, and another from US side. On both projects US side wrote business logic and remote team wrote UI. If you do things this way you can be already in trouble of bad integration.

2. Remote guys sleep when on site team works and vice versa. If you are lucky, you can, probably, have an hour or two of overlapping time. It means that if one of the teams have a bug it will be fixed next day only, causing huge problems to another team. In worse case they could loose whole day.

3. If teams do not have common source repository it is another big issue. If some team do some refactoring it affects another team – other team’s code become uncompilable. Even bigger evil here is integration. On the second project I participated that way we had 2 guys on US side constantly working on integration tasks only, stating from second week of development, when we tried to integrate our code (!). On the similar project before we had only 3 guys on site doing UI, before the same task was transferred to outsourcing team. Can you imagine that? 3 guys did job here and after switching to outsourcing it were 2 guys doing integration tasks! On the first project bugs in business logic prevented UI developers from testing their code.

Okay, it is not always so bad, and sure, it make sense to have outsourcing in many cases.

Here is what you can do to have successful outsourcing:

1. If it is possible, let outsourcing do all parts of the job. That will save you from integration evil. Remember, that if you can’t let outsourcing do all parts of the task, integration is your biggest risk here;

2. Even if you were lucky with 1., make all your teams to write unit tests and run continuous integration everyday or even more often in all teams. It will at least help your teams to prevent most of integration issues, and help them to find their bugs earlier;

3. If it is possible, all teams should store their code in the same source control system. This will help teams to do successful refactoring, even changing other team’s code. To let it work better all teams should try to commit code before end of day, to let remote team successfully refactor. If it is not possible, new code from remote team should be committed to local repository daily;

4. Make business logic team to write all interfaces and mockups before writing actual code. The actual code could take much time, since interfaces and mockups are easy. It will also help your teams to write unit tests and to set up continuous integration tasks early.

Hope it will help you to choose right way and good luck with outsourcing if you are going to use it!

 

April 27, 2008

Bushido of Software Development

Filed under: Software — Tags: , , , — Artem @ 3:07 PM

12 Must Have in Software Development 

Just a minimal simple set or rules and approaches, which, I believe, help projects to succeed. Most of software developers will say that it is something like ”must have” on your project and, of course, it is not complete set. Since each complete set is a process and you can always chose the most suitable process for you.

  1. Unit and integration testing full or most code coverage (of course, you don’t have to test your DTOs or VOs if they don’t have any business logic inside);
  2. Continuous integration. Running integration testing at least daily;
  3. All developers (of all sub-teams) on the project can communicate with each other directly (not only though representative person);
  4. Adequate number of developers on the project (not too small and not too much);
  5. Adequate volume of design documentation (again not too small and not too much);
  6. Design documentation must be readable, illustrative, brief, well-structured and clear; 
  7. Developers must have adequate hardware and software to develop software;
  8. Team must have at least one development server to have development version of software, DB, continuous integration there;
  9. Team must have mock-ups (separate DB) for continuous integration;
  10. Team must use source-control system, all sub-teams of the team must integrate with code in the source control at least daily;
  11. Team must have development infrastructure. Such as wiki, project management and bug-tracking software, etc.;
  12. Automate everything you can.

Unit and integration testing full or most code coverage

It will let developers be sure that their code is functioning OK. More of that, it let them to to check if some part is OK without re-testing whole application.

Continuous integration

Imagine, some developer changed behavior of her/his module and updated his unit tests. Her/his unit tests works fine, but some other, dependent part could be broken.
Continuous integration allows developers to know if there are hidden problems in their application.

All developers on the project can communicate with each other directly

Don’t let absence of communication to become bottleneck of your process. If one developer has question and/or misunderstanding regarding some part of other developer’s work, communicating though contact person could delay delivery date of your project. Or even worse: communication person could transfer information incorrectly.

Adequate number of developers on the project

No need to tell you what happens if there not enough developers on the project. The surprising problem could happen if you took too many developers:
they will face all integration issues. Sometimes small teams could perform better than big ones. The one more issue about big teams is non-uniformity of the application
design. Not all developers have the same level and not all people have the same approaches.

Adequate volume of design documentation

It is simple. Nobody will read bad-structured huge design documents. On the other hands something should stay in-written to reflect common parts, possible misunderstandings,
etc.

Design documentation must be readable, illustrative, brief, well-structured and clear

If it not readable obviously nobody will read it. Non-illustrative documentation hard to process and developers could miss something. Why should it be brief is discussed in
previous section. In badly structured document hard to find information you need, so such documents become useless.

Developers must have adequate hardware and software to develop software

Just not fast enough hardware will simply delay your project. Do you need it? Usually the biggest expense is developers themselves. So it is very improvidently to spend
their time for waiting while program is compiled. The same idea is about software. Just let your developers work more effectively.

Team must have at least one development server to have development version of software, DB, continuous integration there

By word “server” you can understand some computer. They are not so expensive nowadays.

Team must have mock-ups (separate DB) for continuous integration

Don’t let changes in your development DB break your unit-testing. It is not such a big deal to maintain 1 more DB for testing.
Just let your developers play in development DB (or DB on their PCs) and put only what you need for testing to test DB.
Your continuous integration will hardly work well without it.

Team must use source-control system, all sub-teams of the team must integrate with code in the source control at least daily

I can’t imagine a project without source control. I’m sure everyone does the same. The issue can be, for example, if you have one team in
closed proprietary network (say, writing business logic) and one outside (say for presentation layer development). Sometimes both teams
can’t use the same source-control for various reasons, but at least in one of teams should integrate with others frequently (they can put
other team’s code in their source control. Even this process can usually be automated.).

Team must have development infrastructure. Such as wiki, project management and bug-tracking software, etc.

Don’t make your developers search their emails for some important information. Just set up wiki. Your developers are still write
their tasks on pieces of paper? How do you plan to manage it? Use software to develop software.

Automate everything you can

Compilation, deployment, integration with other source controls, sometimes even code-generation, etc. Usually you already have to do much for continuous integration. You can even chose dedicated person for this task if your team is big enough. Save costy time of your developers.

 

April 26, 2008

Misunderstanding of Agile development

Filed under: Software — Tags: — Artem @ 11:38 AM

Agile development is NOT:

  1. A mess-style development;
  2. Agile does not mean that you can write programs without any design documentation;
  3. When your developers have no access to business and business do not take part in the communication with the development team;
  4. Separating development sub-teams;
  5. Absence of continuous integration;
  6. Absence of unit-testing at all or even just some unit-testing instead of full coverage;

Unfortunately, sometimes you have to be negative to distinguish misinterpretations.

 

April 15, 2008

BMW 328i Convertible

Filed under: inRussian — Tags: , , — Artem @ 10:59 PM

Впечатления от катания на BMW 328i Convertible по солнечной Калифорнии

328Праздновал тут, намедни, свой день рождения в Калифорнии. Замечательный штат – тепло, светло и мухи не кусают.

Самое идеальное место для катания на кабриолетах и проч. буржуинских средствах передвижения. Вообще-то сначала я хотел взять Porshe Carrera S тоже кабриолетик, но оного в наличии не оказалось и небыло тогда когда я еще раз про него спрашивал. Живут же люди - кто-то продлил рент автомобиля еще на день. Т.е. еще на 500 местных зеленых бумажек.

Но я не пожалел, что взял этот кабриолет в прокат. Первое, что мне больше всего в нем понравилось это жесткая крыша, которая убирается нажатием кнопки. Т.е. не тот убогий брезент, который обычно рефлексирует под крышу а настоящая металлическая крыша вовсе даже не черного цвета :) Жутко удобно, практично и приятно. Тут тебе и кабриолет и купе в одном флаконе. И еще мне понравился сам процесс: жмешь кнопку и она поднимается. Очень волнующий зажгательно! :) Единственное, крышка не будет подниматься на ходу. Вот в каком состоянии вы с ней начали движение в таком она и останется, сколько не тереби волшебную кнопку. Я разок поднимал на перекрестке, чуть зеленый не пропустил, хотя подъехал на начало красного. Причем местные жители терпеливо ждали в очереди пока я поеду. Даже не побибикали :) Кстати, в случае когда крыша сложена от багажника остаются рожки да ножки :)

Теперь о насущном. Данные брал с американского сайта (http://www.bmwusa.com/Standard/Content/Vehicles/2008/3/328iConvertible/default.aspx), звиняйте, но судя по российскому сайту BMW такая модель в России не продается. Только чуть более мощная 330i, которая в свою очередь не продается в США. :) Судя по данным производителя машинка вполне себе шустренькая: разгоняет тушку до 100 (точнее до 60 миль в час) за 7.2 секунды на автоматической коробке передач. Такая же версия но купе разгоняется уже за 6.8 секунды за счет меньшего коэффициента сопротивления (0.28 против 0.30) и значительно меньшего веса (1540 против 1780). Хотя умельцы утверждают, что умеют разгонять этот болид еще быстрее. Кушает сие чудо природы всего лишь 13.3 по городу, 6.8 за городом и 9.2 в смешанном цикле (это данные для даже более мощной модельки 330 с российского сайта) почти как 14-я вазочка и меньше, чем Волга, несмотря на в 2 раза большую мощность! Хотя масса у них практически одинаковая. 

Ну а теперь о субъективном: Впечатления от вождения BMW описать словами (нематерными) практически невозможно. Сплошной восторг! По-началу я не прочухал, что автомат можно перевести в спортивный режим и довольствовался обычным, в котором машинка ведет себя достаточно стандартно (не считая отличного чувства дороги и руля). Но только стоит переключиться на спортивный режим, как сразу понимаешь, что такое BMW на самом деле и почему ее так все любят. На газ машинка начинает реагировать просто восхитительно. Ускорение напрямую зависимост от силы нажатия на педальку газа. Ощущение, как будто пересел в спортивный автомобиль. В сочетании с идеальными реакциями на руль, шикарными тормозами ничего кроме восторга не вызывает. Соверешенно непередаваемые ощущения я получил, катаясь по тому самому Mulholland Drive. Это такая дорожка по краю обрыва,Mulholland Drive где не знаешь (если, конечно же, там уже не ездил) насколько крут следующий поворот. Моим пассажирам, как они утверждают, было жутко. ;) К сожалению ниразу не переключил передачу с самостоятельно с руля (хотя переключатели там есть), т.к. автомат работает просто отлично. Странно, только почему БМВ-шники не сделали еще его быстрее ручной коробки как это сделали менее ленивые инженеры Porsche.

Кстати, если сравнивать эту машинку с предыдущей, про которую я писал (Pontiac Grand Prix) то большую мощность и больший крутящий момент ей удается развить на моторчике меньшего объема (3 против 3.8 литра), что внушает уважение немецким инженерам, хорошо умеющим превращать кубики в лошадки! :)

Цена же у буржуев как обычно почти в два раза ниже чем в России (от $43 200). Вот такая вот несправедливость. Хотя немцы ближе к россиянам, хотя бы географически. Кстати, тут отлично развита система лизинга и более мощную версию 335i с кучей опций (так что цена дотянет до 57 000) можно взять в лизинг на 3 года всего за 669 баксов в месяц. В России мне такое и не снилось. Все, что я мог себе позволить за такие же деньги это 3-ю мазду в кредит.

 

March 24, 2008

Pontiac Grand Prix и прочие американцы

Filed under: inRussian — Artem @ 9:16 PM

Ощущения от езды на американском автомобиле по американским же дорогам

Car

Волею судьбы приходится бороздить просторы техасщины на Pontiac Grand Prix. Это такой немаленький автомобильчик (см. фото). Другие кусочки машинки можно увидеть здесь. 3.8-литровый 6-ти горшковый 203-сильный движок разгоняет этот 1,5-тонный танк до 100 км/ч за 8,5 секунд. И не так прожорлив, как может показаться: 9,8л на 100 км в смешанном цикле. Тех. характеристики можно посмотреть тут. Для сравнения Волга 31105 разгоняет свои 1,5 тонны до сотни за 13,5 секунд при помощи 2,4-литрового 4-х горшкового движка, кушая при этом 9, а за городом 13,5 литров в городе на сотню.

Теперь о субъективщине.
Я как-то с детства привык ездить на машинках с механической коробкой передач. Ну, казалось бы, нет ничего проще, чем пересесть на автомат. Ан нет, с непривычки давил на тормоз левой ногой. Из-за чего начальник, имевший неосторожность не пристегнуться на заднем сиденье, долбанулся об переднее головой. 2 раза %). А я удивлялся, насколько чувствительные тормоза у машинки :) Хотя, они, собственно, такие и есть. Слишком чувствительные. Это очень неудобно, т.к. любое неосторожное нажатие приводит к тому, что машина просто резко встает. А резко тормозить у буржуев не принято. Они все тормозят очень плавно, что, безусловно, радует. Так что будь я конструктором, тормоза я бы приделал к этой машинке другие.

Теперь про газ (педальку, а не известный автозавод). Газ, прямо скажем, неадекватный. Просто не знаешь, что от него ожидать. С непривычки, иногда стартую с пробуксовкой, несмотря на то, что газ жму несильно. С другой стороны тормозной автомат понимает, что надо переключиться на пониженную только через несколько мнгновений после того, как утапливаешь педальку. Почему эти мнгновения иногда кажутся вечностью, я думаю, объяснять не надо :). Да и вообще, педалька, мягко говоря, неинформативная. Совершенно не чувствуешь адекватную отдачу и сложно дозировать нажатие. При езде по местным дорогам возникает ощущение, что тебя несет потоком. Обгонять не получается, т.к. во всех рядах едут с одинаковой скоростью даже на трассах %). Да и жутковато на таком корабле обгонять, 5 метров в длину все-таки. Хотя, наверное, на Porsche тут тоже было бы скучно ездить :/
Зато в машинке есть такая приятная фичка как круиз-контроль. Т.е. едешь, жмешь на кнопку и педаль газа можно отпустить – машинка будет сама поддерживать наебходимую скорость. В городе фичка бесполезная, а вот на трассе – достаточно приятная.
Кондиционер в машинке плюшевенький. Я, конечно, не избалован этим буржуйским изобретением, но впечатления достаточно грустные. Печка не печет, кондишен охлаждает так себе. Зато вентилятор работает практически бесшумно. И еще что мне понравилось, громкость музыки на штатной магнитолке увеличивается при увеличении скорости движения.

Вот что тут замечательное – это дороги. Это просто местная достопримечательность. Дело даже не в качестве покрытия (тут большинство дорог бетонные) а в том, что дороги хорошие ВЕЗДЕ! Даже в самой захудалой улочке в самом заныканном уголке города. Вот, что важно! Причем везде широкие дороги, несколько полос в каждую сторону, с газончиком и паребриком между направлениями движения. Ну а развязки там (см. фото) – вообще отдельная песня. Так что приезжайте к нам на техасщину – вместе попоем :)

Причем тут “прочие американцы”? А дороги-то кто делал. :))

 

Подробный рецепт солянки по-шагам

Filed under: inRussian — Tags: , , , — Artem @ 8:55 PM

Солянка по-Артемовски :)
Из расчета на большую кастрюлю:

Ингридиенты:

  1. Говядина, 1 цельный кусок > 0.5 кг;
  2. Колбасы (полукопченые, копченые, вареные), копчености, можно сосиски. Все вместе > 0.75 кг;
  3. Поллитровая банка хороших (крепких) соленых огурцов (с рассолом). Если соленых огурцов не нашли (есть только маринованные в уксусе), то рассол можно заменить небольшим количеством каперсов (2-3 чайные ложки). Уксус из под маринованных огурцов в суп добавлять нельзя – вкус супа будет полностью испорчен.
  4. Немного зеленых (можно черных) маслин (шт 6-8) без косточек;
  5. 1 лимон;
  6. 2 картофелины;
  7. 4 крупных луковицы;
  8. 2 морковки;
  9. Томатная паста;
  10. Подсолнечное масло для жарки;
  11. Сметана (обычно около 250г на кастрюлю, в зависимости от Вашего вкуса);
  12. Соль по вкусу;
  13. Черный перец молотый по вкусу;
  14. Грибы по вкусу;

Процесс:

  1. Моем говядину;
  2. Кладем говядину в кастрюлю одним цельным куском, туда же 2 луковицы (неразрезанные, целиком), туда же 2 морковки, заливаем полностью водой по края, чуть подсаливаем, ставим на огонь;
  3. Когда морковка готова, ее вытаскиваем. Мясо довариваем до полной готовности (обычно не менее часа);
  4. Когда мясо готово вытаскиваем мясо и лук из бульона (бульон НЕ сливаем, он – основа супа), вареные луковицы выкидываем(!);
  5. Мелко режем 2 луковицы, режем картошку маленькими кубиками (5мм х 5мм х 5мм);
  6. Берем сковородку, смазываем маслом, чтобы не пригорало, кладем нарезанные луковицы и ставим на огонь, слегка обжариваем добавляем туда картофель, распределяем его по всей сковородке, обжариваем картофель (необязательно до полной готовности);
  7. Нарезаем говядину, колбасы, копчености, сосиски и прочие мясопродукты, которые у нас есть, маленькими длинненькими параллелепипедиками (примерно 5мм х 3мм х 20мм), добавляем к картошке туда же дабавляем очень мелко нарезанную вареную морковку, при желании можно добавить чуть-чуть нарезанных грибочков и обжариваем это все;
  8. Добавляем пару больших ложек томатной пасты, нарезанные такими же мелкими параллелепипедиками огурцы (1/2 – 3/4 банки) и еще обжариваем (можно при этом чуток посолить);
  9. Сваливаем все это обжаренное в бульон из-под говядины, добавляем туда маслины, разрезаем лимон на 4 части и не более 1/4 выжимаем в бульен, затем добавляем туда 1/4 часть рассола из-под огурцов (или пару маленьких ложек каперсов, если нет рассола), ложку томатной пасты, тут же можно добавить чуть-чуть черного молотого перца и варим 10-15 мин под крышкой;
  10. После выключения даем супу настояться под крышкой мин 15;
  11. Уже в тарелки добавляем сметану по-вкусу и еще дополнительно лимонного сока.

Know-How:

  1. Очень важно НЕ пересолить. Если что-то солите – соли надо добавлять совсем немного, т.к. соленость будет от рассола и соленых огурцов;
  2. То же для перца – обычно щепотку-две;
  3. Картошку резать непосредственно перед тем как жарить, иначе обветрится;
  4. На остроту так же влияет лимон, так что можно его тоже чуть меньше заливать, так же убедитесь, что косточки НЕ попадают в суп, когда Вы выжимаете лимон, для этого перед тем как его выживать надо выковорять все косточки, можно также разрезать половинку еще пополам, чтобы косточки было удобнее выковыривать.

В итоге суп готовится очень легко и быстро, т.к. вываривание говядины не требует внимания, а обжарка и варка все вместе занимает мин 30 (если за вас уже все ингридиенты порезали :) ). По последней статистике при готовке вдвоем с неопытным поваром с момента начала и до подачи на стол (последержания под крышкой) прошло 2 часа 30 мин.

Еще один хороший рецепт солянки можно найти тут: http://chefcook.ru/2009/02/20/%D1%80%D0%B5%D1%86%D0%B5%D0%BF%D1%82-%D0%BC%D1%8F%D1%81%D0%BD%D0%BE%D0%B9-%D1%81%D0%BE%D0%BB%D1%8F%D0%BD%D0%BA%D0%B8/

Приятного аппетита!

 

Break and continue statements will stop exception flow

Filed under: Software — Tags: , , , , — Artem @ 3:59 AM

As it is said in The Java Language Specification (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15):
The preceding descriptions say “attempts to transfer control” rather than just “transfers control” because if there are any try statements within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.
Let’s look into next example:

public class Test {
	private static void test() throws Exception {
		for (int i = 0; i < 3; i++) {
			try {
				throw new Exception("Exception text");
			} finally {
				System.out.println("Finally exception " + i);
				continue;
			}
		}
		System.out.println("Impossible");
	}

	public static void main(String[] args) throws Exception {
		test();
		System.out.println("Impossible 2");
	}
}

will produce output:

Finally exception 0
Finally exception 1
Finally exception 2
Impossible
Impossible 2

So, be extremely careful with your breaks!

 

How to access overridden methods of superclass of a superclass in Java?

Filed under: Software — Tags: , , , , , , — Artem @ 3:42 AM

Let us consider an example:

public class Test2 {
  static class TestClass1 {
      int x = 1;
      String test() {
          return "1";
      }
  }

  static class TestClass2 extends TestClass1 {
      int x = 2;
      String test() {
          return "2";
      }
  }

  static class TestClass3 extends TestClass2 {
      int x = 3;
      int testX() {
          return ((TestClass1)this).x;
      }
      String test() {
          return super.test();
      }
  }

  public static void main(String[] args) {
      TestClass3 obj = new TestClass3();
      System.out.println(obj.testX());
      System.out.println(obj.test());
  }
}

It produces expected output

1
2

The point is that there is no way to call test() method of the TestClass1 class!

super.super.test()

won’t compile but

((TestClass1)this).test()

will produce java.lang.StackOverflowError.

Despite that we can access superclass members of any level by casting this to appropriate class (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.11.2), polymorphism allows us to access immediate superclass only, not overridden methods of higher levels (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.9).

  « Newer PostsOlder Posts »
 

You need to log in to vote

The blog owner requires users to be logged in to be able to vote for this post.

Alternatively, if you do not have an account yet you can create one here.

Powered by Vote It Up

Powered by WordPress