AngularJS Scoping (by value – by ref)

It is important to remember that you are basically working with Javascript.  No one would expect the following code to update the outer variable name:

var names = ["Misko", "Igor", "Vojta"];
function doubleName(name) {
  name = name + name;
}
for(var i=0;i<10;i++) {
  doubleName(names[i]);
}
This is because strings are passed by value in JavaScript.  So this is equivalent to
<div ng-init='names = ["Misko", "Igor", "Vojta"]'>
  <div ng-repeat='name in names'>
    <div ng-init="name = name + name"></div>
  </div>
  {{names}}
</div>
Objects on the other hand are passed by reference so this does work:
var objs = [{ name: "Misko"}, name: "Igor"}, {name:"Vojta"}];
 function doubleName(obj) {
   obj.name = obj.name + obj.name;
 }
 for(var i=0;i<10;i++) {
 doubleName(obj[i]);
 }
Which is equivalent to:
<div ng-init='objs = [{name:"Misko"}, {name:"Igor"}, {name:"Vojta"}]'>
  <div ng-repeat='obj in objs'>
    <div ng-init="obj.name = obj.name + obj.name"></div>
  </div>
  {{objs}}
</div>

Endo Sensei Seminar

Last night I attended a seminar with, the excellent Japanese aikido instructor, Sekio Endo 6th Dan, hosted by the Aikido Development Society up in Woodford.

Endo sensei has trained for many years with the major teachers of the Japanese Tomiki aikido fraternity.  It was great to see that his style of aikido was very similar to what we do in our club.

The focus of his teaching at this event was on the atemi wasa (first five techniques) of the randori no kata. Here is a clip of him demonstrating this kata in full, the 17 basic techniques of the Tomiki aikido system.  This was taken in Denver but it gives you an idea of his style.

Sekio Endo Sensei – Randori no kata

He emphasized the principles of balance breaking and keeping one’s own body in good posture.

Notably his balance breaks were always down the weak line. The technique that stood out in this regard was aigamae ate (technique two) where he suggested that rather than pulling on uke’s arm down the line of the attack one should direct it slightly down their weak line in front of them.

In techniques like gedan ate (technique four) he said that the back should stay vertical when throwing and throughout he always insisted that one should keep the hands in centre, especially for techniques like gyakugamae ate (technique three), where he said that use of the second hand would help keep both arms centred.

Each technique originated from pretty static, ma ai, position where the hands are just touching, which meant the techniques came across as a little snappy and vigorous.  It would be interesting to see how he would use uke’s energy from a more committed attack.  I could see how this form would be useful, though, when it comes to tanto randori (knife competition) where the attacker rarely over commits to the thrust.

It was interesting to see that he felt that uke had to have a certain tension in their arm when attacking as in reality if their arm was too floppy they could be easily overcome by tori and attacked and hit, or cut if they had a weapon.  This resulted in a slightly different feel to the balance breaking, where you could rely on a movement of uke’s arm causing their whole body to off balance.

As well as the standard form of the atemi wasa, Endo sensei showed applications for each from single hand grasps, ai hamni (natural posture), gyaku hamni (opposite posture) and both hands grabbed.  It was lovely to see how the same movements worked in each scenario.

I particularly enjoyed seeing a variation on ushiro ate (technique five) where you throw uke from behind.  This variation, coming from a gyaku hamni (opposite posture) or from both hands grabbed, relied also upon creating a tension between uke and tori where tori locks up the elbow of the attacking arm and then suddenly releases the tension to break balance and lead into the ushiro.  One to have a play with…

Endo sensei came across as a very humble, happy and friendly person on the mat.  His teaching was straightforward and down to earth with clear practical efficiency.  I recommend getting down to Folkestone to see him teach this weekend.

Passing Services to Controllers

When using N2 with MVC you may want to use some N2 services in your controller. This is really easily achieved by simply creating a constructor for your controller with a parameter for service you require. N2 will kindly wire up the controller for you.

Here is a very simple and artificial example:

N2.Engine.IEngine engine;public PageController(N2.Engine.IEngine engine) { this.engine = engine;}

And here is a real example from the UserRegistrationController of the MVC templates project. This controller needs to be able to send emails to users who register and log errors.

[Controls(typeof (UserRegistration))]public class UserRegistrationController : TemplatesControllerBase<UserRegistration>{ private readonly IErrorHandler errorHandler; private readonly IMailSender mailSender; public UserRegistrationController(IMailSender mailSender, IErrorHandler errorHandler) { this.mailSender = mailSender; this.errorHandler = errorHandler; }

2008 training begins

The Tuesday night classes return tomorrow after a three week break over the Christmas holidays. I hope that the period of abstinence from practice has fuelled the body, mind and heart for more earnest practice for 2008.

A break from training is a double edged sword – it can be both beneficial and detrimental. I often find that the break allows me to consolidate in my mind what I have been seeing or practicing on the mat but haven’t had time to sit back and absorb properly. On returning to the dojo I have renewed vigour and my aikido feels more natural and balanced. Also, I find that the motivation to get back into it sometimes dwindles and I need a kick start of a few good sessions to get back into the training mindset.

As always, moments like these are good opportunities to train your mind and heart; the loss of motivation is just a test of your determination and commitment to training.

What is the point of practicing aikido for a few months or even one or two years? Yes, you may get a black belt but you will soon lose any benefit gained after only a short time off the mat. The lessons learnt in aikido are not for ever. The benefit of aikido is in the practicing and as soon as you cease to train you lose that.

I was very lucky and grateful to receive a great Christmas present this year. It is a training manual written by one of the foremost exponents of karate and is arguably responsible for bringing karate to the mainstream of Japan from the islands, Gichin Funakoshi.

I must admit I know very little about karate. My only direct experience was a few weeks as a teenager in a karate club in the Midlands. The most profound memory being given the opportunity to have a bit of fun with some padded mits. I managed to pop my friend in the face with a punch. The punch did little harm but he was close to a concrete pillar and as his head flew back he cracked the back of his skull on the wall. Let me just say that there was quite a lot of blood to clear up. I didn’t realise it at the time but this has put me off punching and kicking martial arts for a long time.

Any way back to Funakoshi. What amazed me about this book was the amount of emphasis that was put on personal, moral development over fighting skills. This was completely opposite to my (and possibly the popular) view of karate as very macho and competitive.

The personal development aspect is exactly what encouraged me to start aikido in the first place. I wanted a physical martial art but I also wanted something with a decent philosophy that fitted with my own. On reading this book I found that Gichin Funakoshi’s outlook on life was actually incredibly similar to Ueshiba, O Sensei. Even their life stories are not that different.

I hope to make some comparisons between my understanding of aikido philosophy and this man’s karate-do in the coming weeks. So keep an eye out for those.

In the meantime, practice on Tuesday nights are now going to focus on syllabus for a few weeks as we look to get our yellow belts up to orange and bring the newly qualified beginners up to yellow. As always everyone is welcome to come along. There will be plenty of opportunity for quality practice and you might even find you learn something new!

Numeric Operators

Ruby allows built-in numeric types to co-exist seamlessly with user-defined types. To the client of a non-standard library the interactions between the library and the built in numeric types is fairly invisible. This allows you to define a new type and use instances of it as parameters to built in methods. As an example, consider that we have implemented a class called MyNumber.

class MyNumber

end

If the right methods have been implemented on MyNumber then the following code will work – hopefully with the correct semantics.

x = MyNumber.new

30 + x
54.4 / x
0×80000000 << x

There are two strategies employed in the Numeric classes to achieve this:

Convert to Integer/Float
In some cases it is necessary that the parameter passed in is actually of the same type as the Numeric. An example are the bit shift operators. It doesn’t make sense to shift a value by a non-integer amount (or does it??). In these cases the Numeric class attempts to convert the parameter to the right type. In this case an Integer (or Fixnum to be more precise). This is done either directly, as in the case of Float, or it is done indirectly by calling either to_i or to_int on the parameter. So to allow your class to be used with the Fixnum#<< operator all you have to do is implement to_i. There is a similar to_f method you can implement to convert to Float.

Value Coercion
Sometimes it is simply necessary to ensure that the object of the method and the parameter have the same type. The aim of coercion is to convert built-in types to match the user-defined types. This is used frequently to allow Fixnum and Bignum objects to interact with Floats. For instance, in the following code, the Fixnum get coerced up to a Float before the / operator is invoked. In this case it is the Float#/ operator that actually does the calculation.

3 / 4.3

This is achieved through implementing the coerce method. This method attempts to coerce its parameter to the same type as itself. The clever bit comes inside the Numeric class when a method is called that doesn’t know about its parameter.

Consider the following code:

class MyNumber

end

x = MyNumber.new
3 / x

The Fixnum#/ operator is invoked but it doesn’t know what to do with a parameter of type MyNumber. Instead it calls MyNumber#coerce passing in the self object (in this case the Fixnum 3) as the parameter. The / operator is then invoked on the value returned from coerce.
So assuming the MyNumber class implements both MyNumber#coerce (which coerces Fixnums to MyNumber instances) and MyNumber#/ then the above code will work. Again, hopefully with reasonable semantics.

IronRuby Implementation
This is all well and good but what about implementing this mechanism in the IronRuby libraries?

The convert to Integer implementation is fairly straightforward, we can call Protocols.ConvertToInteger and let it do the work of invoking to_i or to_int accordingly. E.g.

[RubyMethod("|")]
public static object BitwiseOr(CodeContext/*!*/ context, int self, object other) {
other = Protocols.ConvertToInteger(context, other);
return self | Protocols.CastToFixnum(context, other);
}

In the case of coercion I wrote a bit of helper code in the Numeric class that will do the coercion and then call the original operator or method:

public static object CoerceAndCall(CodeContext/*!*/ context, object self, object other, DynamicInvocation invoke) {
RubyArray coercedValues;
try {
// Swap self and other around to do the coercion.
coercedValues = NumericSites.Coerce(context, other, self);
} catch (MemberAccessException x) {
throw MakeCoercionError(context, self, other, x);
} catch (ArgumentException x) {
throw MakeCoercionError(context, self, other, x);
}
// But then swap them back when invoking the operation
return invoke(context, coercedValues[0], coercedValues[1]);
}

This method invokes Coerce on the other object passing in self and then invokes a method that you passed in, which corresponds to the original method called.

The delegate defining what can be passed in is fairly generic:

public delegate object DynamicInvocation(CodeContext/*!*/ context, object self, object other);

This allows you to do the following for the Fixnum#% operator, when the other parameter is not of a known type:

[RubyMethod("%")]
public static object ModuloOp(CodeContext/*!*/ context, object self, object other) {
return Numeric.CoerceAndCall(context, self, other, NumericSites.ModuloOp);
}

Operator Aliasing
In the case where an operator has been aliased, such as Fixnum#modulo and Fixnum#%, we have to be careful. Ruby insists that the same operator/method is invoked after the coercion regardless of aliasing. This means that despite Fixnum aliasing modulo and % to use the same implementation, MyNumber could implement both separately even with different semantics.

Therefore when implementing Fixnum in IronRuby it is necessary for modulo and % to have separate methods for each when the parameter is arbitrary.

[RubyMethod("%")]
public static object ModuloOp(CodeContext/*!*/ context, object self, object other) {
return Numeric.CoerceAndCall(context, self, other, NumericSites.ModuloOp);
}

[RubyMethod("modulo")]
public static object Modulo(CodeContext/*!*/ context, object self, object other) {
return Numeric.CoerceAndCall(context, self, other, NumericSites.Modulo);
}

They can of course share implementation for overloads that have known parameters:

[RubyMethod("%"), RubyMethod("modulo")]
public static object ModuloOp(int self, int other) {
RubyArray divmod = DivMod(self, other);
return divmod[1];
}

Note the multiple RubyMethod attributes in this method where other is int (Fixnum).

Distance

There are three distances at which you can deal with an attack. For want of more precise terminology these are: before contact, at contact and after contact.

Let me explain these distances better. If you want they are also temporal as well as physical.

Before Contact
The attacker is moving toward you to either hit or grab. They are just entering your personal space – that zone around you where you become vulnerable to attack.

At Contact
The attacker has entered you personal space and has almost touched you but maybe not quite; they have reached out to grab you or their punch has been thrown.

After Contact
The person has got you – either with a strike (ouch) or they have grabbed you with a strong hold.

Each of these distances represents diminishing levels of freedom on your part. At the first distance you have the most freedom to deal with the situation. At the last distance you have the least (and may well have been knocked out!)

The distance at which you deal with an attack depends upon, how aware you are to the situation, what your reflexes are like, whether you are constrained (physically or psychologically), how subtle and fast they are.

In any case the best position to be in is the first distance. Well aware of the attack and with the most options available. In this situation you can attack the attacker (preemptively) or make your escape or perhaps even lead the attacker into a position that is unfavourable to them (the most aiki approach).

In the last position, particularly from a grab, you have limited freedom of movement and have basically two approaches. One is to create more freedom using atemi (strikes). The strikes in these situations are not designed, necessarily to disable the attacker but to disrupt them enough to give you options to escape or take control of the situation. The other approach is to move. First you should move things that are not constrained. If your wrist is held then you can move just about everything else other than you wrist. Leave your wrist in the position that it is in and move your whole body around it. This is a form of blending and is fundamental to aikido. This movement allows things to develop and creates opportunities to break the attackers balance and execute an aikido technique.

In the middle distance you are not able to preempt the attack but can still move in a way to lead the attacker into a position where you can control them. This is the most common aikido situation. Timing and blending exercises are important to develop the sensitivity required to achieve this. This is sometimes described as ki no nagare.

Whenever you are practising an aikido technique you should consider at what distance it is most suited and how you could adapt it to the three different distances.

Method overloading

In IronRuby you can create a number of different implementations of a method that each take different parameters; much in the same way that you can do in C#.
E.g.
In BignumOps there is a * (multiply) method of the form: self * other.
Here are the overloads:

[RubyMethod("*")]
public static object Multiply(BigInteger self, BigInteger other)
[RubyMethod("*")]
public static object Multiply(BigInteger self, double other)
[RubyMethod("*")]
public static object Multiply(CodeContext/*!*/ context, BigInteger self, object other)

As you can see, if Multiply is called with a BigInteger (or int for that matter) as the “other” parameter the first method is executed. If it is a double, which maps to Float in Ruby, then the second is executed and any other type as other invokes the third implementation (the context parameter is a hidden support mechanism for providing access to stuff such as the dynamic invocation mechanism).

In other words the DLR is responsible for selecting the correct method overload to call at runtime based on the number and type of parameters.

This is different to how the overloading is achieved in the standard Ruby implementation. In this case you have just one method and this method works out which implementation it should execute itself. This is the equivalent C function in the C Ruby implementation:

VALUE
rb_big_mul(x, y)
VALUE x, y;
{
long i, j;
BDIGIT_DBL n = 0;
VALUE z;
BDIGIT *zds;

if (FIXNUM_P(x)) x = rb_int2big(FIX2LONG(x));
switch (TYPE(y)) {
case T_FIXNUM:
y = rb_int2big(FIX2LONG(y));
break;

case T_BIGNUM:
break;

case T_FLOAT:
return rb_float_new(rb_big2dbl(x) * RFLOAT(y)->value);

default:
return rb_num_coerce_bin(x, y);
}

j = RBIGNUM(x)->len + RBIGNUM(y)->len + 1;
z = bignew(j, RBIGNUM(x)->sign==RBIGNUM(y)->sign);
zds = BDIGITS(z);
while (j–) zds[j] = 0;
for (i = 0; i <>len; i++) {
BDIGIT_DBL dd = BDIGITS(x)[i];
if (dd == 0) continue;
n = 0;
for (j = 0; j <>len; j++) {
BDIGIT_DBL ee = n + (BDIGIT_DBL)dd * BDIGITS(y)[j];
n = zds[i + j] + ee;
if (ee) zds[i + j] = BIGLO(n);
n = BIGDN(n);
}
if (n) {
zds[i + j] = n;
}
}

return bignorm(z);
}

You can see here that there is a lot of type checking and conversion going on. I think that the IronRuby/DLR way is a much more pleasant and maintainable way of developing.

One thing that did worry me though was what happens if someone monkey patches your class. For instance what if I did the following in a Ruby program?

class Bignum
def *(other)
puts “hello”
self + other
end
end

In the C Ruby implementation, the whole C function is overridden and so all that complex type conversion goes out the window and you are left with the simple method given:

>> 0×80000000 * 2
hello
=> 2147483650
>> 0×80000000 * 0.3
hello
=> 2147483648.3

What would happen in the IronRuby case?

I felt it could have gone either way. At first I expected that it would just add a method with the equivalent of the following signature:

[RubyMethod("*")]
public static object Multiply(CodeContext/*!*/ context, BigInteger self, object other)

In actual fact, it appears that all the overloaded methods are wiped out. This is perhaps common sense: the DLR now has no type information on the parameters to distinguish the new Ruby method from those written in C#, so it just blats them all.

Even in cases where there where different overloads accepted different numbers of parameters and you could distinguish based on the number of parameters, those get wiped out too. You just get the one method and calls to the method with a different number of parameters causes an ArgumentError.

So all is good and you don’t have to worry about spreading your code out into multiple overloaded methods to make it easier to read.

Another beginners’ course is over

Well done to Zanna, John and Nicholas who completed the course on Tuesday. They have learned a lot during the ten weeks and I hope that they had fun too. I certainly did.

If any of the others who were on the course read this, then please know that you are most welcome to keep coming. I know that some of you had injuries or work commitments that kept you away. Don’t feel you can’t come along and get back on the horse, as it were.

The course has two aims. One is to introduce aikido generally to people who may have not even seen it before. The other is to get the attendees to learn enough of our syllabus to be able to grade to 6th kyu (white belt). Certainly the three mentioned above managed this with ease.

The difficulty with focusing on a syllabus is that you don’t have time show off lots of other aspects of aikido. This is something we will be remedying over the next few weeks before Christmas. No stress about grading; just fun and exciting aikido.

I hope we can keep up the healthy numbers at the Tuesday session till the end of the year. I.E. Don’t book your Xmas parties on Tuesday nights.

Teacher or Coach

I often worry that my aikido ability is not good enough for me to be teaching. I don’t train often enough for my timing and sensitivity to be good enough that my demonstration of technique is really slick. On the positive side, I do feel that I have a good understanding of aikido principles and a reasonable depth of knowledge of aikido techniques, history, philosophy and so on.

The question is what do people want or need from the person running their classes?

Arguably, a beginner is going to be able to learn something from anyone with more experience than them – assuming that they are not trying to teach them something they don’t understand.

But perhaps more hopefully, and what I would like to believe, is that people learning aikido need a good coach more than a good exponent of the art. You see this a lot in sport, the rugby or football coach is not able to perform at the level of the players but their understanding of the game allows them to get the best out of their team. Boxing coaches are similar.

Now that I say that, it occurs to me that you generally only get a good understanding of something when you have, at least at some point in your life, been good at it yourself. Also, you can’t beat a great demonstration of aikido to inspire and motivate, if not educate.

Oh well, better get more training in then…

Syllabus

OK so we are into the second half of the beginners course and I feel the pressure of getting everyone through the syllabus for the first belt bearing down on me.

With this in mind, I turned my eye toward drilling the techniques and exercises needed for the first grading. I think I have written about a lot of this before but for those not interested in trawling through the archives here is a quick run down of the techniques we need to have covered by the end of the course. Bear in mind that this is only the thinnest sliver of what constitutes the body of aikido. Also, remember that in truth the techniques and exercises are only a vehicle through which to learn the underlying principles that make aikido tick/work.

Techniques 1 to 5 from the randori no kataThis kata was created to teach the basic techniques that could be used in aikido competition as devised by Professor Tomiki. It is possibly his most important legacy to the aikido world.
1 – Shomen ate [frontal strike] – move inside the attack and push through the face or neck down the weak line. Ensure that the push comes from the legs/hips not the arm.
2 – Aigame ate [natural posture strike] – move outside the attack and push through the face or neck down the weak line (the same weak line as in 1 but from outside the arm). Ensure that the arm that is connecting to the opponent is kept in front/centre so as to ensure that the legs/hips are doing the work not the arm.
3 – Gyakugamae ate [opposite posture strike] - throw by pushing the opposite arm across the opponents chest (above their arm) while trapping their leg with yours. Ensure good connection through the whole body with uke to make the throw work. Uke should get bent backwards.
4 – Gedan ate [low strike] – throw by pushing the arm down into the opponents bladder (below their arm) while trapping their legs with yours. Ensure that your posture is good and upright not bent forward. Uke should be forced to sit backwards rather than bending backwards.
5 – Ushiro ate [rear strike] – throw by moving behind uke, hooking their shoulders with your arms and driving them backwards and down. Use your body weight to effect the throw rather than arm power; this requires good connection.