Monday, 20 May 2013

"warning: Invalid parameter passed to C runtime function."

What a frustrating thing to see an error message "warning: Invalid parameter passed to C runtime function." in debugger window without any notice, what does it mean.

I wasn't able to google any useful information, so "I'm just going to leave this here" for those who also stuck at it.

The message "Invalid parameter passed to C runtime function." is being dumped into debugger in msvcrt.dll function __invoke_watson(), using well-known OutputDebugStringA().

Well, this can be easily seen using IDA disassembler. But how we can trace, what was a reason to signal this error? Especially when debugging MinGW-compiled win32-binary in GDB debugger? Just set breakpoint at OutputDebugStringA function (typing break OutputDebugStringA) and then dump your stack (typing bt).

In may case, my program was passing NULL parameter to strcmp() function located in msvcrt.dll, so that's why it (fairly) signalled about error.

Friday, 10 May 2013

Solving Problem Euler 31 - "Coin sums" using Z3 SMT-solver

In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1£1 + 150p + 220p + 15p + 12p + 31p How many different ways can £2 be made using any number of coins?
Problem Euler 31 - Coin sums

Using MSR Z3 SMT solver for solving this is overkill, and also slow, but nevertheless, it works, showing all possible solutions as well. The piece of code for blocking already found solution and search for next, and thus, counting all solutions, was taken from here.

Constraints like "a>=0" should be present, because Z3 solver will search for solutions with negative numbers.
#!/usr/bin/python

from z3 import *

a,b,c,d,e,f,g,h = Ints('a b c d e f g h')
s = Solver()
s.add(1*a + 2*b + 5*c + 10*d + 20*e + 50*f + 100*g + 200*h == 200, 
   a>=0, b>=0, c>=0, d>=0, e>=0, f>=0, g>=0, h>=0)
result=[]

while True:
    if s.check() == sat:
        m = s.model()
        print m
        result.append(m)
        # Create a new constraint the blocks the current model
        block = []
        for d in m:
            # d is a declaration
            if d.arity() > 0:
                raise Z3Exception("uninterpreted functions are not suppported")
            # create a constant from declaration
            c=d()
            #print c, m[d]
            if is_array(c) or c.sort().kind() == Z3_UNINTERPRETED_SORT:
                raise Z3Exception("arrays and uninterpreted sorts are not supported")
            block.append(c != m[d])
        #print "new constraint:",block
        s.add(Or(block))
    else:
            print len(result)
            break
Works very slow, and this is what it produces:
[h = 0, g = 0, f = 0, e = 0, d = 0, c = 0, b = 0, a = 200]
[f = 1, b = 5, a = 0, d = 1, g = 1, h = 0, c = 2, e = 1]
[f = 0, b = 1, a = 153, d = 0, g = 0, h = 0, c = 1, e = 2]
...
[f = 0, b = 31, a = 33, d = 2, g = 0, h = 0, c = 17, e = 0]
[f = 0, b = 30, a = 35, d = 2, g = 0, h = 0, c = 17, e = 0]
[f = 0, b = 5, a = 50, d = 2, g = 0, h = 0, c = 24, e = 0]
73682 results in total.

Tuesday, 30 August 2011

Transferring voice memos from iPhone

1) Turn on voice memo synchronizing in iTunes:
http://www.gilsmethod.com/how-to-synchronize-iphone-voice-memos-with-the-itunes-library

2) Synchronize and find voice memo files in m4a format in folder:
C:\Users\Your Username\Music\iTunes\iTunes Media\Music\Unknown Artist\Unknown Album\

3) Convert them from m4a to anything you want with ffmpeg.

Wednesday, 29 June 2011

Project Euler problem 15

http://projecteuler.net/index.php?section=problems&id=15



def f (cache, posX, posY, sizeX, sizeY):

p=(posX, posY, sizeX, sizeY)
if p in cache:
return cache[p]

rt=0

# right
if posX+1 != sizeX:
rt=rt+f(cache, posX+1, posY, sizeX, sizeY)

# bottom
if posY+1 != sizeY:
rt=rt+f(cache, posX, posY+1, sizeX, sizeY)

# goal
if posX+1 == sizeX and posY+1 == sizeY:
rt=rt+1

cache[p]=rt

return rt

print (f({},0,0,21,21))

Project Euler problem 162

http://projecteuler.net/index.php?section=problems&id=162


# python 2.x

import string

digits=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']

def f2(cache, have_0=False, have_1=False, have_A=False, have_something_in_front=False, remain=0):

fn_params=(have_0, have_1, have_A, have_something_in_front, remain)
if fn_params in cache:
return cache[fn_params]

if remain==0:
if have_0 and have_1 and have_A:
return 1
else:
return 0
else:
rt=0
for d in digits:
rt=rt + f2 (cache, have_0 or ('0' in d and have_something_in_front), have_1 or ('1' in d), have_A or ('A' in d), have_something_in_front or (d != '0'), remain-1)

cache[fn_params]=rt
return rt

print (string.upper(hex(f2({}, remain=16))[2:][:-1]))

Thursday, 3 February 2011

boost::spirit vs. atol()

Code taken from this post and modified to check a list of random values...


#include <time.h>

#include <boost/spirit/include/qi.hpp>
#include <iostream>

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include <list>
#include <string>

std::list<int> test_i;
std::list<std::string> test_s;

void test_spirit(int rep)
{
int val=0;
time_t t=time(NULL);
printf ("test_spirit() begin\n");

for (int r=0; r<rep; r++)
{
std::list<int>::iterator i=test_i.begin();
for(std::list<std::string>::iterator s=test_s.begin(); s!=test_s.end(); s++)
{
boost::spirit::qi::parse ((*s).begin(), (*s).end(), boost::spirit::int_, val);

if (val != *i)
std::cout << "Spirit Errror! val=" << val << std::endl;
i++;
}
};
printf ("test_spirit() end. seconds elapsed=%d\n", time(NULL)-t);
}

void test_atol(int rep)
{
long val=0;
time_t t=time(NULL);

printf ("test_atol() begin\n");

for (int r=0; r<rep; r++)
{
std::list<int>::iterator i=test_i.begin();
for(std::list<std::string>::iterator s=test_s.begin(); s!=test_s.end(); s++)
{
val=atoi((*s).c_str());
if (val != *i)
std::cout << "Atoi Errror! val=" << val << std::endl;
i++;
}
};

printf ("test_atol() end. seconds elapsed=%d\n", time(NULL)-t);
}

int main(int argc, char *argv[])
{
printf ("generating test\n");
for (int i=0; i<5000000; i++)
{
int r=rand();
test_i.push_back (r);
test_s.push_back(str(boost::format ("%d") % r ));
};
test_atol(100);
test_spirit(100);
return 0;
}


Boost 1.45, MSVC 2008, compiling with /Ox flag, results:


generating test
test_atol() begin
test_atol() end. seconds elapsed=34
test_spirit() begin
test_spirit() end. seconds elapsed=50

Thursday, 11 February 2010

237 Robert Fripp's Aphorisms from http://www.dgmlive.com/


"Tomorrow" is the first lie of the Devil.
A beginning is invisible.
A completion is a new beginning.
A decision changes the world.
A discipline that does not lead to a compassionate practice may be said to have failed.
A function of language is to disclose. An effect is to reveal.
A lie divorces who we are from what we are.
A mistake is always forgivable, rarely excusable and never acceptable.
A principle is an instruction in qualitative endeavour.
A principle is universal.A rule is specific.A law is invariable.
A test of our understanding is whether we can apply it in practice.
Abandon concern for hitting the right note.Then, hit the right note.
Accept nothing less than what is right.
Act always in accordance with conscience.
Act from principle.Move from intention.
Act in accordance with time, place and person.
Act in private as if your behaviour were known in public.
Act with courtesy.Otherwise, be polite.
Address the process rather than the outcome.Then, the outcome becomes more likely.
An artist acts with the assumption of innocence within a field of experience.
An end may be a finish, a conclusion or a completion.
An honest society is an ordered society.An ordered society is an efficient society.An efficient society is a richer society. A richer society may support a poorer society.
Answers will come through the guitar.
Any fool can play something difficult.
Any success carries with it an opportunity, a responsibility and an obligation.
Anything within a performance is significant, whether intentional or not.
Artistry repeats the unrepeatable.
Assume the virtue.
Avoid celebrity.
Be very careful about the beginning.Then, be very careful about the end.Then, be very careful about the middle.
Beauty is the reflection of the appearance of truth.Better to seek truth than the reflection of its appearance.But better to seek beauty than nothing.
Before we do something, we do nothing.
Before we move from A to B, better to know we're at A.
Begin with the possible and move gradually towards the impossible.
Being a slob is hard labour.
Being is a measure of our coherence.
Better to be present with a bad note than absent from a good note.
Breathing is optional.
Change one small part and the whole is changed.
Commitments are to be honoured.
Comparison with others is a mark of the fool.
Conscience is utterly impersonal.
Craft is a universal language.
Craft maintains skill. Discipline maintains craft.Craft follows the tradition. Discipline maintains the tradition.Music creates the tradition.
Creative work is serious play.
Cynicism is death to the artist.
Define the aim positively.Do not define the aim negatively.
Define the aim simply, clearly, briefly, positively
Discard the superfluous.
Discharge one small task superbly.
Discipline is a vehicle for joy.
Discipline is not an end in itself, only a means to an end.
Distrust anyone who wants to teach you something.
Distrust those who profess altruism.
Don't be helpful: be available.
Duration is subjective.
Each part does the work of that part, and no other.
Effective action begins when we cease to concern ourselves with being effective.
Efficiency: the right amount of the right quality of energy, in the right place at the right time, doing what is right.
Establish the principle.
Even genius requires a competent technique.
Everything we are is revealed in our playing.
Expect nothing.
Expectation is a prison.
Expectation is the prediction that history will repeat itself, exactly, precisely.
Fear is a preparation for failure.
Good habit is necessary, bad habit is inevitable.
Gradual transitions take place suddenly.
Health is a measure of our wholeness.
Hearing transforms sound into music.
Helpful people are a nuisance.
Honour necessity.
Honour sufficiency.
Honour the role.Respect the person.
How we hold our pick is how we organise our life.
Humour is not permitted.
If a quality is present, it is clearly recognisable and may be named.
If in doubt, consult tradition.If still in doubt, consult your experience.If still in doubt, consult your body.
If we can't play away from the instrument, we can't play with the instrument.
If we can ask our body to do nothing for half an hour, perhaps we can ask our body to do something for half an hour.
If we can define our aim, we are halfway to achieving it.
If we don't know where we're going, we'll probably get there.
If we wish to know, breathe the air around someone who knows.
If you wish to change the world, better first to know the world you wish to change.
In naming myself, I recognise who I am.
In popular culture, our musicians sing to us in our own voice.In mass culture they shout what we want to hear.
In popular culture, the musician calls on the highest part in all of us.In mass culture, the musician addresses the lower parts of what we are.
In the creative act, the Creation continues.
In the creative leap, history waits outside.
In tuning a note we are tuning ourselves.
Intentional action generates intentional results and unforeseeable repercussions.Unintentional action generates unintended consequences and inevitable repercussions.
Intentional poverty is fine.Unintentional poverty is wretched.
Interrogate the error.
It is difficult to exaggerate the power of habit.
It is not asked of us that we never fall over.It is asked of us that we always get up.
It is not necessary to be cheerful.It is not necessary to feel cheerful.But look cheerful.
Just below the surface of our everyday world lie riches.
Let us embrace our mistakes as friends and teachers.
Let us find clean and cheerful friends.
Life is often desperate, but never hopeless.
Life is too short to take on the unnecessary.
Like and dislike are cheap.
Listen also with the ears of the heart.
Listening changes what we are listening to.
Listening is a craft.Hearing is an art.
Listening is how we eat music.Hearing is how we digest it.
Local events have global repercussions.
Mastery acts on what is below.Artistry submits to what is above.
May the quality with which we live our life honour the lives of our parents and mentors.
May we have the clarity to see our work, the courage to embrace it, and the capacity to discharge it.
May we have the clarity to see what is required of us, the courage to accept it, and the capacity to discharge it.
May we have the courage to fail.
May we trust the inexpressible benevolence of the creative impulse.
May we wish for others what we wish for ourselves.
Money is not a problem, only a difficulty.
Moving forward feels like moving forward.It also feels like moving backwards, and standing still.
Music changes when people hear it.
Music is a benevolent presence constantly and readily available to all.
Music is a powerful and direct teacher which speaks to us all, to the degree that we are able to hear.
Music is a quality, organised in sound and in time.
Music is silence, singing.
Music is the architecture of silence.
Music is the cup which holds the wine of silence.Sound is that cup, but empty.Noise is that cup, but broken.
Music so wishes to be heard that it calls on some to give it voice and some to give it ears.
Necessary repercussions are possible.Inevitable repercussions are expensive.Unnecessary repercussions are dangerous.
Necessity is a measure of aim.
Necessity is never far from what is real.
Never become so popular that the public take an interest in you.
Nothing is compulsory, but some things are necessary.
Nothing worthwhile is achieved suddenly.
Offer no violence.
Our enemy is our friend.
Our living is as rich as our attention is available.
Perfection is impossible.But I may choose to serve perfection.
Performance is impersonal yet intimate.
Performance is inherently unlikely.
Playing fast is easier than playing slow.
Power is the capacity to access what is possible.
Process is Intelligence getting to know itself.
Quiet is the absence of sound, silence the presence of silence.
Relaxation is necessary tension.Tension is unnecessary tension.
Relaxation is never accidental.
Rely on what someone does, not what they claim to do.
Remain in hell without despair.
Remember to play.
Right action moves from principle.
Rightness is its own necessity.
Signposts are useful when you know where you're going.
Silence is a bridge between worlds.
Silence is a distant echo of the approach of the Muse.
Silence is an invisible glue.
Silence is not silent.
Silence is the field of creative musical intelligence that dwells in the space between the notes, and holds them in place.
Small additional increments are transformative.
Some things protect themselves by being what they are.
Sometimes God hides.
Space has its own rules and determining conditions.
Suffer cheerfully.
Suffering is necessary, unnecessary or voluntary.
Suffering is our experience of the distance between what we are and who we wish to become.
Suffering of quality is invisible to others.
The act of music is the music.
The artist is a bridge between the possible, the impossible, and the actual.
The attitude that life owes us something, if not everything, encourages life to thwart our endeavours.
The audience is mother to the music.
The centre of discipline: the degree to which we are able to hold ourselves in front of a challenge.
The concern of the musician is music.The concern of the professional musician is business.
The creative impulse animates whatever instrument is placed at its disposal.
The end is a finish, a conclusion or a completion.
The foundation of learning is play.
The future is what the present can bear.
The highest quality of attention we may give is love.
The mind leads the hands.
The more failures, the more successes.
The musician and audience are parents to the music.
The musician has three disciplines: the disciplines of the hands, the head and the heart.
The necessary is possible.The optional is expensive.The unnecessary is unlikely.
The only contribution we make is the quality of our work.
The only person who doesn't make mistakes is God.
The performer can hide nothing, even the attempt to hide.
The presence of absence is an entry into loss.
The problem with knowing what we want is we just might get it.
The quality of a person is revealed in their conduct in front of sex, money and the use of time.
The quality of our perceptions determines the quality of our judgement. Our judgement determines how we interact with the world.How we interact with the world changes the world. So, the quality of our perceptions changes the world.
The quality of the question determines the quality of the answer.
The question is its answer.
The right thing at the wrong time is wrong.The wrong thing at the right time may be right.The right thing at the right time is beautiful.
The science is in knowing, the art in perceiving.
The simplest is the most difficult to discharge superbly.
The unity of all things is experienced through the feelings.
The way we describe our world shows how we think of our world. How we think of our world governs how we interpret our world.How we interpret our world directs how we participate in the world. How we participate in the world shapes the world.
The work of one supports the work of all.
There's more to hearing than meets the ear.
There are few things as convincing as death to remind us of the quality with which we live our life.
There are no mistakes, save one: the failure to learn from a mistake.
There are three kinds of repercussions: the necessary, the unnecessary and the inevitable.
There is only one musician, in many bodies.
Things are not as bad as they seem.They are worse than that.They are also better than that.
This life may not provide justice, but it is fairer than we might like it to be.
Three ways to discover our faults: ask a friend; ask an enemy; recognise a fault in others.
To try is to fail.
Trust music.
Trust the process.
Turn a seeming disadvantage to your advantage.The greater the seeming disadvantage, the greater the possible advantage.
Understanding changes what we understand.
Understanding is simple. Knowing is complicated.
We'll never get rich by hard work.But, we'll never get rich without it.
We also learn by osmosis.
We are held responsible for our actions, whether intentional or not.
We begin again, constantly.
We begin by doing nothing.Then, we move to doing something.
We begin where we are.
We can't go far on enthusiasm, but we don't go far without it.
We have the right to choose our form of suffering.
We have three rights: the right to work, the right to pay to work, and the right to suffer the consequences of our work.We have three obligations: the obligation to work, the obligation to pay to work, and the obligation to suffer the consequences of our work.
We know others to the extent that we know ourselves.
We may do whatever we like, providing we can pay the bill.
We may not have an equality of talent. We may not have an equality of experience.But we may be equal in aspiration. We can be equal in commit-ment.
We may understand our knowing, but we can't know our understanding.
We must be able to play in our sleep.Because usually we do.
We only have what we give away.
We pay our own tab.
We perceive our perceptions.
We recognise in others what we know most deeply in ourselves.
Welcome the unexpected, but not the arbitrary.
What is right accords with principle.
What we hear is the quality of our listening.
What we hear is the way that we hear.
When a musician believes that music is a commodity, music dies in them.
When a record company makes a mistake, the artist pays for it.When a manager makes a mistake, the artist pays for it.When the artist makes a mistake, the artist pays for it.
When stuck, increase the complexity.
When we act as we like, we may get what we want.But not what we need.
When we have nothing to say, it is very hard to say nothing.When we have nothing to do, it is very hard to do nothing.
When we recognise a fault in others, we recognise a fault in ourselves.
Where we're going is how we get there.If where we're going is how we get there, we are already where we're going.
With commitment, all the rules change.
With craft the musician can copy something old.With discipline the musician may copy something new.