Friday, March 23, 2012

о почте россии

...а знаете, это как-то неправильно, что надо физический адрес адресата указывать. Хотя кто-то, наверное, скажет — эй, ну он же адресат, хрен ли тебе не нравится?
А вот не нравится, блджад! С хрена ли адрес обязан быть физическим? Может, я хочу послать человеку анонимусу открытку и при этом не знаю его адреса и знать не хочу, потому что уважаю его анонимность. А?! А вот если бы анонимус мог зайти на сайт российской почты, получить там uuid, который на протяжении им определённого времени будет оной службою маппиться в его физический адрес, а потом сообщить сий uuid мне для использования... Эх, мечты, мечты... :(

Monday, February 13, 2012

A few words about xmlCleanupParser

Today I wrote an application which uses both libxml2 and GStreamer. It crashed for some mysterious reason which turned out to be xmlCleanupParser called twice. Damn it, it turns out that the only reason for that function to exist is getting rid of valgrind messages!

This frees up a few global variables allocated by libxml2. A few
kilobytes at most, but if they get deallocated while somehow the library
is still in use, the application is very likely to crash.
  So never call this in a library.
  In an app the only safe place to call it is close to the exit
It's still useful to make sure there is no memory leak when running a
program under valgrind or equivalent memory checker.
(http://mail.gnome.org/archives/xml/2011-April/msg00048.html)

Cool, huh?!

I think it's worthwhile to emphasize the thought:

NEVER EVER FUCKING CALL xmlCleanupParser() IN A LIBRARY!

Friday, December 9, 2011

Инфиксная запись функций (С++)

В общем-то, последующее — полный изврат и к применению не рекомендуется :)


#include <functional>

template <typename Func> struct infix_operator;
template <typename Func> infix_operator<Func>& operator|(int, infix_operator<Func>&);
template <typename Func> int operator|(const infix_operator<Func>&, int );

template <typename Func>
struct infix_operator {
    typedef infix_operator<Func> infix_t;
    int left;
    static Func func;
    friend infix_t& operator|<>(int, infix_t&);
    friend int operator|<>(const infix_t&, int);
};
template <typename Func> Func infix_operator<Func>::func;

template <typename Func>
infix_operator<Func>& operator|(int left, infix_operator<Func>& op) {
    op.left = left; return op;
}

template <typename Func>
int operator|(const infix_operator<Func>& op, int right) {
    return infix_operator<Func>::func(op.left, right);
}

static struct : infix_operator<std::plus<int>> {} PLUS;
static struct : infix_operator<std::multiplies<int>> {} TIMES;
static struct : infix_operator<std::divides<int>> {} DIV;
static struct : infix_operator<std::modulus<int>> {} MOD;

#include <iostream>
int main() {
    std::cout << (((2 |PLUS| 3) |TIMES| (36 |DIV| 6)) |MOD| 17) << std::endl;
}

Tuesday, November 8, 2011

On variadic templates

GCC developers, February 2008:
We have implemented the complete specification of variadic templates in the GNU C++ compiler [8], which are available in GCC 4.3. The implementation itself was relatively straightforward in GCC, implying that this feature can be implemented in other C++ compilers without architectural changes. Our basic implementation approach involved adding flags to each kind of template parameter and each function parameter stating whether these parameters are in fact parameter packs.
...
Microsoft guys,  September 2011:
We've developed a new scheme for simulating variadic templates.  Previously in VC9 SP1 and VC10, we repeatedly included subheaders with macros defined differently each time, in order to stamp out overloads for 0, 1, 2, 3, etc. arguments.  (For example, included the internal subheader repeatedly, in order to stamp out make_shared(args, args, args).)  In VC11, the subheaders are gone.  Now we define variadic templates themselves as macros (with lots of backslash-continuations), then expand them with master macros.  This internal implementation change has some user-visible effects.  First, the code is more maintainable, easier to use (adding subheaders was a fair amount of work), and slightly less hideously unreadable.  This is what allowed us to easily implement variadic emplacement, and should make it easier to squash bugs in the future.  Second, it's harder to step into with the debugger (sorry!).  Third, pair's pair(piecewise_construct_t, tuple, tuple) constructor had "interesting" effects.  This requires N^2 overloads (if we support up to 10-tuples, that means 121 overloads, since empty tuples count here too).  We initially observed that this (spamming out so many pair-tuple overloads, plus all of the emplacement overloads) consumed a massive amount of memory during compilation, so as a workaround we reduced infinity.  In VC9 SP1 and VC10, infinity was 10 (i.e. "variadic" templates supported 0 to 10 arguments inclusive).  In the VC11 Developer Preview, infinity is 5 by default.  This got our compiler memory consumption back to what it was in VC10.  If you need more arguments (e.g. you had code compiling with VC9 SP1 or VC10 that used 6-tuples), there's an escape hatch.  You can define _VARIADIC_MAX project-wide between 5 and 10 inclusive (it defaults to 5).  Increasing it will make the compiler consume more memory, and may require you to use the /Zm option to reserve more space for PCHes.

Monday, October 31, 2011

Ещё один неплохой шрифт

Что-то осточертел мне Consolas. (А уж стандартные шрифты — и подавно.)
Решил порыться в инете и наткнулся на то, что вы видите справа:

Недостаток — нету bold. Но это компенсируется забавными 'e', 'g', 'j', а также прыгающими циферками :-)

Thursday, October 20, 2011

Оно работает o_O

Решил тут запилить паттерн Visitor с блэкдже использованием std::shared_ptr:
#include <memory>
#include <type_traits>

...

struct Node : public std::enable_shared_from_this<Node> {
    virtual ~Node() {}
    virtual void accept(Visitor&) = 0;
};

#define DEFINE_ACCEPT_METHOD \
    virtual void accept(Visitor& v) { \
        v.visit(std::static_pointer_cast<std::remove_pointer<decltype(this)>::type>(shared_from_this())); \
    }

struct SomeNode : public Node {  
    ...
   DEFINE_ACCEPT_METHOD;
    ...
};
Но на самом деле макросы - зло. В данном случае можно обойтись безо всякой магии, просто заюзав CRTP ещё раз:
template <class NodeType>                                                                                       
struct VisitableNode : public Node {
    virtual void accept(Visitor& v) {
        v.visit(std::static_pointer_cast<NodeType>(shared_from_this()));
    }
};

struct SomeNode : public VisitableNode<SomeNode> { 
    ... 
};

Sunday, September 4, 2011

визуализация ОДУ в Asymptote

Задали нам, понимаешь, изоклины порисовать на досуге. Ну вот какой уважающий себя программер будет подобной фигнёй вручную заниматься? И вспомнил я тут про Asymptote.
Несколько минут ковыряния в документации привели к следующему: для рисования поля направлений и интегральных кривых имеется модуль slopefield, а для рисования изоклин — модуль contour.

Ну и вот что получилось:
import contour;
import slopefield;
import graph; // чтобы оси нарисовать

settings.outformat = "png";
unitsize(2cm);

pair a = (-5, -5);
pair b = (5, 5);

limits(a, b); // картинка ограничена прямоугольником с углами в a и b
xaxis("$x$", EndArrow);
yaxis("$y$", EndArrow);

real f(real x, real y) { return  x^2 + y^2 - 1; }
real[] isoclines = map(new real(real x){return x*x;}, // анонимная функция применяется к
                     uniform(1, 10, 9)                // массиву {1,2,3,4,5,6,7,8,9,10}
                   ); 

add(slopefield(f, a, b));
draw(contour(f, a, b, isoclines), green);

currentpen = red + 1.5;             // 1.5 - толщина пера в bp (bp == 1/72 дюйма)
for (var i : uniform(-5, 5, 20)) {  // range-based for, так сказать
    draw(curve((i, i), f, a, b));
    draw(curve((0, i), f, a, b));
}