class ProducerPipe:
   """Producer-driven pipe: consumer will consume as many values as Producer
   can produce(). Producer terminates by calling last(), and consumer confirms
   or initiates termination by calling finish(), passing an Exception, if
   termination is abnormal."""
Read more... )

def consumer(pp):
         while 1: # would be nice if we could use async for
            x = yield pp.consume()
            print x
      except StopIteration:
         print 'consumer done'
   except Exception as e:
      print e

def producer():
      pp = ProducerPipe()

      print 'producer pipe is ready'
      ioloop.spawn_callback(consumer, pp)
      print 'spawned consumer'
      yield pp.produce('x')
      print 'produced x'
      yield pp.produce('y')
      print 'produced y'
      yield pp.produce('z')
      yield sleep(0.1)
      print 'produced z'
      yield pp.last()
      print 'last done'

      print 'producer done'
   except Exception as e:
      print e
Redefining Euro-Atlantic Values: Russia's Manipulative Techniques

In Russia the concept is associated more with ‘free will’, meaning that one should be free to be the only master of oneself. As stated in the report, The West in Russian Mentality, this concept in Western languages can be directly translated as will, volonte, wille. According to the Russian philosopher Fedotov, it means ‘to be capable of living according to your own will, without being dependent on any social restrictions— norms or laws. This type of freedom usually reflects avoidance (escapism), but not a way to found a new social order’.

Russian citizens are more likely to perceive voting as their duty to the state, rather than a mechanism to control state power and elect representatives.


First, there is a deep chasm between existing and ideal values systems in Russian society.


The problem lies in society itself, which is more inclined to wait passively for social equality to develop on its own.


Russians, however, mentioned ‘diligence’ as the most important value...tolerance in Russian society isn’t even considered to be an actual value as it only garnered 7.3% of popular support.


In Russia the army enjoys the greatest trust, but it shares first place with the church, both of which enjoy similarly high support—63%. This reveals a disposition towards stability and order in the daily and spiritual life. It should not go unmentioned that in Russia, trust in the army is combined with a low demand for civic control of the army, 27% according to research carried out by PEW in 2011.

На думку спадає князівсько-дружинний уклад.
Being subversively silly, like Monty Python:

Petition for Sir David Attenborough to change his name to Boaty McBoatface signed by 3741 thus far.

Read Barry McGuinness' answer to What is the most British thing ever? on Quora
  • Usain Boat
  • Not The Titanic
  • Clifford The Big Red Boat
Unfortunately, the research council chose to ignore the public vote and opted to name the ship after the well known British naturalist Sir David Attenborough.
Надійшла вимога переписати
result = sum([x != y for x,y in zip(a, b)])

для зручності як:
result = 0
for x, y in zip(a,b):
  result |= ord(x) ^ ord(y)
Bad English and tall stories are all part of a plan to filter out those who will not go all the way:
Троє людей прийшли до мудреця, щоб дізнатись, хто з них найрозумніший. Мудрець запропонував задачу: "Я зав'яжу вам очі, намалюю на чолі синє або зелене коло, а потім зніму пов'язки. Якщо бачите синє коло, піднімайте руку. Перший з вас, хто скаже колір кола на їхньому чолі і є найрозумнішим із вас"

Мудрець зав'язав їм очі, і намалював кожному з них синє коло. Коли пов'язку зняв, всі вони, звичайно ж, підняли руки, бо побачили синє коло на чиємусь чолі. Поміркувавши деякий час один з них і каже: "У мене на чолі синє коло".

Як він дізнався?

ruby pearls

Dec. 7th, 2016 02:20 pm
2.2.0 :004 > ':xyz'.split(/:/)[0]
 => "" 
2.2.0 :005 > ''.split(/:/)[0]
 => nil
2.2.0 :006 > 'xyz'.split(/:/)[0]
 => "xyz"

2.2.0 :001 > weak_key = lambda {|c| c.split(/:/, 2)[0]}
2.2.0 :002 > weak_key('xyz:1986')
NoMethodError: undefined method `weak_key' for main:Object

2.2.0 :003 > def weak_key(x)
2.2.0 :004?>   puts "blah"
2.2.0 :005?>   end
 => :weak_key 
2.2.0 :006 > def xyz(x)
2.2.0 :007?>   def weak_key(y)
2.2.0 :008?>     puts x+y
2.2.0 :009?>     end
2.2.0 :010?>   puts "yo"
2.2.0 :011?>   end
 => :xyz 
2.2.0 :012 > weak_key('b')
 => nil 
2.2.0 :013 > xyz('b')
 => nil 
2.2.0 :014 > weak_key('c')
NameError: undefined local variable or method `x' for main:Object
	from (irb):8:in `weak_key'
	from (irb):14
	from /Users/alex/.rvm/rubies/ruby-2.2.0/bin/irb:11:in `<main>'


After endianness, character encodings is probably the next pet project of any decent standard committee.
I have joined my current company to get better exposure to CPS, actors, event-driven programming. What I have found is that strict reasoning about the program's correctness requires a lot more effort: things that would be guaranteed by program order, are no longer guaranteed; more over, new things can happen apparently concurrently, in what otherwise would have been a "single-threaded" program.

Who can share their experiences on this? I heard a few people praising actors as a model that simplifies concurrency.

Suppose, there is an event-driven SMTP server:
smtp.on('mail', …);
smtp.on('rcpt', …);
smtp.on('data’, …);
smtp.on('message-start', (stream) -> stream.on('end', X));
smtp.on('message-end', Y);
smtp.socket.on('error', Z);

All of these things are technically concurrent. They are ordered only as far as the event-loop exposes the events in the same order in which they arrive, and as far as the underlying SMTP library orders events after seeing an ACK to the previous event. But errors are completely concurrent (hello, Yoneda and assertions about isomorphism between A and (A→⊥)→⊥?). And message body stream 'end' event and 'message-end' event of SMTP library occur in some unknown order. So X, Y, Z appear in arbitrary order, now you need barriers and execution time goal.

The same SMTP server without CPS would look like this:
  … = smtp.expectCommand('mail');
  while((C = smtp.expectCommand(Either 'rcpt' 'data')) == Left 'rcpt'){
  stream = smtp.expectCommand('message-start');
  … = smtp.expectCommand('message-end');
} catch(IOException ioe) {

I am not saying it is simpler, but, for example, there certainly is no question about X continuing execution, if Z occurs, so you don't need to cater for this eventuality.

How do you deal with the complexity introduced by event-driven style?
2.2.0 :001 > x = "\xE3\x81\x82"
 => "あ" 
2.2.0 :002 > y = x.encode("iso-2022-jp")
 => "\e\x24\x42\x24\x22\e\x28\x42" 
2.2.0 :003 > y[0]
 => "\e"
2.2.0 :004 > x[0]
 => "あ"
Якби галактика Андромеди була достатньо яскрава, вона б виглядала у порівнянні з місяцем ось так:$File/1186208-6_03102016_1186208-6.PDF?OpenElement

2) отказа Соединенных Штатов Америки от недружественной
в отношении Российской Федерации, который должен

а) в отмене закона Соединенных Штатов Америки 2012 года (закон
Сергея Магнитского) и направленных против России положений закона
Соединенных Штатов Америки 2014 года о поддержке свободы Украины;
Помимо действий, направленных на изменение военно-
стратегического баланса, США предпринимают меры по
расшатыванию экономики Российской Федерации и нарушению прав
российских граждан
Challenge Exercise: Prove that our original implementation of up' does not play nice with extend. In other words, find a counter-example that proves the following equation false:
extend (\t' -> p (up' t')) t = extend p (up' t)

What does he mean?

1. There is no need to look for counter-example, since it is false for any t, if we were to compare literally.

2. His previous statements about up' vs extend up were based on behavioural equality of the two, so motivating these challenges to find out which one was "correct". The behaviour of both sides is identical for all t. No? I tried even some cleverly placed undefined.
Can someone walk me through the first paragraph of the section on polymorphic equality?
The programming language Miranda provides a polymorphic equality function, with type:
(=): ∀ X, X → X → Bool

Applying parametricity to the type of (=) yields, for all a : A → A'
for all x, y ∈ A, (x =A y) = (a x =A' a y).
This is obviously false

Then they also say "This is not a contradiction to the parametricity theorem".

Smells like bullshit. If the statement they've got is the result of applying parametricity, then it is a contradiction to the theorem. But also I have my doubts about how they have applied the theorem. Everywhere else there is no "=" between "(x =A y)" and what follows; only a "if...then".
> [[1],[2,3]].reduce((a,b) => a.concat(b), [])
[ 1, 2, 3 ]
>[1], [2,3])
[ 1, 2, 3 ]
> [[1],[2,3]].reduce(, [])
TypeError: [[1],[2,3]].reduce is not a function
    at Array.reduce (native)
    at repl:1:13
Тут хтось поскаржився, що порядок обчислень в Х-і не зрозумілий. Ну, ось вам імперативний варіант, не обляпайтесь:
function walk2(preorder, inorder) {
  let node = {parent: {}};
  while(preorder.length !== 0) {
    if (preorder[preorder.length - 1] === node.parent.value) {
      node.parent.left = node;
      node = node.parent;
    node.parent = {value: inorder.pop(), parent: node.parent, right: node};
    node = {parent: node.parent};
  return node;
Мені аж цікаво, як я раніше в такому розбирався?
Page generated May. 27th, 2017 04:25 am
Powered by Dreamwidth Studios