State based testing(state charts) & transition sequences - testing

I am really stuck with some state based testing concepts...
I am trying to calculate some checking sequences that will cover all transitions from each state and i have the answers but i dont understand them:
alt text http://www.gam3r.co.uk/1m.jpg
Now the answers i have are :
alt text http://www.gam3r.co.uk/2m.jpg
I dont understand it at all. For example say we want to check transition a/x from s1, wouldnt we do ab only? As we are already in s1, we do a/x to test the transition to s2, then b to check we are in the previous right state(s1)? I cant understand why it is aba or even bb for s1...
Can anyone talk me through it?
Thanks

There are 2 events available in each of 4 states, giving 8 transitions, which the author has decided to test in 8 separate test sequences. Each sequence (except the S1 sequences - apparently the machine's initial state is S1) needs to drive the machine to the target state and then perform either event a or event b.
The sequences he has chosen are sufficient, in that each transition is covered. However, they are not unique, and - as you have observed - not minimal.
A more obvious choice would be:
a b
ab aa
aaa aab
ba bb
I don't understand the author's purpose in adding superfluous transitions at the end of each sequence. The system is a Mealy machine - the behaviour of the machine is uniquely determined by the current state and event. There is no memory of the path leading to the current state; therefore the author's extra transitions give no additional coverage and serve only to confuse.
You are also correct that you could cover the all transitions with a shorter set of paths through the graph. However, I would be disinclined to do that. Clarity is more important than optimization for test code.

Related

Bitcoin Blockchain - Verification process

As the title states, basically my question is about the blockchain verification. I know whats a block chain and basically understood how mining is working, except once simple thing.
Let's say we have 2 guys, Bob and Adam.
Blockchain:
|1|-|2|-|3|-{4} - Bob Chain
|1|-|2|-|3|-{4} - Adam Chain
Assume both Bob and Adam found a new block, but it will not be verified until someone finds a next block. So my questions is whats is happening in a situation if Adam will find a block |5| first. Will Bob get his reward for finding a block? Or it means if Adam found one block, he has to find the next one which is extremely difficult without a huge network of computational resources in order to verify his previous block |4| and get reward for block 4 of 12.5 bitcoins, because the nodes will only accept the longest blockchain? I hope I clearly illustrated the picture. I've tried to find the answer in different videos and materials but somehow this aspect was put aside. If my assumption is true, it means there is no way how can a single person to earn anything from mining without a huge network ?
First of all, in Bitcoin when someone creates a block, he broadcasta it to the rest ot the network. As you said, if there are two people that create the block at the same time, they will broadcast it. So, you will get two blocks at the same time. Although you save both blocks, you will try to mine one of them. After some time, one of the two branches will be longer, so you will delete the second one.
The miners of the Blockchain will create some blocks and a branch will be longer after some time.
In Blockchain, a block is considered well when it has 100 blocks (I d0n't know exactly how many) above of it. So, the reward is taken after 100 blocks, not before.
Who out of Adam or Bob gets the reward depends on whose block remains as part of the 'Best chain' eventually. This in turn partly depends on consensus rules and partly on how the things transpired. This is explained as follows
Adam and Bob claimed that they found the block first by broadcasting to peers almost at same time.
Let's presume that a peer named 'ITWala' saw these 2 blocks which would be at same height. Assuming Adam's block reached ITWala's node first. So this would lead to something known as 'forking' in block chain terminology and is quite normal to occur.
**Chain status on ITWala's node leading to forking **
Block1 --> Block 2 --> Block 3 --> Block 4 (Adam's Block)
|
|--- Block 4 (Bob's Block)
One of following can happen:
Case 1 - For sake of simplicity, assume that Bob is the only one making claim for block 5. Now 'ITWala' receives block 5. He tries to make the chain longer by trying to fit at one end of the fork created from Block 4 from Adam. It does not fit because the hash of the previous block would not match.
Result
Fork at the end of Adam's block is discarded. Fork with Bob's block becomes active chain and thus Bob becomes the winner of 4 as well as 5 for award.
Case 2:
Block 5 is created by 'ITWala' or some peer of ITWala who synced up with copy on ITWala's node.
Result: In this case, ITWala would use Adam's block to activate the best chain as it arrived first making him the winner for block 4. Block 5 is awarded to ITWala
There can be more combinations. However point here is that the block that remains in best chain wins the award.

Understanding Google Code Jam 2013 - X Marks the Spot

I was trying to solve Google Code Jam problems and there is one of them that I don't understand. Here is the question (World Finals 2013 - problem C): https://code.google.com/codejam/contest/2437491/dashboard#s=p2&a=2
And here follows the problem analysis: https://code.google.com/codejam/contest/2437491/dashboard#s=a&a=2
I don't understand why we can use binary search. In order to use binary search the elements have to be sorted. In order words: for a given element e, we can't have any element less than e at its right side. But that is not the case in this problem. Let me give you an example:
Suppose we do what the analysis tells us to do: we start with a left bound angle of 90° and a right bound angle of 0°. Our first search will be at angle of 45°. Suppose we find that, for this angle, X < N. In this case, the analysis tells us to make our left bound 45°. At this point, we can have discarded a viable solution (at, let's say, 75°) and at the same time there can be no more solutions between 0° and 45°, leading us to say that there's no solution (wrongly).
I don't think Google's solution is wrong =P. But I can't figure out why we can use a binary search in this case. Anyone knows?
I don't understand why we can use binary search. In order to use
binary search the elements have to be sorted. In order words: for a
given element e, we can't have any element less than e at its right
side. But that is not the case in this problem.
A binary search works in this case because:
the values vary by at most 1
we only need to find one solution, not all of them
the first and last value straddle the desired value (X .. N .. 2N-X)
I don't quite follow your counter-example, but here's an example of a binary search on a sequence with the above constraints. Looking for 3:
1 2 1 1 2 3 2 3 4 5 4 4 3 3 4 5 4 4
[ ]
[ ]
[ ]
[ ]
*
I have read the problem and in the meantime thought about the solution. When I read the solution I have seen that they have mostly done the same as I would have, however, I did not thought about some minor optimizations they were using, as I was still digesting the task.
Solution:
Step1: They choose a median so that each of the line splits the set into half, therefore there will be two provinces having x mines, while the other two provinces will have N - x mines, respectively, because the two lines each split the set into half and
2 * x + 2 * (2 * N - x) = 2 * x + 4 * N - 2 * x = 4 * N.
If x = N, then we were lucky and accidentally found a solution.
Step2: They are taking advantage of the "fact" that no three lines are collinear. I believe they are wrong, as the task did not tell us this is the case and they have taken advantage of this "fact", because they assumed that the task is solvable, however, in the task they were clearly asking us to tell them if the task is impossible with the current input. I believe this part is smelly. However, the task is not necessarily solvable, not to mention the fact that there might be a solution even for the case when three mines are collinear.
Thus, somewhere in between X had to be exactly equal to N!
Not true either, as they have stated in the task that
You should output IMPOSSIBLE instead if there is no good placement of
borders.
Step 3: They are still using the "fact" described as un-true in the previous step.
So let us close the book and think ourselves. Their solution is not bad, but they assume something which is not necessarily true. I believe them that all their inputs contained mines corresponding to their assumption, but this is not necessarily the case, as the task did not clearly state this and I can easily create a solvable input having three collinear mines.
Their idea for median choice is correct, so we must follow this procedure, the problem gets more complicated if we do not do this step. Now, we could search for a solution by modifying the angle until we find a solution or reach the border of the period (this was my idea initially). However, we know which provinces have too much mines and which provinces do not have enough mines. Also, we know that the period is pi/2 or, in other terms 90 degrees, because if we move alpha by pi/2 into either positive (counter-clockwise) or negative (clockwise) direction, then we have the same problem, but each child gets a different province, which is irrelevant from our point of view, they will still be rivals, I guess, but this does not concern us.
Now, we try and see what happens if we rotate the lines by pi/4. We will see that some mines might have changed borders. We have either not reached a solution yet, or have gone too far and poor provinces became rich and rich provinces became poor. In either case we know in which half the solution should be, so we rotate back/forward by pi/8. Then, with the same logic, by pi/16, until we have found a solution or there is no solution.
Back to the question, we cannot arrive into the situation described by you, because if there was a valid solution at 75 degrees, then we would see that we have not rotated the lines enough by rotating only 45 degrees, because then based on the number of mines which have changed borders we would be able to determine the right angle-interval. Remember, that we have two rich provinces and two poor provinces. Each rich provinces have two poor bordering provinces and vice-versa. So, the poor provinces should gain mines and the rich provinces should lose mines. If, when rotating by 45 degrees we see that the poor provinces did not get enough mines, then we will choose to rotate more until we see they have gained enough mines. If they have gained too many mines, then we change direction.

Turing Machines

I'm reading a book on Languages & Automata and I'm not understanding Turing Machines. I've taught myself about DFA's NFA's and Pushdown Automata without any problems. Can someone please explain what this is doing?
B = {w#w|w ∈ {0, 1}*}
The following figure contains several snapshots of Ml 's tape while it is computing
in stages 2 and 3 when started on input 011000#011000.
Thanks alot!
"Imagine an endless row of hotel rooms, and each room contains a lightbulb and a switch that controls it. Initially, all the rooms are dark. A robot starts at one of the rooms, and has the ability to operate switches and move to adjacent rooms.
The robot has several states that it can be in, and each state determines what it should do based on whether the current room is light or dark. For example, a robot's rules could include these states:
The "scared" state:
If the room is dark, turn on the light and move to the room to the left.
If the room is light, do nothing and go to the "normal" state.
The "normal" state:
If the room is light, turn off the light and move to the room on the right.
Otherwise, go to the "scared" state.
One special state is the "stop" state. When the robot finds itself in this state, the process is complete.
Suppose a robot has n states (not including the "stop" state), and it stops. What is the maximum number of light rooms at this point?
This system is in direct allegory to Turing machines. The hotel is the tape, the robot is the Turing machine, and dark rooms and light rooms are 0 and 1 cells."
It is from googology wiki. I gave an idea to it, but, of course, this text has been improved since me.
Turing machine is a hypothetical machine with a tape where symbols are stored. It can have multiple heads that can read symbols from the tape or write symbols to the tape.
Now your grammar says B = {w#w|w ∈ {0, 1}*}, that is any string of the form "w#w", where w is any combination of 0's and 1's or none at all. So let's say w = 011000 for this particular example. The resulting string will be 011000#011000 and your turing machine will be verifying if it follows this grammar.
Your turing machine has one head in this case. It starts at the beginning of string. Reads the first character which is 0. Mark it "x": meaning I've read this. Then goes immediately after the # and checks if what it just read is matching. In this case it's 0 as well so it marks it as matching "x". It then goes back to previous position and does the same for next character. It keeps doing this until it reaches #. When it reads hash or #, it checks for the end of the string and if it is the end of string, it accepts this string saying yes this follows the given grammar.

Markov decision process - how to use optimal policy formula?

I have a task, where I have to calculate optimal policy
(Reinforcement Learning - Markov decision process) in the grid world (agent movies left,right,up,down).
In left table, there are Optimal values (V*).
In right table, there is sollution (directions) which I don't know how to get by using that "Optimal policy" formula.
Y=0.9 (discount factor)
And here is formula:
So if anyone knows how to use that formula, to get solution (those arrows), please help.
Edit: there is whole problem description on this page:
http://webdocs.cs.ualberta.ca/~sutton/book/ebook/node35.html
Rewards: state A(column 2, row 1) is followed by a reward of +10 and transition to state A', while state B(column 4, row 1) is followed by a reward of +5 and transition to state B'.
You can move: up,down,left,right. You cannot move outside the grid or stay in same place.
Break the math down, piece by piece:
The arg max (....) is telling you to find the argument, a, which maximizes everything in the parentheses. The variables a, s, and s' are an action, a state you're in, and a state that results from that action, respectively. So the arg max (...) is telling you to find an action that maximizes that term.
You know gamma, and someone did the hard work of calculating V*(s'), which is the value of that resulting state. So you know what to plug in there, right?
So what is p(s,a,s')? That is the probability that, starting from s and doing a, you end in some s'. This is meant to represent some kind of faulty actuator-- you say "go forward!" and it foolishly decides to go left (or two squares forward, or remain still, or whatever.) For this problem, I'd expect it to be given to you, but you haven't shared it with us. And the summation over s' is telling you that when you start in s, and you pick an action a, you need to sum over all possible resulting s' states. Again, you need the details of that p(s,a,s') function to know what those are.
And last, there is r(s,a) which is the reward for doing action a in state s, regardless of where you end up. In this problem it might be slightly negative, to represent a fuel cost. If there is a series of rewards in the grid and a grab action, it might be positive. You need that, too.
So, what to do? Pick a state s, and calculate your policy for it. For each s, you're going have the possibility of (s,a1), and (s,a2), and (s,a3), etc. You have to find the a that gives you the biggest result. And of course for each pair (s,a) you may (in fact, almost certainly will) have multiple values of s' to stick in the summation.
If this sounds like a lot of work, well, that's why we have computers.
PS - Read the problem description very carefully to find out what happens if you run into a wall.

What are the most hardcore optimisations you've seen?

I'm not talking about algorithmic stuff (eg use quicksort instead of bubblesort), and I'm not talking about simple things like loop unrolling.
I'm talking about the hardcore stuff. Like Tiny Teensy ELF, The Story of Mel; practically everything in the demoscene, and so on.
I once wrote a brute force RC5 key search that processed two keys at a time, the first key used the integer pipeline, the second key used the SSE pipelines and the two were interleaved at the instruction level. This was then coupled with a supervisor program that ran an instance of the code on each core in the system. In total, the code ran about 25 times faster than a naive C version.
In one (here unnamed) video game engine I worked with, they had rewritten the model-export tool (the thing that turns a Maya mesh into something the game loads) so that instead of just emitting data, it would actually emit the exact stream of microinstructions that would be necessary to render that particular model. It used a genetic algorithm to find the one that would run in the minimum number of cycles. That is to say, the data format for a given model was actually a perfectly-optimized subroutine for rendering just that model. So, drawing a mesh to the screen meant loading it into memory and branching into it.
(This wasn't for a PC, but for a console that had a vector unit separate and parallel to the CPU.)
In the early days of DOS when we used floppy discs for all data transport there were viruses as well. One common way for viruses to infect different computers was to copy a virus bootloader into the bootsector of an inserted floppydisc. When the user inserted the floppydisc into another computer and rebooted without remembering to remove the floppy, the virus was run and infected the harddrive bootsector, thus permanently infecting the host PC. A particulary annoying virus I was infected by was called "Form", to battle this I wrote a custom floppy bootsector that had the following features:
Validate the bootsector of the host harddrive and make sure it was not infected.
Validate the floppy bootsector and
make sure that it was not infected.
Code to remove the virus from the
harddrive if it was infected.
Code to duplicate the antivirus
bootsector to another floppy if a
special key was pressed.
Code to boot the harddrive if all was
well, and no infections was found.
This was done in the program space of a bootsector, about 440 bytes :)
The biggest problem for my mates was the very cryptic messages displayed because I needed all the space for code. It was like "FFVD RM?", which meant "FindForm Virus Detected, Remove?"
I was quite happy with that piece of code. The optimization was program size, not speed. Two quite different optimizations in assembly.
My favorite is the floating point inverse square root via integer operations. This is a cool little hack on how floating point values are stored and can execute faster (even doing a 1/result is faster than the stock-standard square root function) or produce more accurate results than the standard methods.
In c/c++ the code is: (sourced from Wikipedia)
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1); // Now this is what you call a real magic number
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
A Very Biological Optimisation
Quick background: Triplets of DNA nucleotides (A, C, G and T) encode amino acids, which are joined into proteins, which are what make up most of most living things.
Ordinarily, each different protein requires a separate sequence of DNA triplets (its "gene") to encode its amino acids -- so e.g. 3 proteins of lengths 30, 40, and 50 would require 90 + 120 + 150 = 360 nucleotides in total. However, in viruses, space is at a premium -- so some viruses overlap the DNA sequences for different genes, using the fact that there are 6 possible "reading frames" to use for DNA-to-protein translation (namely starting from a position that is divisible by 3; from a position that divides 3 with remainder 1; or from a position that divides 3 with remainder 2; and the same again, but reading the sequence in reverse.)
For comparison: Try writing an x86 assembly language program where the 300-byte function doFoo() begins at offset 0x1000... and another 200-byte function doBar() starts at offset 0x1001! (I propose a name for this competition: Are you smarter than Hepatitis B?)
That's hardcore space optimisation!
UPDATE: Links to further info:
Reading Frames on Wikipedia suggests Hepatitis B and "Barley Yellow Dwarf" virus (a plant virus) both overlap reading frames.
Hepatitis B genome info on Wikipedia. Seems that different reading-frame subunits produce different variations of a surface protein.
Or you could google for "overlapping reading frames"
Seems this can even happen in mammals! Extensively overlapping reading frames in a second mammalian gene is a 2001 scientific paper by Marilyn Kozak that talks about a "second" gene in rat with "extensive overlapping reading frames". (This is quite surprising as mammals have a genome structure that provides ample room for separate genes for separate proteins.) Haven't read beyond the abstract myself.
I wrote a tile-based game engine for the Apple IIgs in 65816 assembly language a few years ago. This was a fairly slow machine and programming "on the metal" is a virtual requirement for coaxing out acceptable performance.
In order to quickly update the graphics screen one has to map the stack to the screen in order to use some special instructions that allow one to update 4 screen pixels in only 5 machine cycles. This is nothing particularly fantastic and is described in detail in IIgs Tech Note #70. The hard-core bit was how I had to organize the code to make it flexible enough to be a general-purpose library while still maintaining maximum speed.
I decomposed the graphics screen into scan lines and created a 246 byte code buffer to insert the specialized 65816 opcodes. The 246 bytes are needed because each scan line of the graphics screen is 80 words wide and 1 additional word is required on each end for smooth scrolling. The Push Effective Address (PEA) instruction takes up 3 bytes, so 3 * (80 + 1 + 1) = 246 bytes.
The graphics screen is rendered by jumping to an address within the 246 byte code buffer that corresponds to the right edge of the screen and patching in a BRanch Always (BRA) instruction into the code at the word immediately following the left-most word. The BRA instruction takes a signed 8-bit offset as its argument, so it just barely has the range to jump out of the code buffer.
Even this isn't too terribly difficult, but the real hard-core optimization comes in here. My graphics engine actually supported two independent background layers and animated tiles by using different 3-byte code sequences depending on the mode:
Background 1 uses a Push Effective Address (PEA) instruction
Background 2 uses a Load Indirect Indexed (LDA ($00),y) instruction followed by a push (PHA)
Animated tiles use a Load Direct Page Indexed (LDA $00,x) instruction followed by a push (PHA)
The critical restriction is that both of the 65816 registers (X and Y) are used to reference data and cannot be modified. Further the direct page register (D) is set based on the origin of the second background and cannot be changed; the data bank register is set to the data bank that holds pixel data for the second background and cannot be changed; the stack pointer (S) is mapped to graphics screen, so there is no possibility of jumping to a subroutine and returning.
Given these restrictions, I had the need to quickly handle cases where a word that is about to be pushed onto the stack is mixed, i.e. half comes from Background 1 and half from Background 2. My solution was to trade memory for speed. Because all of the normal registers were in use, I only had the Program Counter (PC) register to work with. My solution was the following:
Define a code fragment to do the blend in the same 64K program bank as the code buffer
Create a copy of this code for each of the 82 words
There is a 1-1 correspondence, so the return from the code fragment can be a hard-coded address
Done! We have a hard-coded subroutine that does not affect the CPU registers.
Here is the actual code fragments
code_buff: PEA $0000 ; rightmost word (16-bits = 4 pixels)
PEA $0000 ; background 1
PEA $0000 ; background 1
PEA $0000 ; background 1
LDA (72),y ; background 2
PHA
LDA (70),y ; background 2
PHA
JMP word_68 ; mix the data
word_68_rtn: PEA $0000 ; more background 1
...
PEA $0000
BRA *+40 ; patched exit code
...
word_68: LDA (68),y ; load data for background 2
AND #$00FF ; mask
ORA #$AB00 ; blend with data from background 1
PHA
JMP word_68_rtn ; jump back
word_66: LDA (66),y
...
The end result was a near-optimal blitter that has minimal overhead and cranks out more than 15 frames per second at 320x200 on a 2.5 MHz CPU with a 1 MB/s memory bus.
Michael Abrash's "Zen of Assembly Language" had some nifty stuff, though I admit I don't recall specifics off the top of my head.
Actually it seems like everything Abrash wrote had some nifty optimization stuff in it.
The Stalin Scheme compiler is pretty crazy in that aspect.
I once saw a switch statement with a lot of empty cases, a comment at the head of the switch said something along the lines of:
Added case statements that are never hit because the compiler only turns the switch into a jump-table if there are more than N cases
I forget what N was. This was in the source code for Windows that was leaked in 2004.
I've gone to the Intel (or AMD) architecture references to see what instructions there are. movsx - move with sign extension is awesome for moving little signed values into big spaces, for example, in one instruction.
Likewise, if you know you only use 16-bit values, but you can access all of EAX, EBX, ECX, EDX , etc- then you have 8 very fast locations for values - just rotate the registers by 16 bits to access the other values.
The EFF DES cracker, which used custom-built hardware to generate candidate keys (the hardware they made could prove a key isn't the solution, but could not prove a key was the solution) which were then tested with a more conventional code.
The FSG 2.0 packer made by a Polish team, specifically made for packing executables made with assembly. If packing assembly isn't impressive enough (what's supposed to be almost as low as possible) the loader it comes with is 158 bytes and fully functional. If you try packing any assembly made .exe with something like UPX, it will throw a NotCompressableException at you ;)