Monday, December 16, 2013

SPOJ THINKBIT

Well, I always got "compilation error" or "wrong answer" in THIS.
Here are my solutions that works OK on my local machine but NOT on the SPOJ!
return 2 | !(!(x >> 1)); // I like this one!
// but they don't wanna bit shifts!
return 2 | !(!((x & 2) | (x & 4) | (x & 8) | (x & 16) | (x & 32) | (x & 64) | 
(x & 128) | (x & 256) | (x & 512) | (x & 1024) | (x & 2048) | (x & 4096))); 
// kinda idiotic, but works :)
return 2 | !(!(x & 1073741822)); // OK on 64-bit UNIX
return 2 | !(!(x & 65534)); // 32-bit? here it is...
return 2 | !(!(x & 4094)); // WTF?! this gives "wrong answer" on this f... SPOJ !

Whats wrong with SPOJ guys?

SPOJ THINK

Strange Pattern (Easy)
return 3-(x%2)/x; // OK!
return -!(x-1)+3; //gives a "compilation error" ;)

Friday, October 25, 2013

THE BLIN! As expressive as BLYAD but you can also eat it!

The Objective-C religion doesn't allow to insert Integers into NSDictionary

So...
// why they've done so with old good enums?
typedef NS_ENUM(NSUInteger, PaymentType) {
    tCreditCard  = 0,
    tBankAccount = 1,
    tBitcoin     = 2
};

        ...

NSDictionary *payItem = [[NSDictionary alloc] 
                        initWithObjectsAndKeys:[NSNumber numberWithInt:tCreditCard], @"type", 
                        [self makeFakeCreditCardData], @"data", nil];

        ...

switch([[object valueForKey:@"type"] integerValue])
{
    case tCreditCard:
        // do something
        break;

        ...

Thursday, October 17, 2013

Thank you very much!

Some editions of Windows 8 don’t support the free update to Windows 8.1. These include:
Windows 8 Enterprise

Tuesday, October 15, 2013

Linking Storyboards

Very "elegant" solution to resolve "We have one storyboard at all" iOS programmers group nightmare.
Yes, I'm making fun :)

Monday, October 7, 2013

Sunday, September 29, 2013

GitHub's "language tags" just sucks! Although they use "Linguist" to parse sources, them absolutely do not care about which programming language you've really used. They ignore this issue within 10 months! I believe it will be still ignored 10 years after, so I prefer Bitbucket ;)

Wednesday, September 25, 2013

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

Thursday, July 11, 2013

I hate these guys...
I mean guys like Dark Photon. I even cannot register there to leave a comment: after filling out the registration form this f** forum says "we don't want spamers"(!)

Saturday, July 6, 2013

Adobe Acrobat Reader XI...

Well. Still no elementary possibility to make bookmarks! So my choice is still a "Document Viewer" (open source).

Wednesday, July 3, 2013

New Supaplex

Thanks to Sergant this brilliant game is cloned and you can download it for Windows, Linux and MAC OS.

Monday, July 1, 2013

Good tools that help me in my work

After writing this angry post I just have to mention really good tools and their eminent authors.

1. VIM

2. Midnight Commander

3. Firebug

4. Microsoft Visual Studio

5. ReSharper

6. XCode

7. Sublime Text

8. Bitbucket (and thanks for Git, Linus!)

9. WireShark

10. Parse

 

To be continued.

Saturday, June 8, 2013

New fashionable shit that hinders me in my work

Actually I even don't know why these "tools" exist (the only reason seems: to make a life harder). Useless shit that hinders me in my work!

1. LESS CSS

- adds extra work (converting the made-up new syntax to what I really am trying to say, installing stuff on my server etc);
- adds Yet Another Layer Where Things Can Go Wrong between me and my rendered page;
- slows down the performance of the application, eats the computer resources;
- I don't write CSS for crappy grid HTML, so I don't need to go install some tool to help me do that

2. Handlebars.js

- adds extra work (converting the made-up new syntax to what I really am trying to say, installing stuff on my server etc);
- adds Yet Another Layer Where Things Can Go Wrong between me and my rendered page;
- slows down the performance of the application, eats the computer resources;
- it is really buggy;
- I don't write JS for crappy grid HTML, so I don't need to go install some tool to help me do that.

3. CoffeeScript

- in that you basically learn a whole new syntax... to write Javascript. Instead of writing... Javascript;
- adds extra work (converting the made-up new syntax to what I really am trying to say, installing stuff on my server etc);
- adds Yet Another Layer Where Things Can Go Wrong between me and my rendered page;
- slows down the performance of the application, eats the computer resources;
- knowing JavaScript very well, I don't need to go install some shit tool that breaks my mind instead of writing in the old good pure programming language.

4. jQuery

- Hey, Resig! Well-intentioned road to hell is paved with! So you invented just one more tool that gives to lamers the feel of knowledge. But now you are a world known person. Is it what you wanted?

You must use all these "tools" in case you are a real lamer and 'shit diving' is your favorite sport or if you need to do a visibility of work instead of work itself.

In conclusion, I would like to say the word of thanks to all the authors of the shit tools mentioned above: fuck you!

Tuesday, June 4, 2013

New World Говнопорядок

Есть такие "кайфовые" супер-гипер-карпарации "прогромиздские", в которых годик "поработаешь" - и становишься почти профнепригодным. Два годика "поработаешь" - окончательно профнепригоден. Понятно, откуда уши растут, что-как-кто-и-зачем - тоже всё понятно (уж, слава Богу, не совсем дурак), но... [продолжите сами]

"Нам не нужно, чтобы оно работало, нам нужно, чтобы ТЫ заебался!" (с)


Sunday, May 19, 2013

ППКС

Эдсгер Дейкстра: “Приходится признать, что главная задача компьютерной науки — «не запутать все до неузнаваемости» — так и не была достигнута. Увы, большинство наших систем слишком сложны, чтобы не тревожиться об их состоянии, они слишком хаотичны и запутанны, чтобы с ними можно было чувствовать себя уверенно и спокойно”.

Никлаус Вирт: “Лет 25 тому назад интерактивный текстовый редактор мог быть спроектирован из расчета всего лишь 8000 байт памяти — современные редакторы текстов программ требуют в 100 с лишним раз больше. Операционная система должна была обслуживать 8000 байт, а компилятор умещаться в 32 Кбайт, в то время как их нынешние потомки требуют для своей работы многих мегабайтов. И что же, это раздутое программное обеспечение стало быстрее и эффективнее? Наоборот. Если бы не аппаратура с ее возросшей в тысячи раз производительностью, современные программные средства было бы просто невозможно использовать… Характерной чертой компьютерной индустрии является тот факт, что поставщик, которому удалось первым выбросить продукт на рынок, как правило, получает ощутимые преимущества над конкурентом, чей аналогичный — и лучший по качеству! — продукт появляется вторым. Тенденция принимать первый появившийся продукт в качестве 'de facto'-стандарта — крайне прискорбный феномен, вызванный к жизни все той же спешкой.
...В действительности беды программной инженерии происходят вовсе не из-за отсутствия инструментов или хорошего менеджмента, а от недостатка технической компетентности. Хороший проектировщик должен опираться на опыт, на строгое логическое мышление и на педантичную точность. Никакая чудесная магия не может помочь. В свете всего этого особенно грустно, что во многих университетских программах по информатике «программированием в большом» (programming in the large) пренебрегают. Проектирование не заняло надлежащего места в программах по подготовке специалистов. Как результат, программная инженерия превратилась в эльдорадо для хакеров. Программировать без царя в голове стало условием профессионального выживания: чем более хаотичной выглядит программа, тем меньше опасность, что кто-то возьмет на себя труд проинспектировать этот код и развенчать как саму программу, так и ее автора”.

Ларри Уолл: “Такое ощущение, что компьютерная наука ищет некую панацею, которая позволит людям писать корректные программы, даже не думая. На самом деле нам необходимо научить людей думать правильно. И именно здесь компьютерная культура оказывается несостоятельной. Мы забыли о важности фонетических методов изучения компьютерных языков”.

Деннис Цикритзис (автор бестселлеров по операционным системам): “Множество программистов не являются экспертами. Большинство программ не имеют четко определенной среды, в которой они должны работать, или четко определенных спецификаций, определяющих, что же они должны делать”.

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

Tuesday, May 14, 2013

Linux Mint 14, "Nadia"

The newest Linux Mint 14, nicknamed Nadia, uses the fine Cinnamon desktop. Based on the Gnome 3 libraries it is equipped with a hierarchical start menu and all the ergonomic features that the new Gnome Shell is missing. Simplicity rules!

Generally all desktops except Unity from Ubuntu and the new Gnome Shell are usable. Just these two main ones are going strange ways. It is hard to understand that the developers behind them are still trying to ignore all the criticism that comes back from users.

I liked it. It is fast and there is nothing superfluous. Seems to be the best news from the world of Linux for me for a long time.

Saturday, May 11, 2013

The nature of me

"For every word I’ve written, five have been discarded. Such is the nature of writing. For every ten programs I’ve downloaded, tried, and tested, nine have been discarded. Such is the nature of software."
(c) Steven Goodwin

For every line of code I’ve written, too many lines have been discarded. Such is the nature of me :)

Thursday, May 9, 2013

Visual Studio 2012 Pro cannot build your solution because of XAML

You have a large enough project (in my case it is about 2 Gigabytes of sources, libs etc. etc. oh, yeah, baby... although it results in just 33 Mb 'release' executable) written in XAML/C++ for Windows 8 Metro. Suddenly from some point you cannot build it. There are errors in Output something like:
"The specified module could not be found. (Exception from HRESULT: 0x8007007E) your_path\your_project\FuckingPage.xaml 18 13 YourSolution",
"Cannot create instance of type 'YourSolution.Common.YourClass' your_path\your_project\FuckingPage.xaml 30 25 YourSolution" etc.

If this is a case, don't rush to dive into debugger or even figure out what's going wrong. Most likely there is not your mistake at all. Just close before the compilation all opened tabs containing fuckin' XAML files.

Nice, isn't? :)

C structures and memory consumption

Hack to death on your nose: when you declare a structure in C, the bigger data types must go at first. For example:
struct S {
    long double ld;
    char *p; // can be 8 bytes on x64    
    double d;
    float f;
    int i;
    char c;    
} *p;
But not:
struct S {
    char c;
    int i; 
    float f;
    double d;
    char *p;  
    long double ld;
} *p;
I guess the same rule is valid not only for C.

Monday, May 6, 2013

Bit Twiddling

int conditional(int x, int y, int z) {
    return x ? y : x;
}

int conditional(int x, int y, int z) {
    return ((y&(!x+~0))|(z&~(!x+~0)));
}
WARNING: latter is worse not only because it is unreadable, but it also results the worst assembler code (at least in case of the modern compilers). So be careful by using such shit which you can find in some "clever" books and articles :)

Как я провёл лето

Как я провёл "длинные" майские выходные в 2013 году. Надоело писать не по-русски :)

Мда-с. Давненько не брал в руки GDB, Valgrind etc. и не хакал дизассемблированный код. Ощущения непередаваемые, жаль только, что это всё в выходные вместо отдыха. Ну, пара новых прочтенных на аглицком книжек (одна - по Аде, вторая - по компиляторам) да три-четыре статьи - почти не в счёт. Выходные удались, в общем. Хотя домашние меня, кажется, уже тихо ненавидят :(

Планы на следующие "длинные" выходные: примерно такие же, но с упором на Фортран.

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

Saturday, April 27, 2013

Cursed be the day when Microsoft bought Skype!

Subj.

God save the testers

Testers: "Bug report. It is too dark at night and the user can't see anything. Please see the attached screenshot. Assigned to Lord."

Lord: "I tried to reproduce this issue using cats, owls, bats and gentlemen in black velvet too. Cannot reproduce. Closed as 'By Design'."

Testers: "Reopened. Then it seems to be reasonable to show some warning to the user in the evening or even better to turn the user into a cat or an owl. Priority changed to not critical but must be fixed to the next release."

Lord: "Assignee changed to Lucifer. Btw I don't know the next release date."

Monday, April 8, 2013

Very special software for very special users

The MAC users will never know which date, month and year is today. They are completely happy with their half-apple of knowledge about what day of the week is today.

Wednesday, March 27, 2013

JavaScript sux again?

document.execCommand("delete", false.null); will be OK at least in MSIE 10
(attention to the dot between second and third PARAMETERS)

Monday, March 18, 2013

JAVA is good...

Saying that Java is good because it works on all platforms is like saying anal sex is good because it works on all genders.

Friday, March 8, 2013

Brendan Eich about JavaScript

As is well known at this point, I created JavaScript in ten days in May 1995, under duress and conflicting management imperatives—“make it look like Java,” “make it easy for beginners,” “make it control almost everything in the Netscape browser.”
Apart from getting two big things right (first-class functions, object prototypes), my solution to the challenging requirements and crazyshort schedule was to make JavaScript extremely malleable from the start. I knew developers would have to “patch” the first few versions to fix bugs, and pioneer better approaches than what I had cobbled together in the way of built-in libraries. Where many languages restrict mutability so that, for example, built-in objects cannot be revised or extended at runtime, or standard library name bindings cannot be overridden by assignment, JavaScript allows almost complete alteration of every object.
I believe that this was a good design decision on balance. It clearly presents challenges in certain domains (e.g., safely mixing trusted and untrusted code within the browser’s security boundaries). But it was critical to support so-called monkey-patching, whereby developers edited standard objects, both to work around bugs and to retrofit emulations of future functionality into old browsers (the so-called polyfill library shim, which in American English would be called “spackle”).
Beyond these sometimes mundane uses, JavaScript’s malleability encouraged user innovation networks to form and grow along several more creative paths. Lead users created toolkit or framework libraries patterned on other languages: Prototype on Ruby, MochiKit on Python, Dojo on Java, TIBET on Smalltalk. And then the jQuery library (“New Wave JavaScript”), which seemed to me to be a relative late-comer when I first saw it in 2007, took the JavaScript world by storm by eschewing precedent in other languages while learning from older JavaScript libraries, instead hewing to the “query and do” model of the browser and simplifying it radically.
Lead users and their innovation networks thus developed a Java- Script “home style,” which is still being emulated and simplified in other libraries, and also folded into the modern web standardization efforts.
In the course of this evolution, JavaScript has remained backward (“bugward”) compatible and of course mutable by default, even with the addition of certain methods in the latest version of the ECMAScript standard for freezing objects against extension and sealing object properties against being overwritten. And JavaScript’s evolutionary journey is far from over. Just as with living languages and biological systems, change is a constant over the long term. I still cannot foresee a single “standard library” or coding style sweeping all others before it.
No language is free of quirks or is so restrictive as to dictate universal best practices, and JavaScript is far from quirk-free or restrictionist (more nearly the opposite!). Therefore to be effective, more so than is the case with most other programming languages, JavaScript developers must study and pursue good style, proper usage, and best practices. When considering what is most effective, I believe it’s crucial to avoid overreacting and building rigid or dogmatic style guides.

(c) Brendan Eich,
Foreword to "Effective JavaScript" by David Herman