<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://alexeyvishnevsky.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://alexeyvishnevsky.com/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-30T10:16:43+02:00</updated><id>https://alexeyvishnevsky.com/feed.xml</id><title type="html">Alexey Vishnevsky</title><subtitle>There is always one more bug to fix. Notes on Python, data systems, algorithms, and experiments.</subtitle><author><name>Alexey Vishnevsky</name></author><entry><title type="html">Reinventing Quick Sort by improving Stupid Sort.</title><link href="https://alexeyvishnevsky.com/2018/03/reinventing-quick-sort/" rel="alternate" type="text/html" title="Reinventing Quick Sort by improving Stupid Sort." /><published>2018-03-14T14:00:00+02:00</published><updated>2018-03-14T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2018/03/reinventing-quick-sort</id><content type="html" xml:base="https://alexeyvishnevsky.com/2018/03/reinventing-quick-sort/"><![CDATA[<p>Stupid sort is the sort that just randomly shuffles the array until it eventually becomes sorted.</p>

<p>In spite of the fact that stupid sort is not so popular in production environment, it may be mentioned as an opening question at programming interview of any level. The discussion about optimizing this kind of search may be very interesting and useful for better understanding some sorting techniques.</p>

<p>In a nutshell stupid sort may be written like this:</p>

<p><a href="/wp-content/uploads/2018/03/Screenshot_2018-03-20-23-40-58_com.quseit.qlua5pro2.png"><img src="/wp-content/uploads/2018/03/Screenshot_2018-03-20-23-40-58_com.quseit.qlua5pro2.png" alt="" /></a></p>

<p>The average running time of this algorithm is terribly long. For each permutation (out of n!) we need to verify the order of all the elements in the array (n elements) which gives us O (n*n!). On my Hexa-core Xiaomi Redmi 3 phone this process is very slow even for n=10 ending up with more than 36 million operations. In the worst case, the running time of the algorithm is unbounded, for the same reason that a tossed coin might turn up heads any number of times in a row.</p>

<p>The best case occurs if the list as given is already sorted; in this case the expected time complexity is O(n)</p>

<p>For any collection of fixed size, the expected running time of the algorithm is finite for much the same reason that the <a href="https://en.m.wikipedia.org/wiki/Infinite_monkey_theorem" title="Infinite monkey theorem">infinite monkey theorem</a> holds: there is non-zero probability of getting  right permutation, so given an unbounded number of tries it will <a href="https://en.m.wikipedia.org/wiki/Almost_surely" title="Almost surely">almost surely</a> eventually be chosen.</p>

<p>Let us demonstrate the way we can increase the average running time by adding a couple of simple rules. In our example <code class="language-plaintext highlighter-rouge">shuffle</code> each time swaps 2 random elements. What if we will not swap those pairs that already placed in a right order (left element smaller than right)? This will immediately save us a lot of swaps and also significantly decrease the running time.</p>

<p>Let us write down this “directional shuffle”:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def shuffle(arr, l, r):
    rint = random.randint
    while l &amp;lt; r:
        m = rint(l, r)
        if arr[l] &amp;gt; arr[m]:
            arr[m], arr[l] = arr[l], arr[m]
        l += 1
    return arr
</code></pre></div></div>

<p>Now, after adding these new rules, my phone was able to sort 100 elements in less than a second.</p>

<p><a href="/wp-content/uploads/2018/03/Screenshot_2018-03-13-23-49-09_com.quseit.qlua5pro2.png"><img src="/wp-content/uploads/2018/03/Screenshot_2018-03-13-23-49-09_com.quseit.qlua5pro2.png" alt="" /></a></p>

<p>Although the running time has decreased, it still increases very fast, when the number of elements in the array adds up. For example, to sort 1000 elements takes about 100 seconds. We increased the array size by x10 and got the x1000 slow down. This allows us to estimate our algorithm by O(n^3). It turns out that if we only could split our 1000 elements array to 10 sub-arrays by 100 elements and then sort each other separately, this would take us less than 10*(1 sec) = 10 seconds (instead of 1000). The only thing we should figure out is how to split the array in such way that the merge back would be trivial. Apparently we can change our shuffling function a little bit so that after shuffling the value of elements in the left part of the array will be smaller than those of the elements in the right part. Shuffling written in this way may be called many times on the same part of the array until it eventually becomes sorted (stupid-sort technique). Then, after all parts of the array are sorted, the entire array becomes sorted (trivially).</p>

<p>Let us modify our “shuffle” to swap elements with respect to some randomly chosen element of the array (pivot):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def shuffle(arr, l, r):
    m = l

    # chose pivot randomly and place as last element
    p = random.randint(l, r)
    arr[p], arr[r] = arr[r], arr[p]

    # swap elements arr[l], arr[m] according to pivot arr[r]
    while l &amp;lt; r:
        if arr[l] &amp;lt; arr[r]:
            arr[l], arr[m] = arr[m], arr[l]
            m += 1
        l += 1

    # place pivot between 2 partitions
    arr[m], arr[r] = arr[r], arr[m]
    return m
</code></pre></div></div>

<p>The result of one run of this function is that original array was divided into 2 parts: left and right, separated by pivot. Each element on the left is smaller than pivot, and each element on the right is greater or equal than the pivot. Please notice that the function has O (n) time complexity and works in-place.</p>

<p>Now our stupid_sort can be written as follows:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def stupid_sort(arr):
    r = len(arr) - 1
    while not is_sorted(arr):
        p = shuffle(arr, 0, r)
        p1 = shuffle(arr, 0, p)
        p2 = shuffle(arr, p, r)
        p3 = shuffle(arr, 0, p1)
        p4 = shuffle(arr, p1, p)
        p5 = shuffle(arr, p, p2)
        p6 = shuffle(arr, p2, r)
        # etc..
</code></pre></div></div>

<p>We can actually achieve the same functionality, using a recursion:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def stupid_sort(arr, l, r):
    if l &gt;= r:
        return
    p = partition(arr, l, r)
    stupid_sort(arr, l, p)
    stupid_sort(arr, p + 1, r)
</code></pre></div></div>

<p>Pay attention, that is_sorted(arr) call replaced with if l &gt;= r: since once the size of partitions is 2 the partitions become sorted. Then the original array which consists of sorted partitions becomes also sorted.</p>

<p>Here is the full code resuming all the above:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import time
import random


def shuffle(arr, l, r):
    m = l
    p = random.randint(l, r)
    arr[p], arr[r] = arr[r], arr[p]

    while l &lt; r:
        if arr[l] &lt; arr[r]:
            arr[l], arr[m] = arr[m], arr[l]
            m += 1
        l += 1

    arr[m], arr[r] = arr[r], arr[m]
    return m


def stupid_sort(arr, l, r):
    if l &gt;= r:
        return
    p = shuffle(arr, l, r)
    stupid_sort(arr, l, p)
    stupid_sort(arr, p + 1, r)


n = 100000
arr = [random.randint(1, n) for i in range(n)]
st = time.time()
stupid_sort(arr, 0, len(arr) - 1)
print time.time() - st
print arr
</code></pre></div></div>

<p>Written in such way, shuffling function has a special name – partitioning and the algorithm called Quick Sort. Its complexity is bound by number of</p>

<p>partitions, multiplied by complexity of shuffling each partition which is `log(n)</p>
<ul>
  <li>n`<br />
Thus, we have just demonstrated how by means of gradually improving the<br />
most basic and simple function, our stupid sort has been transformed into<br />
one of the most efficient sorting algorithms known today.</li>
</ul>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Algorithms" /><summary type="html"><![CDATA[Stupid sort is the sort that just randomly shuffles the array until it eventually becomes sorted. In spite of the fact that stupid sort is not so popular in production environment, it may be mentioned as an opening…]]></summary></entry><entry><title type="html">SSDB as a cheaper alternative to Redis</title><link href="https://alexeyvishnevsky.com/2017/01/ssdb-redis/" rel="alternate" type="text/html" title="SSDB as a cheaper alternative to Redis" /><published>2017-01-16T14:00:00+02:00</published><updated>2017-01-16T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2017/01/ssdb-redis</id><content type="html" xml:base="https://alexeyvishnevsky.com/2017/01/ssdb-redis/"><![CDATA[<p>Hello again, today I would like to talk about SSDB – high-performance NoSQL database as a cheaper drop in replacement for Redis.</p>

<p>Redis in most cases is the best solution for managing a high-througput and low-latency data access. It’s also open source and free to use. But using Redis might be expensive in terms of higher costs for hardware resources utilization. For example, I was recently required to store a lot of keywords, which number per task was virtually unlimited. Redis was a first option coming to my mind. I’ve started to look around for existing services which hosts Redis, and found that the prices were much over expectations. At redislabs.com to get the database storage of 15 GB would cost about USD1000 per month. This is the cheapest I could find so far. Thus, in case, one would need to store large amounts of data, he would have to pay quite a fortune to do this with Redis. Such prices explained by the fact that Redis is in-memory database and memory is an expensive resource. So I started to think about alternatives and search for Redis-like disk-based database which will reduce the costs without compromising the speed.<br />
<strong>Ask and it will be given to you.</strong><br />
Eventually, as I was doing my search, I came across SSDB – high performance NoSQL database. It supports most of Redis protocol and can be used as a drop in replacement for Redis. It even can be accessed with Redis clients. There is a <a href="http://ssdbhub.com/documentation.html#using-ssdb-with-different-languages-using-with-redis-clients-key-value">list of supported Redis commands</a> and the way they map to SSDB. While being disk based, SSDB can store much more data, than Redis on the same machine, which is much cheaper.</p>

<p><a href="https://people.eecs.berkeley.edu/%7Ercs/research/interactive_latency.html">Every programmer should know</a> that 1 disk seek is by 100.000 times slower than an access to RAM. Therefore, how possibly disk-based database can be as fast as in-memory one?<br />
The answer is – a little bit of magic and voila … LevelDB design, which implements SSTable (Sorted Strings Table, hence the name for SSDB). Credit to Google.<br />
Describing briefly, the process works as follows:  the database queries, which change the data (writes, updates and deletes) are stored as a deltas in memory layer which is fast. Once the specified size of such layer is reached, all those deltas dumped to disk. Being sorted, the data is written to disk sequentially, which is only by 3 times slower than writing to RAM (not x100.000 times slower as I mentioned before). Such dumps occur once a while thus giving us the amortized performance comparable to in-memory’s one. Reads are done by searching in-memory layer first and then, if not found – accessing the disk (worst case).<br />
The worst case scenario, performing many random seeks to disk, in theory would be significantly slower. However, let’s keep in mind that in such a case, when the data size is bigger than memory available, any in-memory database would be already overflown and effectively dead. Thus the above comparison is still in favor of SSDB.</p>

<p>I made a quick benchmark with redis-benchmark tool to Redis server:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>➜  ~ redis-benchmark -p  6379   -n 50000 -t set,get -q
SET: 77399.38 requests per second
GET: 62972.29 requests per second
</code></pre></div></div>

<p>and the same procedure to SSDB server, running on the same machine, with same redis-benchmark tool:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>➜  ~ redis-benchmark -p  8888   -n 50000 -t set,get -q
SET: 61652.28 requests per second
GET: 63451.78 requests per second
</code></pre></div></div>

<p>We can see that SSDB’s <code class="language-plaintext highlighter-rouge">set</code> is only 20% slower, but <code class="language-plaintext highlighter-rouge">get</code> is slightly faster then <code class="language-plaintext highlighter-rouge">get</code> of Redis.<br />
Concluding the above, we saw that SSDB in most cases is as fast as Redis, and worst case for SSDB is not even supported by Redis. There is an attempt to overcome this problem with hybrid solution such as Redis + MongoDB or Redis + PostgreSQL, where Redis provides a cache-like layer in front of disk-based database. Such approach seems to be not trivial at all, when it comes to scaling and synchronizing the different databases between themselves.<br />
SSDB provides solution to all of these cases at once. No more hybrid solutions needed.<br />
Many companies have already recognized advantages of SSDB. Thus Chinese search giant Baidu uses SSDB for their most important service – Web Search. QIHOO 360 which operates hundreds of millions users, migrated its Redis instances to SSDB, and now it uses less servers for storage.<br />
When I realized there is no simple way to use SSDB from Heroku platform, I created <a href="http://ssdbhub.com/">ssdbhub.com</a> which  provides SSDB as Heroku add-on.</p>

<p><strong>WE ARE LOOKING FOR ALPHA TESTERS FOR THIS ADD-ON</strong></p>

<p>Our first users will be given away 5 GB Free Plan for unlimited period of time.<br />
To claim your free plan, drop your email at <a href="http://ssdbhub.com/">ssdbhub.com</a></p>

<p>To get started, refer to <a href="http://ssdbhub.com/documentation.html">documentation</a>. There is a comprehensive guide on how to create the SSDB add-on on Heroku and how to access it, using your favorite programming language.</p>

<p>It’s extremely important to us to get your feedback, If you have any technical issues, fill free to open the public discussion on our <a href="https://github.com/ssdbhub/ssdbhub.github.io/issues">issue tracker</a> or send us a direct message to <a href="mailto:support@ssdbhub.com">support@ssdbhub.com</a>, whichever works best for you.</p>

<p>A journey of a thousand miles begins with a single step.</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Data systems" /><summary type="html"><![CDATA[Hello again, today I would like to talk about SSDB – high-performance NoSQL database as a cheaper drop in replacement for Redis. Redis in most cases is the best solution for managing a high-througput and low-latency…]]></summary></entry><entry><title type="html">Mission Impossible! Or how to beat a chess computer at impossible level.</title><link href="https://alexeyvishnevsky.com/2015/10/chess-com-conquered/" rel="alternate" type="text/html" title="Mission Impossible! Or how to beat a chess computer at impossible level." /><published>2015-10-26T14:00:00+02:00</published><updated>2015-10-26T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2015/10/chess-com-conquered</id><content type="html" xml:base="https://alexeyvishnevsky.com/2015/10/chess-com-conquered/"><![CDATA[<p>Hello again,</p>

<p>check out the video I have made of playing chess on today’s one of the most popular chess sites. As you can see, I was able to outplay a chess computer at “IMPOSSIBLE” level as its name suggests.</p>

<p>On the web site it has been rated 2300 ELO that compares to a strong master level. So my achievement is quite impressive, considering I have never been studying playing chess professionally, and my rating is about average.</p>

<p>I’m not a professional chess player …but I’m a programmer.</p>

<p>And here is the catch. As you have probably guessed, it is my chess bot that is playing on the video. I was surprised how easy it is to actually build one. The bot opens a browser, logs in to the playing area, reads the moves from the moves list, detects game times and makes its own moves by actually clicking and dragging the pieces over the board. I used Selenium for browser automation and Stockfish – one of the world’ strongest, open sourced chess engine – for “thinking”. All in all, it took less than a hundred lines of Python code and a weekend of hacking around the web sites DOM tree.</p>

<p>I’m not going to publish the source code, not to encourage the usage of such piece of technology against the real players. I think it’s not fair and not fun.</p>

<p>That was a challenge for me as a programmer and it is successfully accomplished. I was able to create an automated player that is much stronger than myself and stronger than majority of human players. This brings me to an interesting point…</p>

<p>It does not matter what you are going to learn, learn Programming!</p>

<h6 id="background-music-izzat-man--robots-are-also-sleeping">Background music: Izzat Man – Robots are also sleeping</h6>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Experiments" /><summary type="html"><![CDATA[Hello again, check out the video I have made of playing chess on today’s one of the most popular chess sites. As you can see, I was able to outplay a chess computer at “IMPOSSIBLE” level as its name suggests. On the web…]]></summary></entry><entry><title type="html">Lua as a Python’s secret weapon.</title><link href="https://alexeyvishnevsky.com/2015/05/lua-wraped-python/" rel="alternate" type="text/html" title="Lua as a Python’s secret weapon." /><published>2015-05-28T15:00:00+03:00</published><updated>2015-05-28T15:00:00+03:00</updated><id>https://alexeyvishnevsky.com/2015/05/lua-wraped-python</id><content type="html" xml:base="https://alexeyvishnevsky.com/2015/05/lua-wraped-python/"><![CDATA[<blockquote>
  <p>There are Lies, Damn Lies, and Benchmarks</p>
</blockquote>

<p><strong>Pure Python</strong></p>

<p>Hello again, today I would like to share some remarkable benchmark findings that demonstrate the way Python may be boosted by embedding Lua into Python code. The process has started with simple task my friend asked me to fulfil in order to compare Python to other languages. So, below is the benchmark we are going to test:</p>

<p><strong>fig 1.0</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import random
import time

size = 5000000
st = time.time()
a = [random.randint(1, size) for _ in xrange(size)]
b = [random.randint(1, size) for _ in xrange(size)]
print "Pure Python init", time.time() - st

def test():
    for i in xrange(size):
        if a[i] != b[i]:
            a[i] = a[i] + b[i]

st = time.time()
test()
print "Pure Python sum", time.time() - st
</code></pre></div></div>

<p>We have created 2 arrays of 5M random integers each and then we have compared them. If elements with corresponding indexes are different (merely they are) we would make “sum and update” action, which gives us the following result:</p>

<p>Pure Python init 7.01951003075<br />
Pure Python sum 0.525348901749</p>

<p>Thus, Python requires about 7 seconds to initialize the arrays and another 0.52 seconds to perform “sum and update” action.<br />
Are we capable to get more out of Python? Yes, for sure, we are!  Let’s see below:</p>

<p><strong>NumPy</strong></p>

<p>Apparently NumPy is capable to sum up two arrays in very efficient way. It is also superior in array initialization.</p>

<p>Consider the following code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import numpy as np
size = 5000000
st = time.time()
a = np.random.randint(size, size=size)
b = np.random.randint(size, size=size)
print "Numpy init", time.time() - st

def test1():
    np.sum(a!=b)

st = time.time()
test1()
print "Numpy sum", time.time() - st
</code></pre></div></div>

<p>The output:</p>

<p>Numpy init 0.211035966873<br />
Numpy sum 0.0101628303528</p>

<p>We can see that NumPY requires just 0.2 seconds for arrays initialization versus 7 seconds of Python, which is 35x faster of pure Python time. Same thing is with the “sum and update” action. NumPy used 0.01 second versus 0.5, which is 50x time. Pretty impressive numbers!</p>

<p><strong>PyPy</strong></p>

<p>Running the pure Python code (fig 1.0) with PyPy gives us the same results as NumPy:</p>

<p>Regular init 0.203986883163<br />
Regular sum 0.0113749504089</p>

<p><strong>C</strong></p>

<p>Now let’s see what we are able to get out of C. My friend claimed he could write this function with C and it would take him no more than 5 minutes. Well, he actually did it within 5 minutes and then spent another hour trying to figure out why the function was not working. Probably, every experienced C programmer would immediately spot the problem. Namely, in C you cannot just declare the array of size 5000000 because it is too big to be placed in app stack. What you should do, is to place it in a heap by malloc function.. While my friend was straggling with C code, I wanted to figure out how to speed up Python code without writing custom module in C. And I have found this simple solution:</p>

<p><strong>Lua</strong></p>

<p>Lua is an amazing language! It’s available as open source, it’s easy to read and understand, which makes it easy to learn. You can find a detailed and authoritative introduction to all aspects of Lua programming written by Lua’s chief architect Roberto Ierusalimschy <a href="http://www.lua.org/pil/contents.html">here</a>. In spite being simple, it is, nevertheless, a very powerful tool and a solid piece of programming art. To say the least, Lua is one of the fastest dynamic languages today. So please do not underestimate it. An important feature for us is that Lua has a very small memory footprint – less than 200K for the whole interpreter. This allows us to seamlessly embed it into any environment in order to facilitate and speed up the process.</p>

<p>Here is our benchmark written with Lua but yet wrapped with Python:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>from lupa import LuaRuntime
lua = LuaRuntime()

lua_code = """
function (size)
    a = {}
    b = {}
    st = os.clock()
    for i=0, size-1 do
        a[i] = math.random(size)
    end

    for i=0, size-1 do
        b[i] = math.random(size)
    end

    print("LUA init: "..(os.clock()-st))

    st = os.clock()
    for i=0, size-1 do
        if a[i] ~= b[i] then
            a[i] = a[i] + b[i]
        end
    end
    print("LUA sum: "..(os.clock()-st))
end
"""
test = lua.eval(lua_code)
size = 5000000
test(size)
</code></pre></div></div>

<p>Output:</p>

<p>LUA init: 0.080163<br />
LUA sum: 0.007911</p>

<p>The result is amazing! We can see that Lua is faster than PyPy and faster than NumPy by 1.5-3x, and faster than pure Python by 50-100x!</p>

<ol>
  <li>Python   1x</li>
  <li>NumPy  50x</li>
  <li>PyPy     50x</li>
  <li>Lua       100x</li>
  <li>C          100x</li>
</ol>

<p>As you can see, it was easy to embed Lua in Python and the results are outstanding! Thus, we can say that Lua is definitely of a great help when you need to speed up some critical parts of your Python code. Many commercial products today use Lua. Just to name a few: <a href="http://www.adobe.com/products/photoshoplightroom/">Adobe Photoshop Lightroom,</a> <a href="http://www.worldofwarcraft.com/">World of Warcraft,</a> <a href="http://www.farcry-thegame.com/">FarCry,</a> <a href="http://simcity.ea.com/">SimCity 4</a> and <a href="http://en.wikipedia.org/wiki/Lua_%28programming_language%29#Applications">others</a>.</p>

<p>Hope you enjoyed this post and it will be useful to you.</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Algorithms" /><summary type="html"><![CDATA[There are Lies, Damn Lies, and Benchmarks Pure Python Hello again, today I would like to share some remarkable benchmark findings that demonstrate the way Python may be boosted by embedding Lua into Python code. The…]]></summary></entry><entry><title type="html">Yahoo ChessMaster R.I.P</title><link href="https://alexeyvishnevsky.com/2015/02/yahoochessmaster-r-i-p/" rel="alternate" type="text/html" title="Yahoo ChessMaster R.I.P" /><published>2015-02-15T14:00:00+02:00</published><updated>2015-02-15T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2015/02/yahoochessmaster-r-i-p</id><content type="html" xml:base="https://alexeyvishnevsky.com/2015/02/yahoochessmaster-r-i-p/"><![CDATA[<p>Hello again,</p>

<p>this is my next publication in which I would like to share one of my first experiences as a programmer.</p>

<p>I strongly believe the best method of learning something is simply to start doing it. Yep, it’s all about practice.<br />
So, there was no better way for me to learn a new programming language than just start writing a project using this language. One of my first self-educational projects was YahooChessMaster – a chess bot that can play chess at Yahoo game portal.</p>

<p><a href="/wp-content/uploads/2015/02/yahoochessmasterv10pk6.png"><img src="/wp-content/uploads/2015/02/yahoochessmasterv10pk6.png" alt="yahoochessmasterv10pk6" /></a></p>

<p>I think, it was one of the first Yahoo bots at that time. I have written it using VC++ v.6.0 back in 2005.<br />
YCM was identifying the open browser window with a chessboard inside and it was scanning the board visually pixel by pixel. Then YCM was passing the pieces position from the board to a local chess engine, using UCI protocol. The engine was making a move and returning its algebraic notation to YCM.<br />
After that YCM was moving the corresponding piece on the board by transmitting mouse events to browser window. You may say: “Scanning the board is an overhead.  Wouldn’t be much easier to emulate the network interactions: request/response?”</p>

<p>No it wouldn’t, turns out, to emulate the networking may not be that simple at all. First, the communication mays need to be ssl encrypted; then, it has to use some sort of custom protocol that would require tons of reverse engineering efforts.<br />
In my method, I had managed to speed up the board scanning process by reducing the amount of pixels that need to be scanned. Thanks to the reach color pallet of the chess pieces representation, it was possible to identify a chess piece by getting only one single pixel from a single square. Thus, to read the entire game position was a matter of reading 64 single pixels only. YCM was able to do it many times per second.<br />
Eventually, after all the Internet lags, plus pixels reading stuff, plus IPC interactions with engine and mouse events passing back to the browser, YCM was able to shoot 1 move per second, playing 1 minute blitz game. In addition to incredibly short move time, YCM playing strength was amazingly high. Behind the curtains YCM was using one of the strongest chess engines at this time called Spike – a winner of a first Computer World Championship in 2005. And Spike was free of charge.<br />
Very quickly YCM became 2400 rated. It literally never lost any game. I have realized that I’ve created something really good and tried to sell it… During playtime YCM was posting spam-like messages in the rooms chat that were referring individuals who might be interested to my website where a limited demo version was available for free and fully-functional-commercial one for only $9.<br />
Only one YCM copy was sold and later refunded. It turned out, YCM did not have an ability to comply with too many different versions of Windows at that time. Just to name few of them: XP Home, XP Professional, ME, 2000, 98, 95… I just had no time to support all of this “commercial” stuff, and eventually I abandoned the project. The website with the demo version was shut down. All this happened in 2005<br />
Today there are couple of chess bots for Yahoo that are dramatically similar to my YCM. One of them is Chess Buddy.</p>

<p>Here is how it looks like:</p>

<p><a href="/wp-content/uploads/2015/02/ssChsY2.gif"><img src="/wp-content/uploads/2015/02/ssChsY2.gif" alt="ssChsY2" /></a></p>

<p>And here is the screen shot from YCM:</p>

<p><a href="/wp-content/uploads/2015/02/yahoochessmasterv10bmp2ui3.png"><img src="/wp-content/uploads/2015/02/yahoochessmasterv10bmp2ui3.png" alt="yahoochessmasterv10bmp2ui3" /></a></p>

<p>So there is a chance that my ideas were adopted and are living till now. And I’m good with that.</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Experiments" /><summary type="html"><![CDATA[Hello again, this is my next publication in which I would like to share one of my first experiences as a programmer. I strongly believe the best method of learning something is simply to start doing it. Yep, it’s all…]]></summary></entry><entry><title type="html">About websockets of 90’s and creativity within..</title><link href="https://alexeyvishnevsky.com/2014/10/websockets-90s-creativity-within/" rel="alternate" type="text/html" title="About websockets of 90’s and creativity within.." /><published>2014-10-01T15:00:00+03:00</published><updated>2014-10-01T15:00:00+03:00</updated><id>https://alexeyvishnevsky.com/2014/10/websockets-90s-creativity-within</id><content type="html" xml:base="https://alexeyvishnevsky.com/2014/10/websockets-90s-creativity-within/"><![CDATA[<p>Eventually I was involved in a talk about different ways of establishing a real time connection between browser and server. One of my colleagues just said: “I would use a GIF for that”, and I was like “whaat?”, and then he showed me this library: <a href="https://sourcegraph.com/github.com/twolfson/gifsockets?symbolKind=var">gifsockets</a>. This is an implementation of Graphical Interchange Format protocol, known as GIF. It’s supposed to represent animation in browser, that consists of set of frames that are consistently changing each other. When downloading GIF animation, browser is doing this frame by frame and is holding the connection till receiving a special character from the server. Potentially, when there is no such special character sent, the browser might hold the connection opened forever. It’s also possible to convert plain text to a special format (RGB frame) and send it via a regular GIF protocol to a browser.</p>

<p>Back in 90’s, when there was no websockets, people were using this feature for establishing a real time communication between browser and server. Although this is clearly a big piece of hack – when something is used in a way it’s not supposed to – I think this is an amazing example of creativity in programming..</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Python" /><summary type="html"><![CDATA[Eventually I was involved in a talk about different ways of establishing a real time connection between browser and server. One of my colleagues just said: “I would use a GIF for that”, and I was like “whaat?”, and then…]]></summary></entry><entry><title type="html">Extracting textual time-based content from blog page using LCA techique on a DOM tree.</title><link href="https://alexeyvishnevsky.com/2014/01/scraping-blogs-finding-repeating-patterns-dom-tree/" rel="alternate" type="text/html" title="Extracting textual time-based content from blog page using LCA techique on a DOM tree." /><published>2014-01-20T14:00:00+02:00</published><updated>2014-01-20T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2014/01/scraping-blogs-finding-repeating-patterns-dom-tree</id><content type="html" xml:base="https://alexeyvishnevsky.com/2014/01/scraping-blogs-finding-repeating-patterns-dom-tree/"><![CDATA[<p>Today there is increasing interest in scraping the latest data from internet. Especially textual data. There is a lot of content providing sites, such as blogs, news, forums, etc. This content is time-based (periodically updated during the time). Extracting time-based content from millions of sites is not a trivial task. The main difficulty here is that we don’t know beforehand what is the format of the HTML page that we are going to scrape.</p>

<p>In this post I will describe the method for extracting the time-based textual content from the blog pages in the automatic manner.</p>

<p>Let us look on how posts are organized in the vast majority of blogs:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;div class="post-container"&gt;
  &lt;div class="post-1"&gt;
    &lt;p&gt;...&lt;/p&gt;
    &lt;abbr class="published entry-date"&gt;January 11, 2014&lt;/abbr&gt;
  &lt;/div&gt;
  &lt;div class="post-2"&gt;
    &lt;p&gt;...&lt;/p&gt;
    &lt;abbr class="published entry-date"&gt;January 10, 2014&lt;/abbr&gt;
  &lt;/div&gt;
  &lt;div class="post-3"&gt;
    &lt;p&gt;...&lt;/p&gt;
    &lt;abbr class="published entry-date"&gt;January 9, 2014&lt;/abbr&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre></div></div>

<p>There are posts that consist of repeating DOM elements such as divs, spans and so on. The common feature in them is that every post contains time stamp. The time stamp might be in the beginning of the post or in the end of it, but almost always it’s a separate DOM element.</p>

<p>So it might be not too hard to detect the dates, using some sort of date parsing library, such as <a href="http://labix.org/python-dateutil">dateutil</a>.</p>

<p>The dates detection process would go like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import datetime
from lxml import etree
from lxml.html import HTMLParser
from dateutil.parser import parse

def is_valid_date(text):
    """Based on dateutil should return True if text is valid 
       date format, and False othervise"""
    ...

def main():
    response = urllib.urlopen("http://alexeyvishnevsky.com/")
    element_tree = etree.parse(response, HTMLParser())
    date_candidates = []
    for element in element_tree.getiterator():
        text = element.xpath("text()")
        if not len(text):
            continue
        if is_valid_date(texti[0]):
            date_candidates.append(element)
    print [d.xpath("text()")[0] for d in date_candidates]

main()
</code></pre></div></div>

<p>Now when we have the dates, we assume that each of them is the part of the post that we need to collect, but we don’t know where does the post starts and where does it end?</p>

<p>Fortunately there is an efficient method to identify the posts boundaries by finding the Lowest Common Ancestor (LCA) for given dates elements in a DOM tree. Then having the dates LCA’s we can be pretty sure that its children provide the required entry points to the posts itself. Below is the picture that visualizes the idea:</p>

<p><a href="/wp-content/uploads/2014/01/Screenshot-from-2014-01-19-183138.png"><img src="/wp-content/uploads/2014/01/Screenshot-from-2014-01-19-183138.png" alt="Screenshot from 2014-01-19 18:31:38" /></a></p>

<p>Another, more complex case such as multiple post threads in the page:</p>

<p><a href="/wp-content/uploads/2014/01/Screenshot-from-2014-01-19-175745.png"><img src="/wp-content/uploads/2014/01/Screenshot-from-2014-01-19-175745.png" alt="Screenshot from 2014-01-19 17:57:45" /></a></p>

<p>All these cases are supported by the following code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def find_lca_candidates(graph, date_candidates):
    import itertools
    lca_local_candidates = None
    lca_global_candidates = set()
    comparing_set_for_local_date_candidates = itertools.combinations(
                                                    date_candidates, 2)
    for item in comparing_set_for_local_date_candidates:
        path = graph.shortest_path(item[0].xpath, item[1].xpath)
        if not lca_local_candidates:
            lca_local_candidates = set(path)
        else:
            lca_local_candidates = lca_local_candidates.intersection(
                                                            set(path))
        if len(lca_local_candidates) == 1:
            item = lca_local_candidates.pop()
            lca_global_candidates.add(item)
            lca_local_candidates = None

    return lca_global_candidates
</code></pre></div></div>

<p>Where graph is the <a href="http://www.clips.ua.ac.be/pattern">pattern.graph.Graph</a> instance representing the HTML DOM tree. We are using here shortest_path method to find the shortest paths between the dates elements. The intersection points of these shortest paths will provide the LCA  candidates.</p>

<p>Then we might want to iterate through LCA’s children and extract text from them. This may be accomplished with something similar to the following actions:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def collect_posts_from_page():
    posts = []
    for lca_candidate in lca_global_candidates:
        for child in lca_candidate:
            posts.append(extract_text_from_etree(child))
    return posts
</code></pre></div></div>

<p>And, Yuppee!! We have got the posts!</p>

<p>This was a high level overview of the method. Obviously there is more optimization needed to make use of it in the production environment. Hopefully this will give some insights for those who’s interested with data mining and especially in time-based content extraction.</p>

<p>Thanks to my sister <strong>Natalia Vishnevsky</strong> for editing this and for the moral support.</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Algorithms" /><summary type="html"><![CDATA[Today there is increasing interest in scraping the latest data from internet. Especially textual data. There is a lot of content providing sites, such as blogs, news, forums, etc. This content is time-based…]]></summary></entry><entry><title type="html">Python as an optimal solution for today’s network application programming challenges.</title><link href="https://alexeyvishnevsky.com/2013/11/python-as-an-optimal-solution-for-todays-network-application-programming-challenges/" rel="alternate" type="text/html" title="Python as an optimal solution for today’s network application programming challenges." /><published>2013-11-03T14:00:00+02:00</published><updated>2013-11-03T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2013/11/python-as-an-optimal-solution-for-todays-network-application-programming-challenges</id><content type="html" xml:base="https://alexeyvishnevsky.com/2013/11/python-as-an-optimal-solution-for-todays-network-application-programming-challenges/"><![CDATA[<p>Recently I have made a brief exploration of local job market and have found a simple fact – Python is greatly misunderstood and as a result – extremely underestimated.</p>

<p>Having an experience of being employed by different software developing companies, I have heard many times from technical people that Python is slow and doesn’t have a real threading mechanism and due to the lack of static types it’s error-prone; that some of the “basic” OOP stuff is missing there and this is more like a toy language with no real use in production environment… So I felt a deep need to write an introduction to Python for potential users, employers and to all who may be interested. It might be of great use for business owners and start-up runners as well as for technical people.</p>

<p><strong>Introduction.</strong></p>

<ol>
  <li>
    <p>“Python is a programming language that allows you to work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.” – From my personal experience the development on Python is about 3 times faster then on Java.</p>
  </li>
  <li>
    <p>“Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual machines.” – and I would add also all of <a href="http://www.python.org/download/other/">them</a>.</p>
  </li>
  <li>
    <p>“Python is free to use, even for commercial products, because of its OSI-approved <a href="http://www.python.org/psf/license/">open source license</a>.”</p>
  </li>
</ol>

<p><strong>The world is changing. Reactive Manifesto.</strong></p>

<p>First of all I would like you to introduce a <a href="http://www.reactivemanifesto.org/">reactive application manifesto</a>.</p>

<p>It has been recently created to name the changes that are remarkably  taking place in nowadays requirements to a network application. <a href="http://www.reactivemanifesto.org/">Reactive application manifesto</a> lists the rules that application has to comply with, namely – scalability, responsiveness and resilience. It clearly says that scalability and responsiveness are all about asynchronous programming models (APM).</p>

<p><strong>Responsiveness.</strong></p>

<p>A year ago I’ve written a post about <a href="../../../index.html">asynchronous programming with python</a>, where I explained the advantages of APM over threading model. There I claimed that Python is actually excels APM in respect to simplicity of code writing. Having one of the largest official <a href="https://pypi.python.org/pypi">repository</a> of open source code (<strong>36195</strong>packages as of time of writing the current post), Python can offer many different libraries that make it dead-easy to write an APM based code. While the most advanced of them is <a href="http://twistedmatrix.com/">Twisted</a> – event driven networking engine.</p>

<p><a href="https://gregorybegelman.com">Gregory Begelman</a> describes <a href="http://blog.gregorybegelman.com/crawling-the-web-with-scrapy/">here</a> how we built APM crawlers system on top of <a href="http://scrapy.org/">scrapy</a> that is being able to scrape simultaneously 2000 domains on one machine with 8 cores and 32G of RAM. In <a href="../../../index.html">this post</a> I elaborate it even further.</p>

<p><strong>Scalability and Resilience.</strong></p>

<p>Today the major players on the market such as Google, Facebook, Yahoo, Youtube and <a href="https://wiki.python.org/moin/OrganizationsUsingPython">many others</a> use Python as part of their core infrastructure.</p>

<p>Such well-known and commonly used computing systems as  <a href="http://aws.amazon.com/">Amazone Web Services</a>, <a href="https://developers.google.com/appengine/">Google AppEngine</a>, <a href="http://hadoop.apache.org/">Appache Hadoop</a> and <a href="http://discoproject.org/">Nokia Disco</a> have been integrated with Python as well.</p>

<p>Thereby, Python is perfect for reactive application model that is described above. Considering its simplicity in use and its open source nature with a mature community and huge repository, I conclude that Python is an optimal, best and the most efficient choice for today’s network application programming needs and challenges.</p>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Python" /><summary type="html"><![CDATA[Recently I have made a brief exploration of local job market and have found a simple fact – Python is greatly misunderstood and as a result – extremely underestimated. Having an experience of being employed by different…]]></summary></entry><entry><title type="html">Tips on optimizing scrapy for a high performance</title><link href="https://alexeyvishnevsky.com/2013/11/tips-on-optimizing-scrapy-for-a-high-performance/" rel="alternate" type="text/html" title="Tips on optimizing scrapy for a high performance" /><published>2013-11-02T14:00:00+02:00</published><updated>2013-11-02T14:00:00+02:00</updated><id>https://alexeyvishnevsky.com/2013/11/tips-on-optimizing-scrapy-for-a-high-performance</id><content type="html" xml:base="https://alexeyvishnevsky.com/2013/11/tips-on-optimizing-scrapy-for-a-high-performance/"><![CDATA[<p><strong>Running multiply crawlers in a single process.</strong></p>

<p>When crawling many web pages it’s important for an application to get an advantage of <a href="../../../index.html">APM</a>. Scrapy is a Python asynchronous crawling framework, that with small changes is perfectly suites this need.</p>

<p>Scrapy has a Crawler component that includes request scheduler as well as visited urls queue, together with all the configuration parameters related to how the crawling process should be performed. Thus if you want to crawl multiple domains simultaneously the best isolation level would be to create a separate Crawler for each domain. This will allow you to have a custom configuration context per domain.</p>

<p>The conventional use of scrapy is its Crawler-per-process model. However if you need to crawl 2000 domains simultaneously  on one machine, it would be very inefficient  having 2000 processes on there. So our purpose is to run multiple Crawlers within just one scrapy process.</p>

<p>Gregory Begelman describes in <a href="https://blog.gregorybegelman.com/crawling-the-web-with-scrapy/">his post</a> how we solved this problem, and how we managed to run 300 concurrent domains from only one process that took just one processor core and about only 3G of RAM.</p>

<p><strong>Bloom as a duplicate filter for visited urls.</strong></p>

<p>The default duplicate filter, that is used in scrapy for filtering visited urls, uses a list of url fingerprints – basically sha1 hashes in length of 40 characters that is 77 bytes long in Python 2.7. Lets say you have to scrape a site with 2M of pages, then your duplicates filter list might grow up to 2M * 77b = 154Mb per one Crawler. In order to be able to scrape 300 of such domains simultaneously, you will need 300 * 154Mb = 42G of memory. Fortunately there is another way – <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom Filter</a>. It’s a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. When we define it to store 2M of items with probability of false positive matches equal to 0.00001% we are getting the duplicate filter that is good enough for only 11Mb of memory. This enables us to crawl 300 domains using only 3G of memory.</p>

<p>Below is the Bloom filter for scrapy implemented with <a href="https://pypi.python.org/pypi/pybloom/1.0.2">pybloom</a></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>from pybloom import BloomFilter
from scrapy.utils.job import job_dir
from scrapy.dupefilter import BaseDupeFilter

class BLOOMDupeFilter(BaseDupeFilter):
    """Request Fingerprint duplicates filter"""

    def __init__(self, path=None):
        self.file = None
        self.fingerprints = BloomFilter(2000000, 0.00001)

    @classmethod
    def from_settings(cls, settings):
        return cls(job_dir(settings))

    def request_seen(self, request):
        fp = request.url
        if fp in self.fingerprints:
            return True
        self.fingerprints.add(fp)

    def close(self, reason):
        self.fingerprints = None
</code></pre></div></div>

<p>To enable it in your project add to the projects settings.py the following line:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Somewhere in settings.py
DUPEFILTER_CLASS = "project_name.bloom_filter.BLOOMDupeFilter"
</code></pre></div></div>]]></content><author><name>Alexey Vishnevsky</name></author><category term="Python" /><summary type="html"><![CDATA[Running multiply crawlers in a single process. When crawling many web pages it’s important for an application to get an advantage of APM . Scrapy is a Python asynchronous crawling framework, that with small changes is…]]></summary></entry></feed>