пятница, 27 декабря 2013 г.

Алфавит Азалундского Пса

"Алфавит" Линча - хороший фильм, но дурно влияет на реальность. Когда ехал после просмотра в метро, вокруг зашкалило количество сумасшедших.

Тот же "Азалундский Пёс" сегодня не более непонятен, чем любой немой фильм той эпохи. (если с середины смотреть).

воскресенье, 15 декабря 2013 г.

Поколение Next().Next()

Дикобраза (от B2) - что знают те, кому сейчас 16-18.

Они росли при вечном Путине, для них политическая и стория страны стабильна. Слышали про Хрущёва и Брежнева, но обычно не помнят их очерёдности.

Ленин - правитель, правил после царей, к власти пришёл, кажется, через госудерственный переворот вроде тех, что в новостях показывают.

Похоже, это успех ещё ельцинского (да и доельцинского) стремления к всяческому закремлению преемственности. В инагурация-1996 была заявлена как "соответствующая русским традициям" - хотя до Ельцина и России в текущих границах не было, и правили государством не совсем президенты (Горбачёв, когда стал в 1990-м президентом СССР, ограничился присягой).

пятница, 13 декабря 2013 г.

Z-виртуоз

B2: Z тратит много сил, времени и денег на то, чтоб быть, как он думает, музыкантом. То, что он играет и поёт скучную хрень, а его прожекты закрываются после пары концертов его вообще не волнует.

Как и подобает подростку, он целиком и полностью живёт внешним - то, что результат в никуда не годится, его вообще не парит.

вторник, 10 декабря 2013 г.

воскресенье, 1 декабря 2013 г.

Братья наши соломенные

Если у X есть недостатки, это не всегда значит, что X - плохо. Например, у легендарных Соломенных Енотов львиная (даже не енотная!) доля песен написаны 7-стопным ямбом и поэтому кажутся одной и той же песней.

Но это не значит, что Соломенные Еноты - плохая группа. Они хорошие. Особенно поздние.

вторник, 12 ноября 2013 г.

Украсть миллион

(Андрей рассказывал)

Очень любимая нищебродами тема - украсть миллион и сбежать далеко-далеко. А основной сложностью они считают добраться до этого миллиона.

Добраться до миллиона и правда непросто. Но для завершения квеста этого, увы, недостаточно. Потому что миллион будут искать. И потому что его мало заполучить - его ещё легализовать надо.

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

Не говоря о том, что в одиночку ты деньги никогда не отмоешь.

вторник, 20 августа 2013 г.

Ads and Reality of Functional Programming

There’re a lot of rumors about functional programming now. For example, a lot of people say (mostly on forums) that only really smart guys can learn a functional language and in the short time a Java/C#/C++ programmer will look like a pure C programmer in our age.

Why will functional languages win? Because “they are languages of future” and “I like them”. One more thing: a Haskell program looks really difficult. How can you beat such a difficult thing?

But I don’t think so. Functional languages are very active now, they give great influence to Object Oriented ones, Ruby, Python, PHP, Java, C#, even C++ are implementing lambdas and mapping. But “being futuristic and unusual” and “look difficult” aren’t features. It isn’t even the truth.

Firstly, functional languages are much older then Object Oriented ones. LISP was released in 1958, and became popular in Algol time. They had really plenty of time to beat Fortran or Pascal, but they didn’t. Even today there’re plenty of languages with functional influence, there’re plenty of languages where functional style is possible, but the pure functional family is very little: LISP relatives (they are surviving in Closure, Emacs and SICP, but even SICP course is studied  today with examples on Python), Haskell (more studied then used), Erlang (needed only if you work for Sony Ericsson) and ML languages (OCaml/F# and Scala). All of them look unusual. if you were teached programming on Pascal/C++/Java/Python and are very usual for stufent who studied SICP. LISP was used even in Soviet Union (there’re some translations of handbooks made in 1988-1990).

Even Google uses C++/Python/Java, not Scheme or Haskell.

Secondly, if you need really unusual and different things, try quantum mechanics. The simpler code is, the cheaper will be support. If you aren’t sure, do you need the easy supported code, ask your vendor.

But what’s the thing that make functional languages useful? Let’s look to very ancient (1984, last edition at 1990) paper by a guru:


  1. Glueing Functions Together – you can glue functions and objects they generate as easy as you glue modules of your application.
  2. Glueing Programs Together – any program on a functional language is a function and can be used this way easily
  3. Lazy evaluation makes functional language a good choice to write AI (this was even in Soviet-time books on computer science from 1990!). Because of it, you can avoid storing in memory all of the wrong variants during position analysis.

Have you met this pros in any of functional languages polemics? Or they aren’t important anymore?

If you didn’t, there aren’t any gurus in this thread. There’re just people who show you rare things that are fashionable only because they are rare. Such a people will never make functional languages popular: when something can be used my everyone, it isn’t cool and fashionable anymore.

Studying and using the ideas from functional programming is the business of “simple” programmers on C++-like languages. Because we are only ones who can find place for all of pretty lambdas, closures and monads.

четверг, 18 июля 2013 г.

суббота, 29 июня 2013 г.

Add/Rename “Home” link in WordPress

Blog posts in Wordpress appear mostly on the main page of the site. That’s why you need a link to it at the navigation bar. But some of the themes doesn’t have such a link. Another one has, but it’s called Home mostly. What if you want to rename it to Blog, for example? The thing is that can’t be fixed by WordPress configuaration. The only you can do is to update the theme source code by yourself.

The problem becomes even bigger if your site is not in English. You apply a good theme and… can’t do anything with “Home” label. Like NewsBelarus can’t.

There aren’t any standart way to fix it currently. Install and apply the theme. Then open the main page of your site with your browser (I’ve used Chromium, but Firefox+Firebug or Opera with debugger work fine too) and open Appearance -> Editor in another tab.

Check the source for the HTML around the menu items. Then check the php files of you theme for the place where it is generated. In the most of themes it’s placed in functions.php or header.php. Use menu and home as a keyword to seek in it.

When you’ve found the place, just update it depending on your case:

1) You have no “Home” link, your menu is generated with wp_list_pages(…) function
Write at the top of it another one <li>…</li> block with link to Home page with properly CSS classes.

2) Your menu is generated with wp_page_menu(…) function and you have no “Home” link, or you have “Home” link, but it isn’t written directly in wp_page_manu using ‘show_home’=>true Add ‘show_home’=>”Replacement_for_Home”. If wp_page_manu gets a string in this param, it will be put to Home link as a title.

3) The menu is generated with wp_page_menu or wp_nav_menu Seek in php files (it’s placed in functions.php mostly) for code (probably with another function names) that looks like this:

function mybirdsite_page_menu_args( $args ) {
 $args['show_home'] = true;
 return $args;
}
add_filter( 'wp_page_menu_args', 'mybirdsite_page_menu_args' );

Replace

$args['show_home'] = true;

With

$args['show_home'] = "Replacement_for_Home";

If there aren’t such a lines, add them with properly $args["show_home"]. For wp_page_menu remove the custom menu in  Appearance -> Menus It works because this functions call wp_page_menu actually.

4) The “Home” text is hard-coded If you don’t need i18n, just replace it with the text you need. Otherwise replace it in English version, then put into _e(…) and translate in your language file. This hack is primitive, of course, but isn’t obvious.

понедельник, 22 апреля 2013 г.

C#: Checking for null’s with monads


public static TResult With<tinput tresult="">
(this TInput o, Func<tinput tresult=""> evaluator)
where TResult : class
where TInput : class
{
    return (o == null) ? return null : evaluator(o);
}
Usage:
string postCode = this.With(x => person)
 .With(x => x.Address)
 .With(x => x.PostCode);

понедельник, 1 апреля 2013 г.

Python - filesize in bytes with proper prefix


 
def get_bytes_size_units(num):
  """ Get file size with proper units of measurement.
  """
  range_titles = ["b", "kB", "Mb", "Gb", "Tb", "PB", "EB", "ZP", "YB"]
  range_titles_len = len(range_titles)
  i = 1
  prev_value = 0
  new_value = num
  is_iteration = True
  while is_iteration:
    prev_value = new_value
    new_value = num >> ((i << 1) * 5)
    i += 1
    is_iteration = new_value < 0 and i < range_titles_len
  i -= 2
  return "%.2f%s" % (float(num) / float(1 << ((i << 1) * 5)), range_titles[i])

среда, 20 марта 2013 г.

Incorrect characters in the list of audio devices in Java

Everyone knows, that audio devices are listed in Java with AudioSystem.getMixerInfo(). Mac users know, that the only sound device they have for Macintosh is Built-in Input, Built-In output and Java Sound Audio Engine, version 1.0. And only the ones who use non-latin symbols in OS, know about the problem with this function: Cyrillic letters looks like a habracadabra with it. I’m not sure about Japanese ones, has to be checked still..

Like this:



It happens because getMixerInfo() returns device data in Windows-1252 charset, but tries to output it in Windows-1251. We have to help it somehow

It might be cool to write a wrapper for javax.sound.sampled.Mixer.Info, but toString() and getName() methods in this class are final. Let’s use helper functions:

public class Shared {
 private static String OS = null;
 public static String getOsName()
 {
  if(OS == null)
   OS = System.getProperty("os.name");
     return OS;
 }
 public static boolean isWindows()
 {
    return getOsName().startsWith("Windows");
 }
 public static String toLocalString(Object info)
 {
  if(!isWindows())
   return info.toString();
  String defaultEncoding = Charset.defaultCharset().toString();
  try
  {
   return new String(info.toString().getBytes("windows-1252"), defaultEncoding);
  }
  catch(UnsupportedEncodingException ex)
  {
   return info.toString();
  }
 }
}

Then we use Shared.toLocalString(item.getName()) for every such an instance. All of the titles are ok now:


вторник, 19 марта 2013 г.

grep support for \d

A long time ago, when every PC had own OS, it was easy to remember, which RegEx are from POSIX standart, and which appeared only in Perl-style. Now it’s almost forgotten, and C# regexp classes don’t support POSIX character classes (like [:digit:]).

That’s why the debugging of a simple bash script is so difficult. grep is older then a lot of his users, he remembers all of these times and needs -P for Perl mode and ‘\d’ for digits support.

That’s how

ls | grep -e "[0-9][0-9].[0-9][0-9].md"

becames:

ls | grep -Pe "\d{2}.\d{2}.md"

Free and open-source software licenses

There’re plenty of free and open-source software licenses and not all of them are as simple as Do What the Fuck You Want to Public License. And even if you collected all 4 freedoms and 650 pokemons, it isn’t enough.

The main thing a developer has to know about free and open-source licenses – some of them let the code be linked from code in another language, and some of them don’t.

For example, if you use something licensed as GNU GPL. your project has to be under GNU GPL too. In other hand, if you use BSD license, you can sell it to Apple to make OS X from it.

Please, check the license before using something from GitHub or Google Code.

Google Code allows only OSI-Approved licenses. You have to remember this table to be safe using projects from it:

LicenseLink with code using a different licenseRelease changes under another license
Apache License++
Artistic License+!
Eclipse Public+-
GNU GPL 3--
GNU GPL 2--
GNU Lesser+-
Mozilla Public+!
New BSD++
Microsoft Public License*+-
+ – allowed
- – not allowed
! – limited
* Microsoft Public License isn’t included in official list on Google Code, but is approved by OSI too and is very popular on Codeplex.


Git: How to rename a GitHub repo

GitHub allows to rename your repos. I really like this solution.

Install curl if you haven’t and use terminal (or cygwin under windows):

user=MyUserName
pass=MyPassword
newName='{"name": "NewNameForRepo"}'
oldName="MyRepo"
curl -u "$user:$pass" -X PATCH -d "$newName" https://api.github.com/repos/$user/$oldName

четверг, 7 марта 2013 г.

QT: error: cannot find -lQtMultimedia

The QtMultimedia library is not available in Ubuntu. If you’re trying to create in Qt a project that uses it, it will fail with following error:

error: cannot find -lQtMultimedia

To fix it, you have to install qtmobility and use multimedia items from this lib. Install qtmobility-dev and libdeclarative-multimedia. Then remove QT += multimedia from .pro file and add INCLUDEPATH to QtMobility and QtMultimediaKit directories.

воскресенье, 24 февраля 2013 г.

“Already defined” linker error

This error is very common, when you try to compile in Visual Studio a huge cross-platform C++ project.

This is because of standart C++ templates, that are released in Visual Studio libs and in additional UNIX libs too. So, you have to exclude one of them to use another.

Just add one of them, go to Project Properties / Linker / Input / Ignore Specific Default Libraries and add the standard lib that produces conflict. For me it was enough to add LIBCMT.LIB.

LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

It's a common error when you compile C++-projects with Visual Studio 2010. Ift happens when 2 version of Visual Studio are installed on same PC (like 2010 and 2012) and cause conflict between two versions of cvtres.exe.

To fix it, go to the bin directory of Visual Studio 2010 (c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\ or something like this) and rename cvtres.exe to cvtres0.exe.

Don't worry, it willn’t break linker of 2010,