Skip navigation

Monthly Archives: May 2009

I’m one of those programmers who HATES it when he sees things like:


public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get
    {
      return m_hp ;
    }
    set
    {
      m_hp = value ;
    }
  }
}

Encapsulation or no encapsulation, this just SEEMS dumb.

Sometimes you’ll see this written as:


public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get { return m_hp ; }
    set { m_hp = value ; }
  }
}

Which further proves my point: You can compress code like that when its not meant to be looked at.

The point is, THERE IS NO POINT in having pass-thru getters/setters like this.

In languages other than C#, you’ll see people using functions of course instead of C# properties.


class Grunt
{
private:
  int m_hp ;

public:
  void ChangeHp( int toVal )
  {
    m_hp = toVal ;
  }

  int Hp()
  {
    return m_hp ;
  }
} ;

VERSUS:


class Grunt
{
public:
  int hp ;
} ;

Isn’t there a very slight performance hit for writing code that always uses methods? Yes. ++points for public members.

HOWEVER. Recently I have thought of ONE major benefit to this “methods only/no public members” style that I never really credited to the style before.

Readability.

Think of client code using the Grunt class:


Grunt g ;

if( g.Hp() > 10 )
{
  g.ChangeHp( 12 ) ;
}

VERSUS:


Grunt g ;

if( g.hp > 10 )
{
  g.hp = 12 ;
}

What reads better? g.ChangeHp( 12 ) or g.hp = 12?

Really, g.hp = 12 ; LOOKS more cryptic because even though you know what its doing if you think about it for a fraction of a second, (changing hp to 12), for the method way g.ChangeHp(12) you CANNOT READ IT without knowing exactly what it does like, even faster than the one with the =.

SO. Maybe all private members and all accessor methods aren’t such a bad idea after all.

yet another post about spam comments.. but they’ve been getting really offensive lately. i mean, they mix the words sex and poop and whatever else that’s sufficiently disgusting they can think of, and just cram it up on your blog.

its really rude. i mean, downright rude.

i avoid namespaces in C# because of the extra indentation

what’d be nice if there was an option in visual studio to NOT INDENT namespaces like we indent other blocks.

so it’d be like


namespace ns
{
class c
{
  public static int x ;
  public void method()
  {
    if( x == 5 )
    {
      Console.WriteLine("Everything indents normally except for the NAMESPACE");
    }
  }
}
}

I still think Java’s package statement is by far superior notation because it doesn’t indent the whole file. namespace declarations that were Java-like WERE ALLOWED in .NET 1, but they’re not allowed anymore.

Adding them is easy

Say we have 3 tables, users, sports, and users_sports_hobbies. The user_sports_hobbies table relates the users and sports table to tell what sports, each user likes.


-- drop tables with REFERENCES to table
-- because you can't drop the users or sports
-- tables WHILE users_like_sportsx refers
-- to it!
-- drop table users_like_sports1;
-- drop table users_like_sports2;
-- drop table users_like_sports3;
-- drop table users;
-- drop table sports; 






-- create the users table
create table users(

  user_id int not null primary key identity,
  username varchar( 255 )

) ;


-- and the sports table
create table sports(

  sport_id int not null primary key identity,
  sport_name varchar( 255 )

) ;

-- create the users_like_sports1 table
-- with foreign keys
-- compact notation, not naming the foreign key
-- constraints
create table users_like_sports1 (

  rel_id int not null primary key identity,

  user_id_fk int not null
  FOREIGN KEY REFERENCES users( user_id ),

  sport_id_fk int not null
  FOREIGN KEY REFERENCES sports( sport_id )

) ;

-- now here's the same thing, a users_like_sports table
-- only using a different notation to declare the
-- foreign keys.  this is completely functionally
-- equivalent to the above way, only in this
-- way i'm showing you here, I am NAMING
-- the foreign key constraints.  This is useful
-- for DROPPING the foreign key constraint off
-- the table later.
create table users_like_sports2 (

  rel_id int not null primary key identity, -- this is the "relationship id",
  -- i am in the habit of ALWAYS having a primary integer key for
  -- every field, even if it doesn't obviously serve any purpose here
  -- It may come in useful later, and its a real ass-biter to NOT
  -- have put in a simple integer primary key  

  -- Here is one way to do it:
  user_id_fk int not null
  CONSTRAINT fk_1a FOREIGN KEY REFERENCES users( user_id ),
  -- now we've said that the user_id_fk field
  -- is constrained by a constraint named "fk_1"
  -- and its a foreign key constraint, referencing
  -- the user_id column from the users table.
  -- (the name of the constraint "fk_1" 
  -- is useful for deleting this constraint later, if need be)

  sport_id_fk int not null
  CONSTRAINT fk_2a FOREIGN KEY REFERENCES sports( sport_id )

) ;



-- Finally here is a different notation.  This is a 
-- more common blown out notation
-- listing the foreign key references
-- at the bottom of the table specification.
create table users_like_sports3 (

  rel_id int not null primary key identity,

  user_id_fk int not null,
  sport_id_fk int not null,

  CONSTRAINT fk_1b FOREIGN KEY (user_id_fk) REFERENCES users( user_id ),
  CONSTRAINT fk_2b FOREIGN KEY (sport_id_fk) REFERENCES sports( sport_id )

) ;


-- ***
-- DROPPING THE CONSTRAINTS
-- Now here is how you drop the foreign key constraints
alter table users_like_sports2
drop constraint fk_1a ;

alter table users_like_sports2
drop constraint fk_2a ;

-- users_like_sports2 table now has
-- NO CONSTRAINTS AT ALL.  They
-- have been DROPPED.


-- Dropping the constraints for
-- table users_like_sports3
alter table users_like_sports3
drop constraint fk_1b ;
alter table users_like_sports3
drop constraint fk_2b ;

-- we can't easily drop the
-- constraints for users_like_sports1
-- since we don't have the constraint
-- names.
drop table users_like_sports1 ;


-- now that all references and constraints
-- to these two tables have been dropped,
-- we can safely drop the users and sports tables.
drop table users;
drop table sports;


If you don’t really need web history, just turn it off in firefox. A lot of what bogs firefox down (slow startup, slow action when typing something into the address bar) is because of the immensely detailed history it tries to keep for you.

Sheesh. It even keeps track of which letter sequences you type into the address bar, and which address you end up selecting (for instance, when I start to type “gm”, then I usually press the down arrow to pick gmail.com”). This is how firefox is smarter, but also slower. For me, I’m happier with the faster performance.

windows 3.1 i wanted windows 95.
windows 95. i wanted windows 98, kinda.

windows 95. i REALLY wanted winxp.

winxp. wanted vista.

vista. back to xp.

xp. want windows 7? eah, not sure.

xp is good.

windows 7 RC? use it for a year? eah. I want xp.

do you see how one mess up, one “bad release” (yes, I HAVE tried it) – you just can’t have an o/s start up, look all fine, then it jump down your throat for “needing permission” to move a basic file.

i created my login name as “root”! what more do you want?

sheesh. i mean, if they want to shove security issues down my throat, they really shouldn’t do it this way.

also being a developer, I don’t like the “toy” messages – “this application has stopped working”

What? then start it back up again! vista, why are you screwing with me?

I mean, saying “the application BROKE” would make more sense. But “has stopped working” is just too gay and “politically correct” – it still makes me think that vista is behind the application “stopping to work”.

I do not like the vista LOOK. the aero scheme, and the new window layouts, i think its because i’m sour on vista. what was so sleek and cool when it first come out turned out to be a lie and a signature for “SLOW” – the one thing I cannot stand from my machine.

I’m HAPPY to hear that Windows 7 is a huge improvement over vista – that its like the “new XP” that everyone wanted for christmas in 2006. I’m not trying the beta or the RC, I don’t think. I’m just going to wait and hope it doesn’t suck.

Windows and windowing

  • Taskix for changing the order of windows in the taskbar
  • Ultramon for having a taskbar appear on each monitor

General tools

  • Winspector for examining Windows messages
  • Winmerge for code file diffing
  • WinDiff for diffing either single files, or entire folders. This is a powerful program, don’t let its simple appearance deceive you. Comes with Windows SDK, if you develop for Windows you probably already have it.
  • Regex Coach for testing out regular expressions
  • TCPView for looking at net connections that are active, and what program is using it
  • the rest of the SysInternals suite (great tools!)
  • PuTTY for telnet
  • a href=”http://www.oldversion.com/download_WS_FTP_LE_6.html”>ws_ftp 6 for FTP file transfers, before it became bloatware
  • DaemonTools – mounts DVD images to your hard disk, though i like poweriso as well (*poweriso is not free, its shareware)
  • Teracopy. For copying files between disks. This application is BLAZINGLY fast, you won’t believe it – if you’re used to Windows Explorer copies.

media/mp3

  • GoldWave – a fantastic recorder/wav/sound editor
  • Winamp – just THE BEST media player. Now plays FLV!
  • VLC for all those avi’s that just refuse to play with anything else

NES and games

Web

(this section lacking, i know)

  • Not so much these days, but multiple ie gives you ie 6

Windows directory comparison tool

I was LOOKING for one for a long time. I finally found one, right on my own system!!

C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin\x64\WinDiff.Exe

There’s also: SyncToy

So it comes with the Windows SDK. Try searching for WinDiff on your computer

If you don’t already have it, then you can get it here.

I use it mostly because I keep redundant copies of entire folders, a lot of the time. For example, when my laptop was going down (lost ability to recharge from wall.. it was gonna go in for repairs!) i made an emergency dump of all the files that were on it. Some of the code files I had several copies of already, so WinDiff expedites the process of being able to blow away entire folders that are completely redundant -

Its pretty neat.

You can also blow out the thing, to see the actual file that is causing the diff

Well, to quote the great master:

When Windows needs to load a DLL module before running a program that requires it, the library file must be stored in the directory containing the .EXE program, the current directory, the Windows system directory, the Windows directory, or a directory accessible through the PATH string in
the MS-DOS environment. (The directories are searched in that order.)

Programming Windows 5th edition, page 962

MSDN ref

i was trying to run my ogre apps from the root..

and you know what happened?

yeah. delta 3d hijacked my setup.

debug output:

‘aiSimulator.exe’: Loaded ‘C:\CPP\Projects\2009\grad\aiSimulator\Debug\aiSimulator.exe’, Symbols loaded.
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Unloaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\ntdll.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\user32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\gdi32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\advapi32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\rpcrt4.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\secur32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcp90d.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcr90d.dll’
‘aiSimulator.exe’: Loaded ‘C:\Program Files (x86)\Delta3D_REL-2.2.0\ext\bin\CEGUIBase_d.dll’
LDR: LdrpWalkImportDescriptor() failed to probe C:\Program Files (x86)\Delta3D_REL-2.2.0\ext\bin\CEGUIBase_d.dll for its manifest, ntstatus 0xc0150002
Debugger:: An unhandled non-continuable exception was thrown during process load
The program ‘[2860] aiSimulator.exe: Native’ has exited with code 128 (0×80).

But I’m running an OGRE game.. ah. because CEGUIBASE_d.dll is found first in the delta3d folder, windows it tries to load IT, and because ogre came after in the path setting.. something got screwed up

so all i did was remove delta 3d fro the path setting, RESTART and voila, its fine

Well, in Python, you can attach an ELSE to a WHILE statement like so:

# python
while oi.hasNext() :
  print oi.value
else :
  print 'oi had no values'

You can’t do that in C++, but you can do this instead:

// C
if( ! oi.hasNext() )
  print 'oi has no values' ;
else do
{
  print oi.value ;
} while( oi.hasNext() ) ;

I used else do instead of


if( ! oi.hasNext() )
  print 'oi has no values' ;
else while( oi.hasNext() )
{
  print oi.value ;
} 

In case that oi.hasNext() has a side effect (such as advancing an iterator).. in this case, oi.hasNext() gets called twice before we ever try to read oi.value.

#include <stdio.h>
#include <map>
#include <string>

using namespace std;


// C++ affords PLENTY of mechanisms
// to make its code much less ugly.

// using namespace declarations,
// #defines and typedefs - but yet
// so many developers choose not
// to use these features and are
// perfectly content seeing lines
// of code like
// for( map::iterator iter = history.begin() ;iter != history.end(); ++iter )

// While it could look like
// foreach( HTIterType, iter, hash )

// I show how here.

int main()
{
  typedef map Hashtable;

  map history ;

  history[ "first" ] = "bob" ;
  history[ "second" ] = "mcnugget" ;


  //string val = history[ "first" ];
  //printf( "val is %s", val.c_str() );


  for( map::iterator iter = history.begin() ;
       iter != history.end();
       ++iter )
  {
    printf("key: %s / val: %s\n", iter->first.c_str() , iter->second.c_str() );
  }


  // Here's a more elegant way of doing that same thing
  
  // Create a new type called Hashtable, which
  // is going to be exactly equivalent to 
  // the map type
  typedef map<string,string> Hashtable ;

  // now define the HashtableIterator type
  typedef map<string,string>::iterator HTIterType ;

  // now create a hashtable
  Hashtable hash ;
  hash[ "firstentry" ] = "hello" ;
  hash[ "another"] = "there" ;

  // now use a "foreach" loop
  #define foreach( x, y, z ) for( x y = z.begin(); y != z.end(); ++y )

  // this is supposed to read "foreach ( HTIterType iter in hash )"
  foreach( HTIterType, iter, hash )
  {
    printf("key: %s / val: %s\n", iter->first.c_str(), iter->second.c_str() );
  }

  // Because the #define above turns:
  // foreach( HTIterType, iter, hash )
  
  // into:
  // for( HTIterType iter = hash.begin(); iter != hash.end(); ++iter )
  
  // which is in turn equivalent to
  // for( map::iterator iter = hash.begin(); iter != hash.end(); ++iter )
}

Well, the problem with my application was I wasn’t capturing the mouse.

bool frameRenderingQueued( const FrameEvent & evt ) override
{
mKeyboard->capture();
mMouse->capture();

return true;
}

The secret to a fresh-smelling butt is

shave your asshole
use damp toilet paper

I just looked up “fey”, as in tina fey, and can you believe fey means “slightly insane”??

i’m watching through the first season of studio 60 right now.
last week, i watched through season 1 of 30 rock.

i’m just thinking, about the differences between the two.

first thing i’m noticing is the ATMOSPHERE of studio 60: darker, MORE CONFRONTATIONAL.

studio 60 is about a bunch of actors who are constantly surrounded by drama. the show is in a way extremely melodramatic.

30 rock on the other hand isn’t AT ALL like that. 30 rock is airy and fluffy – its light and its funny. the jokes are about silly things that have no consequences – like getting an illegal fish -

THE CAST. 30 rock is filled with fun and UNIQUE characters you don’t see often – Kenneth – I love kenneth and his mannerisms. Lemon. Tracy. They all bring something to the show – they fight among each other but its not a nabbling kind of fighting.

I don’t know. The first episode of Studio 60 was GREAT. It was dramatic and it kind of made your head spin. I’m on the 4th episode and the show is rapidly decaying. The entire premise – the whole idea of the show being about struggling to produce a show is a bit too – I don’t want to say “prophetic” – but it seems like the writers of the show really aren’t getting the show itself together.

Also 1 hour /44 minutes is too long. There’s SO MUCH TALK about “filling 90 seconds” – I mean, they spend 90 seconds of the show itself worrying about how they’re going to fill 90 seconds of their “live” show -

If these shows came out at the exact same time, 30 rock would have absolutely steamrolled over studio 60 (if they were in any kind of competition).

Where was I in 2006? I don’t know. I didn’t watch either show back then.

Dear Interweb,

Can I propose class:gets()?

I mean, come on, this method is used COMMONLY everywhere. Can’t we all just agree to save keystrokes and just use class::gets() as a standard instead of class::getSingleton()?

Well, one thing I love about C++ is #define

I’m going through Ogre now, and I’m seeing A LOT of

CEGUI::WindowManager::getSingleton()

The great thing about C++ is I’m replacing this ugly call with

#define WinMan CEGUI::WindowManager::getSingleton()

So this makes it MUCH better to look at

CEGUI::Combobox* objectComboBox = (CEGUI::Combobox*)CEGUI::WindowManager::getSingleton().getWindow(“OgreGuiDemo/TabCtrl/Page2/ObjectTypeList”);

VS

CEGUI::Combobox* objectComboBox = (CEGUI::Combobox*)WinMan.getWindow(“OgreGuiDemo/TabCtrl/Page2/ObjectTypeList”);

huh?

self-fulfilling prophecy
A situation where “a false definition, in the beginning… evokes a new behavior which makes the original false conception come true.”

Canadians start with a false definition of who the best nine- and ten-year-old hockey players are. They’re just picking the oldest every year. But the way they treat those “all-stars” ends up making their original false judgement look correct. As Merton puts it: “this specious validity of the self-fulfilling prophecy perpetuates a reign of error. For the prophet will cit the actual course of events as proof that he was right from the very beginning.”

From Blink, by Malcolm Gladwell, page 25

We’ve all seen this.

Well, some people say there isn’t one.

But there is.

The short of it is, instead of writing base.FunctionName() as you would in C#, you write BaseClassName::FunctionName(). And NO, you DO NOT have to pass “this” to the base class.. although you do not use THIS in the invocation of the base class function in any way, C++ passes it automatically.

Short and long example follow.

Short and sweet

class BaseClass
{
public:
  BaseClass()
  {
  }

  virtual void OverrideMe()
  {
  }
}

class DerivedClass : public BaseClass
{
public:
  DerivedClass() : BaseClass() // explicit call base class ctor.
  {
  }

  void OverrideMe()
  {
    // run some stuff

    // call the OverrideMe() function of
    // the base class, "this" will be passed
    // automatically.  Clearly can't do this if
    // base class has purely virtual function
    BaseClass::OverrideMe() ;

    // The REASON for the non-existence
    // of base:: or super:: is because
    // of multiple inheritance
  }
}

Longer example

#include <stdio.h>


class Sprite
{
public:
  char * name ;

  Sprite()
  {
    name = "Dartagnian" ;
    printf( "Sprite alive, named %s\n", name );
  }

  Sprite( char* desiredName )
  {
    printf("Sprite '%s' alive\n",desiredName);
    name = desiredName ;
  }

  virtual void Speak()
  {
    printf( "  %s [ the Sprite ] saying hello\n", name );
  }
};

class Grunt : public Sprite
{
public:
  Grunt()
  {
    printf("A new grunt is alive and kicking, the base class ctor will pass the default name in.\n");
  }

  Grunt( char* desiredName ):Sprite( desiredName )
  {
    printf("RRU?? '%s' alive\n",desiredName);
  }

  void Speak()
  {
    printf( "  rrru?  me %s say Hi!\n", name );

    // C++ has no SUPER keyword
    // and no BASE keyword, on account
    // of multiple inheritance, or so
    // it is said.  But we can still access
    // the base class functionality
    // by casting "this" to being a pointer
    // to an instance of the base class.
    //( (Sprite*)this )->Speak();
    // HOWEVER, this is a BAD WAY TO DO IT.

    // The reason is, if the base class function
    // is marked "VIRTUAL", then what will happen is
    // THIS (the Grunt's) Speak() function will
    // be called repeatedly.

    // So to call the base class
    Sprite::Speak();
  }
} ;


int main()
{
  Grunt g("Grom!!");

  g.Speak();
}

Ref 1, ref 2

source

Access control of base class members (C++ only)

When you declare a derived class, an access specifier can precede each base class in the base list of the derived class. This does not alter the access attributes of the individual members of a base class as seen by the base class, but allows the derived class to restrict the access control of the members of a base class.

You can derive classes using any of the three access specifiers:

* In a public base class, public and protected members of the base class remain public and protected members of the derived class.
* In a protected base class, public and protected members of the base class are protected members of the derived class.
* In a private base class, public and protected members of the base class become private members of the derived class.

When trying to compile/run my new Ogre app in release mode, I came up with this error:

Assertion failed!

Program: …
File: f:\codingextra\ogre\shoggoth_vc9\ogr…\ogreroot.cpp
Line: 103

Expression: ms_Singleton

For information on how your porgram can cause an assertion failure, see the Visual C++ documentation on asserts

(Press Retry to debug the application – JIT must be enabled)

Abort/Retry/Ignore

OK here’s the image

It turns out that this problem comes up because you tried to build in Release mode while still linking to the DEBUG MODE (ending in _d.dll) libraries.

The libraries that ogre will link to are in plugins.cfg:

# Defines plugins to load

# Define plugin folder
PluginFolder=.

# Define plugins
Plugin=RenderSystem_Direct3D9_d
Plugin=RenderSystem_GL_d
Plugin=Plugin_ParticleFX_d
Plugin=Plugin_BSPSceneManager_d
Plugin=Plugin_CgProgramManager_d
Plugin=Plugin_PCZSceneManager_d.dll
Plugin=Plugin_OctreeZone_d.dll
Plugin=Plugin_OctreeSceneManager_d

So I just changed this file to:

# Defines plugins to load

# Define plugin folder
PluginFolder=.

# Define plugins
Plugin=RenderSystem_Direct3D9
Plugin=RenderSystem_GL
Plugin=Plugin_ParticleFX
Plugin=Plugin_BSPSceneManager
Plugin=Plugin_CgProgramManager
Plugin=Plugin_PCZSceneManager.dll
Plugin=Plugin_OctreeZone.dll
Plugin=Plugin_OctreeSceneManager

Just basically taking away all the _d at the end of the file names.

I also made sure to LINK TO the correct libraries – I prefer inline linking instead of fiddling with the Visual Studio Project options dialog boxes, so I have this code:

#ifdef _DEBUG
#pragma comment( lib, "CEGUIBase_d.lib" )
#pragma comment( lib, "OgreGUIRenderer_d.lib" )
#pragma comment( lib, "OIS_d.lib" )
#pragma comment( lib, "OgreMain_d.lib" )
#else
#pragma comment( lib, "CEGUIBase.lib" )
#pragma comment( lib, "OgreGUIRenderer.lib" )
#pragma comment( lib, "OIS.lib" )
#pragma comment( lib, "OgreMain.lib" )
#endif

This is my problem with MSVC++

What on EARTH does _Kty, _Ty, _Pr, _Alloc even ___MEAN___ ??? Through 3 VERSIONS of MSVC++ i’ve seen (VC 7, VC8, and even now in VC9) we haven’t seen __ANY__ improvement whatsoever in making standard library function autocomplete not stupid.

I like the idea of an ITNERFACE that provides.. more capabilities. (or less).

HTMLDocumentClass htmlDoc = new HTMLDocumentClass();

IHTMLDocument2 iHTML = htmlDoc ;

Because HTMLDocumentClass IMPLEMENTS IHTMLDocument2, we can look at the HTMLDocumentClass object AS IF IT WERE JUST an object AS DESCRIBED BY the IHTMLDocument2 interface.

The INTERFACE is like a JOB.

ME. I can implement: ISoftwareProgrammer, IMan, IHusband, IBoxer, IMotorcyleRider.

Say I implement all those interfaces. I am an instance of class Human, implementing the above listed interfaces.

In your interaction with me, your interaction with me is LIMITED. So, say you are a woman who takes no sexual interest in me whatsoever. So you will basically view me from my PROFESSIONAL INTERFACE: my ISoftwareProgrammer interface. Your view of me is going to only be .. seeing me as a SoftwareProgrammer, and not as a boxer, husband or anything else that I AM. Because you dael with me THROUGH the ISoftwareProgrammger interface, you SEE ME AS just someone who implements the ISoftwareProgrammer interface requirements and you WILL NOT SEE any of the other interfaces that I implement.

In other words, dealing with me through an INTERFACE makes me … a pawn.

Dealing with people through the correct interface insures correct behavior. Knowing which interface to use, prevents lawsuits such as using your IBarAttendee interface on a coworker.

Because I am a Boxer, I COULD punch your lights out. But when you deal with me professionally, you actually won’t see that, because you deal with me exclusively through my ISoftwareProgrammer interface.

Now when I’m down at the track, riding my motorcycle, all the people THERE are seeing me as implementing the IMotorcycleRider interface. They don’t know and they don’t care what other interfaces I implement. I implement, IMan, IHusband and ISoftwareProgrammer interfaces, so they COULD interact with me through those interfaces .. through my softwareProgrammer interface I can be asked to .Code something – ( (ISoftwareProgrammer)me ).code() ;

REALLY, I have these methods:
me.Eat() // due to me being of base class Human
me.Sleep() // due to me being of base class Human

me.Code() // due to software programmer interface, i implement .code()
me.Grunt() // due to man interface, i implement .grunt()
me.Serve() // due to the husband interface, I implement .serve()
me.Punch() // due to IBoxer

But when you deal with me through the ISoftwareProgrammer interface, you actually do not see my other capabilities, really. If you dealth with me through the Human base class interface, you might see I only do .Eat() and .Sleep().

Doesn’t that make sense?

So, WHY program to an interface.

Programming to an interface makes it so that the way to interact with the underlying code remains fixed, even though the code itself might change radically.

To understand this, say you get work done on your car. You want to soup it up, you want to make it go faster. What kind of mods done to your car will _not bother you_? Mods that change / improve how the car works inside, WITHOUT CHANGING THE WAY YOU AS THE DRIVER INTERFACE TO THE CAR.

The interface of your car is standard. It has pedals to stop and go, and a wheel to steer. If you did a soup up that changed your steering wheel to a stick, then you WOULD have SERIOUS problems getting used to the new steering “wheel” (or stick). If suddenly the pedals were put on the roof, it would be very hard for you to get used to that. In fact, you would probably be angry.

Is it any wonder software programmers get angry when libraries change their interfaces? When a programming library changes its interface (ALA D3D, DirectX SDK is ALWAYS doing this) then it means that we as programmers must change our code that uses those interfaces. Microsoft has gone and made a wheel a stick, or a stick a wheel, and our program code must change to accomodate that fact.

Ideally interfaces are CONCRETE and do not change often. When an interface does NOT change, it means your code that uses an interface has a WAY easier time handling “upgrades”. Its like dropping a new engine into your car, and you finding the car equally easy to drive. The interface – or how you interact with the car – has not changed – the steering wheel and pedals are still the same. But something internal to the car – the engine in this case – has been improved and replaced – so while you still use your car the same way, it just works better.

In an ideal world that is what Interfaces are SUPPOSED to do for software. An Interface is SUPPOSED TO be written in stone, something that doesn’t change, and it is the “outline” of functions and data members that a class exposes for YOUR CODE to use. Upgrading the code of a class that IMPLEMENTS an interface should not require changes to the code that USES that class.

you can’t create an instance of an interface directly because.. well you can’t just have a SOFTWARE PROGRAMMER. There is no such thing.. there’s only people who are software programmers.. PEOPLE that IMPLEMENT the ISoftwareProgrammer interface. Invariably you’re going to get a PERSON who can do many more things than just software program.

I had this problem that kept coming up again and again, so I’m recording it here.

The problem is when you have a server that listens for UDP packets. Its fine, its open, no firewalls are causing issues at that end. Say its at 200.100.205.70:10006

Now, you want to connect to that server using a UDP sockets program on your local machine. Because you have a firewall, you need to DICTATE from which IP:Port your local sockets program will send sockets.

So naturally, you first go to your firewall software (in your router) and you open port 10007 on 192.168.1.105 (which is your IP address assigned to you by your router).

Now from your client sockets program, you send UDP packets out on a UDP socket which is bound to 127.0.0.1:10007.

It doesn’t work.

WHY??? BECAUSE YOU DIDN’T OPEN 127.0.0.1 ON YOUR ROUTER/FIREWALL, NINNY, YOU OPENED 192.168.1.105!!

Even though the UDP socket is being sent from “THIS MACHINE” (which is probably what you intended when you used the loopback), LOOPBACK != EXTERNAL IP ADDRESS!!

Sending data from the loopback address is actually completely different to the router.. than sending data from your externally assigned ip address. So, yes, if you are connected to the internet, your computer DOES have minimum 2 ip addresses (loopback and the external ip address the router gives you). Actually it has 5: 127.0.0.1, 127.0.0.2, 127.0.0.3, 127.0.0.4 are all loopback. Then the external ip (which for me was 192.168.1.105).

OK!! So how do you fix it?

You bind the UDP socket to

192.168.1.105

OR

bind it to (IPADDRESS.ANY, 10007) (like, 0.0.0.0:10007).

Hmm. That DOESN’T MAKE SENSE, does it?

Aaron Zupancic (from web archive) says its Microsoft’s fault.

This is basically what the Microsoft article says:

If sending a datagram using the sendto function results in an “ICMP port unreachable” response … the subsequent call to recvfrom does not work with a WSAECONNRESET (10054) error response.

Isn’t that STUPID?? Isn’t that like, totally against the spirit of UDP? Isn’t the UDP protocol supposed to like, “not care” if the message doesn’t get there? Why are you throwing this error in my face now when I don’t expect it, Microsoft?

Anyway, here it is again: On a UDP-datagram socket this error indicates a previous send operation resulted in an ICMP Port Unreachable message.

Anyway, it only happens once PER TIME you call sendto() on an (address,port) that isn’t set up to receive a UDP packet. Basically, when you send something to an (address,port) that CANNOT RECEIVE IT, you get this error on your NEXT call to recvfrom(). Its a pretty roundabout and counter intuitive way of doing stuff, but hey, so are a lot of other things in sockets (EWOULDBLOCK on nonblocking socket when you try to receive, zero-length packet when someone closes a TCP connection..), but it CAN BE pretty useful to know that SOMEONE has gone away and you should check the whether each of the clients you THINK is there, if any of them has gone away (which one of them certainly has).

You know what song, I just heard, which took me back to camp times..

“I’d like to teach the world to sing..”

I’d pay .. a million dollars to hear it by KT Tunstall

I wish we could request artists to do covers of songs we think they’d sound cool doing.. alas, radio shows, for songs we already know..

1. in solving problem with logarithms

n log2(n) = 8

What is the solution?

nn = 28

seems wrong.

2. in solving selection sort complexity

What is this summation?

I thought it was to pull out ( n – 1 )*( n + 2 ) term, but I’m not SURE that is correct (though it seems correct)

Say you come across

What you do is
break it up

#include <stdio.h>

void p( int a[], int len )
{
  for( int i = 0; i < len - 1; i++ )
    printf( "%d, ", a[i] ) ;
  printf( "%d\n", a[ len - 1 ] ) ;
}


int main()
{
  int a[] = { 3, 6, 2, 11, 59, 5782, 2 } ;
  int len = sizeof(a) / sizeof(int) ;

  p(a, len) ;

  // selection sort

  // Imagine you have 6 pieces of pasta, all
  // of different lengths.

  // |
  // |         |
  // | |     | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Now you want to put them in order of increasing height.
  // Here's what you do with selection sort.

  // You start at the very left side.
  // You pass through all sticks,
  // in the rest of the collection
  // LOOKING FOR THE SMALLEST ONE.

  // You identify the smallest one
  // as index 2.

  // |
  // |         |
  // | |     | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Swap with the item at index 0.

  //     |
  //     |     |
  //   | |   | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Now you are on index 1.  You need to
  // pass through array elements 2-5 and
  // find the smallest one in THAT set
  // of the collection.

  // You identify the smallest as index 3.
  // swap.

  //     |
  //     |     |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Keep going.
  // 2 swaps with 3

  //       |
  //       |   |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // 3 swaps with 4

  //         |
  //         | |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // 4 swaps with 5
  //           |
  //         | |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // and we're done

  //////////
  // The algorithm.
  // We will walk through the array ONE TIME
  // from the first element to the SECOND LAST
  // element.  We don't need to "sort" the very
  // last element.  Think about it.
  for( int i = 0 ; i < len - 1 ; i ++ )
  {
    // Now, at each element, we want to
    // find the SMALLEST ELEMENT TO THE
    // RIGHT OF IT, so we can swap the
    // current element (at i) with the
    // smallest element in the rest of the list.

    // set the mini = minimum index to be
    // ASSUMED to be the one immediately
    // to the right of the element we are
    // currently sorting.
    int mini = i + 1 ;

    // now, walk through the rest
    // of the list .. everything to the right
    // of the current element we are sorting
    // must be examined... NOTHING to the left
    // will be examined because that part
    // HAS ALREADY BEEN SORTED.

    // Once we reach the 3rd element, for example,
    // you should realize that THE FIRST 2 SLOTS
    // WILL ALREADY CONTAIN THE TWO SMALLEST
    // ELEMENTS IN THE WHOLE ARRAY.  Take a
    // look at what this next loop does to understand
    // why.

    for( int j = i + 1 ; j < len ; j++ )
      if( a[ j ] < a [ mini ] )   // if this jth element is smaller than the smallest we found so far
        mini = j ;   // then set the smallest to being j

    // swap a[ i ] with the SMALLEST ELEMENT
    // we could find
    int tmp = a[ i ] ;
    a[ i ] = a[ mini ] ;
    a[ mini ] = tmp ;
  }

  p(a, len) ;
}

The question is: How many bits do you need to represent the following numbers in a computer?

a) 3000

b) 3

c) 20

d) 598225

The answer to each is found by this formula:

numBits = ceil( log2( n ) )

If you are on a hand-calculator, you can always get log2 by doing:

numBits = log10n
log10(2)

Dividing by log102 gives you the right answer.

#include <stdio.h>

void p( int a[], int len )
{
  for( int i = 0; i < len - 1; i++ )
    printf( "%d, ", a[i] ) ;
  printf( "%d\n", a[ len - 1 ] ) ;
}


int main()
{
  int a[] = { 5, 9, 1, 22, 6, 7, 7, 90 } ;
  int len = sizeof( a ) / sizeof( int ) ;  // *note:
  // sizeof() doesn't work for pointer (int * a) style arrays 

  p( a, len ) ;

  // The insertion sort algorithm is here, and
  // every line is explained in comments.

  // UNDERSTANDING INSERTION SORT
  // The best analogy for understanding insertion
  // sort is if you think of holding a hand of cards.

  // Say you have this hand:
  // 7, 2, 5, 8 

  // Now you like to see things in order, so you
  // want them to have the order 2, 5, 7, 8.  What's
  // the easiest way to order the cards without
  // putting them down flat on the table?

  // You'd probably do this.  Start at the
  // very left hand side.  Skip the first card,
  // and PULL OUT the second card
  // so now you're looking at the 2.

  // In left hand:  7, ___,  5, 8
  // In right hand:  2

  // (the empty space is where the 2 WAS)

  // FROM the place where the 2 WAS,
  // work backwards until
  // you find where that 2 "SHOULD GO"
  // in the GREEN ("already sorted") section.

  // Clearly the 2 should go in front of the 7.

  // Thinking like a computer...

  // To make the 2 go in front of the 7, we have
  // to SLIDE the 7 over to occupy the space
  // where the 2 WAS:

  // In left hand:  ___, 7,  5, 8
  // In right hand:  2

  // Now we can insert the 2 into that blank spot:

  // In left hand:  2, 7,   5, 8
  // In right hand:  ___

  // You just keep going
  // until you INSERT all the cards from the
  // UNSORTED section
  // into their correct positions in the SORTED section

  // Next step:  We're on the 5.
  
  // Pull it out.

  // In left hand:  2, 7, ___  8
  // In right hand:  5

  // WORK BACKWARDS FROM the ___ spot.

  // AS WE STEP BACKWARDS,
  // we are looking for an entry in
  // the already sorted section that
  // is SMALLER than the number
  // we have plucked out in our right hand
  // (the 5 in this case)

  // In left hand:  2, 7, ___  8
  // ** NO, 7 is not SMALLER than 5.
  // So we simply siddle the 7 up

  // In left hand:  2, ___, 7  8
  // ** YES, 2 is smaller than 5, so
  // our 5 will belong right after the
  // 2 (where the blank space happens
  // to be right now!!)

  // We simply insert the 5 here,
  // and we are done with the 5.
  // In left hand:  2, 5, 7  8

  // last step:  remove the 8:

  // In left hand:  2, 5, 7, ___

  // Start by looking at the 7.  7
  // is less than 8, so the 8 goes
  // in after the 7 (where it was
  // basically)

  // In left hand:  2, 5, 7, 8

  // And that's the algorithm.

  // NOTICE the method you use.  At every card
  // you attempt to sort, you count BACKWARDS
  // from the place you pulled it out from,
  // until you find a number that is SMALLER
  // than the card you are trying to insert.


  //////////////
  // THE C CODE: 

  // the outer for loop.  the outer loop walks us
  // THRU the array, FORWARDS, ONCE.

  // In this SINGLE PASS through the array
  // we are sorting, at EVERY number we hit
  // we will STOP, look back through the
  // beginning part of the list, and put that
  // number WHERE IT BELONGS.

  for( int j = 1;  // start at the SECOND element of the list
       j < len ;   // go until the end of the list
       j++ )       // one at a time.
  {
    // { 5, 9, 1, 22, 6, 7, 7, 90 } ;
    //     ^^^
    //    ( START HERE, not at the very beginning )
    
    // Now, at EACH number you're at
    // first, we must SAVE IT OFF.

    // Reason:  Its going to be overwritten.
    int KEY = a[ j ] ;

    // This is equivalent to "pulling
    // the card out" in the explanation above.

    // Next, we walk BACKWARDS through
    // the array, STARTING at the position
    // JUST BEFORE the card we "pulled out"

    int i ;
    for( i = j - 1 ;  // start at position JUST BEFORE item we pulled out
         i >= 0 ;     // we'll walk down until the VERY BEGINNING of the list
         // ** UNLESS WE FIND A NUMBER IN THE LIST
         // THAT IS SMALLER THAN KEY (in which case
         // we will BREAK out of this loop)

         i-- )        // we're walking backwards thru the list
    {
      // Now, we are LOOKING FOR
      // a number in a[] that is
      // SMALLER than the KEY we
      // have in our hand.

      // Once we find a number that
      // is SMALLER than the KEY,
      // we will know where to
      // insert the KEY (right
      // after THAT number which is
      // smaller than the KEY.)

      // Notice how this assumes that
      // everything to the left of the KEY
      // IS ALREADY SORTED (which it will be
      // as this algorithm works through
      // the list).
      if( a[ i ] < KEY )
      {
        // Found spot for KEY.  Stop "siddling"
        // (see ELSE statement below for "siddle").

        break;
      }
      else
      {
        // siddle.  copy element over.
        
        a[ i + 1 ] = a[ i ] ;

        // on the first iteration, this
        // operation will overwrite the KEY
        // in the array (hence the need to
        // save it off in a separate variable).
      }
    }

    // Insert the key.
    a[ i + 1 ] = KEY ;
  }

  p( a, len ) ;
}

liz owns..

I just love how the other girl tucks her hand away.

The internet2is dissent.

Come on. You can’t form a separate network and call it Internet2. This is totally against the spirit of the Internet and I can just see myself having to dial up to different networks.. No. This doesn’t sound right.

this youtube video on Bush’s statement about the “internets” was actually correct.

Actually the original subtitle of this blog was “technology and the internets”. mwtss.

I’ve never seen this before: VIDEO SPAM!!

just wanted to record this before askimet says bye-bye. thanks askimet!

TCP VS UDP

And why TCP is unsuitable for games

OK, so I did some comparisons using a server of mine.

The thing is, TCP and UDP ARE pretty much equal when it comes to transportation times across the internet.

In my tests, I sent 10,000 messages across about 50km (my server is located about 50km from where I am now).

The results:

UDP: Average round-trip time: 30ms

TCP: Average round-trip time: 500ms

Now you’re saying WTF???? YOUR TEST IS WRONG!! But allow me to explain.

The reason the TCP tests were so awful, is, well, here, take a glance at numerics of the results first.

UDP RESULTS:
DIFF=0.0278434801501
DIFF=0.0305130913992
DIFF=0.0277071201201
DIFF=0.027180660817
DIFF=0.0300143798507
DIFF=0.0273463786314
DIFF=0.0335492180775
DIFF=0.0280604430992
DIFF=0.0330231491187
DIFF=0.0273172101218

// And it looks the same for all 10000 messages.. no huge latencies at all.
// these are in SECONDS, so it translates to about 30ms per datagram.

// BTW, in this test, I sent 10000 messages and received 9994 of them.

Now for the TCP results..

// First few, at the beginning when the application first launched…
DIFF=0.0373954983804
DIFF=0.0373870345209
DIFF=0.0373785706613
DIFF=0.0373701068017
DIFF=0.0373617621515
DIFF=0.0373534175012

// HMM, that looks pretty much the same as TCP
// Scrolling down a bit… it gets worse..
DIFF=0.0669155569774
DIFF=0.0669068546993
DIFF=0.066898510049

// further down still..
DIFF=0.0961061779911
DIFF=0.0960975949222
DIFF=0.0960886542255

// ok, further down…
DIFF=0.232780874127
DIFF=0.232772767895
DIFF=0.232756436223

// and take a look at THIS interesting section ..
DIFF=2.25679475173
DIFF=2.25677114829
DIFF=2.2567289482
DIFF=2.17196494445

DIFF=1.80040103301
DIFF=1.10465389594
DIFF=0.114454568475
DIFF=0.114441693871
DIFF=0.114434064477

So what’s going on here? What’s happening, especially in the very last block where the round-trip time varies from 2.35 seconds to 0.11 seconds is the PRIMARY REASON why I wouldn’t recommend to use TCP for games, EVER.

Its because of the BUFFERING. You know that when you call .send() on a TCP socket, TCP WILL NOT NECESSARILY DELIVER THE MESSAGE IMMEDIATELY! TCP has a buffer BOTH at the sender (messages might pile up for a number of seconds before actually being fired off across the net) __AND__ at the recipient (messages might stock up for a number of seconds before the remote user’s TCP subsystem alerts HIM that you have sent some bytes). This is precisely what makes TCP so inappropriate for use for games: it might withhold the data from you, even if its already at your machine, as you can see here, for up to 2 seconds (or more!).

In the context of a fast paced game, this will give a stupid 2 second lag in game play (likely the game will freeze up for the player, as if he had temporarily disconnected.. depending on how you programmed it of course) which really is not good.

The TCP system is basically like having customs at the airport. Before you can travel, you have to pass through customs, and after you arrive, you also have to pass through customs. You might be held up at customs (the outgoing buffer) for very short (“anything to declare? no? good!”) or you might be there for hours (seconds). You then get into the same plane as the UDP packets, travel across the internet, and when you arrive at the remote host, you as a TCP message must go through customs AGAIN (while the UDP packet simply runs off into the crowd). UDP packets don’t have customs (buffering). But TCP packets do. And because of the customs (buffering) there’s this UNPREDICTABLE, UNCONTROLLABLE (just like customs!!) extra wait that makes TCP totally unsuitable for games.

UDP, as you can see from the results listed above (0.03s, 0.03s…), CONSISTENTLY delivers the messages in 30ms .. UDP is completely stateless and connectionless – you fire off a message, and away across the net it goes. UDP has no sense of buffers or any of the heavyweight stuff that TCP employs. When you use UDP to send messages across the internet, the only delay that will be encountered as the messages goes across the web is because of congestion on the web itself. A UDP message WILL NOT be held up in some buffer EITHER on the local machine from which you send it, or at the remote host that receives it.

Often when people build games, you see them building a TCP-like system (with message acknowledgement and re-sending in case the message doesn’t arrive), but you might wonder WHY they bother to you see people using UDP if they need message acknowledgement. Well, the reason is simple. More CONTROL. UDP doesn’t have that annoying buffer! When you implement “TCP in UDP”, you are in complete control and can achieve the same reliability you get with TCP using UDP. And its worth it.

Conclusions: On Windows it SEEMS that TCP “gets lazy” after about 10 seconds of using it. When a program is sending thousands of really small (8-byte, in this case) messages, the TCP implementation in Windows XP really starts to buffer the packets up and you start to see big honking 1024k messages being transmitted, which ultimately translates to ADDITIONAL DELAY for your game.

So, this is the PRIMARY REASON that TCP isn’t suitable for games. Its not that “TCP is slower” in any absolute sense – actual transmission speeds between TCP and UDP are pretty much the same across the same segment of the ‘net. WHAT IS different is that TCP MAY WITHHOLD THE DATA FROM YOU for longer than you might like in its buffers. And that (the buffering) is what makes TCP unsuitable for games. You can’t control the buffering of TCP – its a FEATURE, not a bug/problem.

The scripts used are below. You launch the server script on your server, then you run the client script and tell it whether you want (U)DP test to run (type U) or the TCP test to run (T).

The UDP test takes about 100 seconds to run, because there is a 0.01s pause between the .send for each of the 10000 messages (something about the UDP buffer overflowing and getting MASSIVE packet loss if you try and send UDP packets too rapidly).

See also Topics in High-Performance Messaging, by Robert A. Van Valzah. It has some very interesting notes on reasons for UDP packet loss, and a section on UDP buffering.

SERVER SCRIPT

Run on the server you are using. It launches BOTH a UDP listener AND a TCP listener (on separate threads), so you can run either test by running this single server script.

#SERVER SCRIPT
#Python 2.5
from socket import *
from select import select
from struct import *
from time import *

import thread

import sys


TCPServer = socket( AF_INET, SOCK_STREAM )
TCPPort = 10007
TCPDone = False

UDPServer = socket( AF_INET, SOCK_DGRAM )
UDPPort = 10008
UDPDone = False

""" UDP server startup """
def UDPServerStart():

  global UDPDone

  try :
    # just bind UDP socket
    UDPServer.bind( ( '', UDPPort ) )
    print '\nUDP socket bound successfully on port %d' % UDPPort

  except :
    #only get here if something bad happened in try block above
    print "\nServer couldn't startup! Reason:",sys.exc_info()
    UDPServer.close()
    sys.exit()  # bail if failed



  
  while( UDPDone is False ):

    try :
      ( buf, senderAddr ) = UDPServer.recvfrom( 1024 )
      #print 'I got something'
      
    except :
      print '\nudp: could not recvfrom'
      break

    # now just return that message to the sender
    UDPServer.sendto( buf, senderAddr )

    # we are done when the message is a 0
    if( buf[ 0 ] == 0 ):
      UDPDone = True
      
  #end while

  print '\nShutting down the UDP server'
  UDPServer.close()


""" TCP Server startup """
def TCPServerStart():

  global TCPDone
  
  try :
    #bind
    TCPServer.bind( ( '', TCPPort ) )
    print '\nTCP socket bound on port %d' % TCPPort

    #listen
    print '\nTCP socket is listening'
    TCPServer.listen( 5 )

    #Accept
    (sock,senderAddr) = TCPServer.accept()
    print '\nTCP socket has accepted connection',senderAddr
    
  except :
    #only get here if something bad happened in try block above
    print "Server couldn't startup! Reason:",sys.exc_info()
    TCPServer.close()
    sys.exit()  # bail if failed


  # now
  TCPDone = False
  
  while( TCPDone is False ):

    try :
      buf = sock.recv( 1024 )
    except:
      print '\nproblem in tcp receive'
      TCPDone = True
      break #will drop us out of the loop

    # now just return that message to the sender
    sock.send( buf )
    ##print 'Got',buf

    # we are done when the message is a 0
    if( len(buf) == 0 or buf[ 0 ] == 0 ):
      TCPDone = True
      
  # end while

  print '\nshutting down the connected socket'
  sock.close()
  
  print '\nShutting down the TCP server'
  TCPServer.close()

def Unstick():

  udpunsticker = socket( AF_INET, SOCK_DGRAM )
  udpunsticker.sendto( '', ( '127.0.0.1', UDPPort ) )
  udpunsticker.close()
  
  # unstick sticky socket
  tcpunsticker = socket( AF_INET, SOCK_STREAM )
  
  # connect to MAINSOCKET to basically unstick (unblock) it
  tcpunsticker.connect( ('127.0.0.1', TCPPort) )
  
  tcpunsticker.close()
  
# end def Unstick

def main():

  global TCPDone
  global UDPDone

  # Start up 2 threads, one for the TCP server, and one
  # for the UDP server.

  # thread.start_new_thread( RunGame, ( player1sock, player2sock ) )
  thread.start_new_thread( TCPServerStart, () )
  thread.start_new_thread( UDPServerStart, () )
    
  inputs = raw_input("Press any key to shut down")

  TCPDone = True
  UDPDone = True

  Unstick()

main()

CLIENT SCRIPT

Launch after already having launched SERVER SCRIPT on your server

#Python 2.5
from socket import *
from select import select
from struct import *
from time import *

import thread
import sys





class Packet :

  def __init__( self, ID ) :
    self.ID = ID
    self.constructionTime = clock()

  def packMe( self ) :
    packed = pack( 'ff', self.ID, self.constructionTime )
    return packed

  def unpackMe( self, data ) :
    unpacked = unpack( 'ff', data )
    return unpacked

  def getDataAsTuple( self ):
    return ( self.ID, self.constructionTime )



  

LocalIPAddress = '127.0.0.1'
RemoteIPAddress = '127.0.0.1'  # CHANGE TO YOUR REMOTE SERVER ADDRESS
TCPSocket = socket( AF_INET, SOCK_STREAM )
TCPPort = 10007

UDPSocket = socket( AF_INET, SOCK_DGRAM )
UDPLocalPort = 10006
UDPRemotePort = 10008
Done = False

cumDiff = 0
cumMsgs = 0

StartTime = clock()

SaveOver = ''

TotalReceivedMessages = 0


def TCPTest():
  
  global cumDiff
  global cumMsgs
  global SaveOver
  global TotalReceivedMessages
  
  def TCPListener() :

    global cumDiff
    global SaveOver
    global TotalReceivedMessages
    
    output = open( "tcplisteneroutput.txt", "w" )
    output.write( 'Listener start'+ '\n'  )
    
    while( Done is False ) :

      try :
        data = TCPSocket.recv( 1024 )
        datalen = len(data)
        output.write( "Now I got "+str(data)+" which is "+str(datalen)+" bytes."+ '\n'  )
      
      except :
        output.write( 'I couldnt recv '+str(sys.exc_info())+ '\n'  )
      
      # This is some packet we already sent
      # and its being echo'd back to us here
 
      # what time is it NOW?
      timeNow = clock()

      # the difference is how long it took to transport
      # there and BACK
      packet = Packet( 1 )
      
      
      # Now, if there IS something saved over from last time, prepend
      # those elements to the array.
      if len( SaveOver ) is not 0 :
        # prepend those leftovers
        
        data = SaveOver + data
      
      
      
      # now compute if there's any
      # left over on THIS iteration
      overChop = datalen % 8
      
      # save over
      lastGood = datalen - overChop 
      SaveOver = data[lastGood:]
      
      
      
      try :
        
        output.write( "Processing " + str( datalen-overChop ) + "\n" )
        
        for i in range( 0, datalen - overChop, 8 ) :
          unpacked = packet.unpackMe( data[i:i+8] )
          diff = timeNow - unpacked[1]
          output.write( "DIFF="+str(diff)+ '\n'  )
          cumDiff += diff 
          TotalReceivedMessages += 1

      except :
        output.write( 'problems unpacking'+str( sys.exc_info())+ '\n'  )
    
    output.close()
    
    
  f = open( "tcpTest.txt", "w" )
  
  # connect to the TCP server and rapidly
  # fire off messages.  the server will send
  # the messages back to you, so you can measure
  # round-trip time
  f.write( "TCP test begin"+ '\n'  )

  try :
    # connect to the server
    addr = ( RemoteIPAddress, TCPPort )
    TCPSocket.connect( addr )
    f.write( 'TCPSocket connected to '+str(addr)+ '\n'  )
    
  except :
    #only get here if something bad happened in try block above
    f.write( "Server couldn't startup! Reason: " + str(sys.exc_info())+ '\n'  )
    TCPSocket.close()
    sys.exit()  # bail if failed



  # start up the listener thread
  thread.start_new_thread( TCPListener, () )


  
  ### TCP TEST
  for i in range( 1, 10000 ) :

    f.write( 'sending packet '+str(i)+ '\n'  )
    packet = Packet( i )

    # serialize and send that packet, also saving it
    # so we can know when it came back.
    data = packet.packMe()

    try :
      TCPSocket.send( data )
      cumMsgs += 1
    except :
      f.write( 'data send failed!' + str(sys.exc_info() )+ '\n'  )

    
  #Done = True
  sleep( 2 )
  
  # done now, so print the average.
  avg = cumDiff / TotalReceivedMessages
  
  endStr = "cumDiff="+str(cumDiff) + \
    " TotalReceivedMessages="+str(TotalReceivedMessages)+ \
    ' The TCP average transport time was '+str(avg)
    
  f.write( endStr + '\n' )
  print endStr
  
  f.close()

  return #/TCPTest
      

def UDPTest():
  print "UDP test begin"
  
  global cumDiff
  global cumMsgs
  global TotalReceivedMessages
  
  def UDPListener() :

    global cumDiff
    global TotalReceivedMessages
    
    output = open( "udplisteneroutput.txt", "w" )
    output.write( 'UDP listener start'+ '\n'  )
  
    while( Done is False ) :

      try :
        ( data, senderAddr ) = UDPSocket.recvfrom( 1024 )
        output.write( "Now I got "+str(data)+" which is "+str(len(data))+" bytes, from "+str(senderAddr)+ '\n' )
        
      except :
        output.write( 'I couldnt recv'+str( sys.exc_info() )+ '\n' )
      
      
      
      # This is some packet we already sent
      # and its being echo'd back to us here
 
      # what time is it NOW?
      timeNow = clock()

      # the difference is how long it took to transport
      # there and BACK
      packet = Packet( 1 )
      
      try :
        # all packets from UDP will always be the same length.
        
        unpacked = packet.unpackMe( data[0:8] )
        diff = timeNow - unpacked[1]
        output.write( "DIFF="+str(diff) + '\n')
        cumDiff += diff 
        TotalReceivedMessages += 1
        
      except :
        output.write( 'problems unpacking '+str( sys.exc_info() )+ '\n' )
        
  # connect to the TCP server and rapidly
  # fire off messages.  the server will send
  # the messages back to you, so you can measure
  # round-trip time
  f = open( "udpTest.txt", "w" )
  
  f.write( "UDP test begin"+ '\n' )

  try :
    # bind this UDP socket.. because we want to be
    # able to receive on it.  we still could if
    # we didn't bind, but it would be a random port
    # and the ports are usually all closed.
    
    addr = ( '', UDPLocalPort )
    UDPSocket.bind( addr )
    f.write( 'UDPSocket BOUND to '+str(addr)+ '\n' )
    
  except :
    #only get here if something bad happened in try block above
    f.write( "Server couldn't startup! Reason: "+str(sys.exc_info())+ '\n' )
    UDPSocket.close()
    sys.exit()  # bail if failed



  # start up the listener thread
  thread.start_new_thread( UDPListener, () )


  
  
  ### UDP TEST
  for i in range( 1, 10000 ) :

    f.write( 'sending packet '+str(i)+ '\n' )
    packet = Packet( i )

    # serialize and send that packet, also saving it
    # so we can know when it came back.
    data = packet.packMe()

    try :
      UDPSocket.sendto( data, ( RemoteIPAddress, UDPRemotePort ) )
      
      print 'Sending',data
      sleep( 0.01 )   # if you send packets too rapidly
      # you will get severe packet loss (possibly due to
      # UDP buffer overflow at the remote host
      
      cumMsgs += 1
    except :
      f.write( 'data send failed! '+str( sys.exc_info() )+ '\n' )

    
  #Done = True
  sleep( 5 )
  # done now, so print the average.
  avg = cumDiff / TotalReceivedMessages
  
  endStr = "cumDiff="+str(cumDiff) + \
    " TotalReceivedMessages="+str(TotalReceivedMessages)+ \
    ' The UDP average transport time was '+str(avg)
  
  print( endStr + '\n' )
  f.write( endStr + '\n' )
  
  return #/TCPTest


def UnstickTCP():
  # unstick sticky socket
  tcpunsticker = socket( AF_INET, SOCK_STREAM )
  
  # connect to MAINSOCKET to basically unstick (unblock) it
  tcpunsticker.connect( ('127.0.0.1', TCPPort) )
  
  tcpunsticker.close()
  
def UnstickUDP():

  udpunsticker = socket( AF_INET, SOCK_DGRAM )
  udpunsticker.sendto( '', ( '127.0.0.1', UDPPort ) )
  udpunsticker.close()
    
# end def Unstick


# rapidly send out
def main():


  inputs = raw_input("(T)CP or (U)DP?")
  
  if( inputs.startswith( 'T' ) ) :
    TCPTest()
    Done = True

  
  elif( inputs.startswith( 'U' ) ) :
    UDPTest()
    Done = True



main()
raw_input("Press enter to continue . . .")


. . . IN A CRUMMY EDITOR!!

Sometimes we forget how SHITTY a dev experience can get when you’re using a crummy code editor.

I have a huge habit of using CTRL+SHIFT together to select “one word at a time”

For instance copy this code into IDLE

x = 'IDLE exhibits "shitty"' \
' behavior'

Now in IDLE, start at the ‘x’, hold down CTRL and press RIGHT. It jumps STRAIGHT to the I in IDLE. Now hold shift down as well. While holding CTRL+SHIFT, press right 3 times, noting what gets highlighted with each step. See how on the third press, it highlights THE WHOLE DADGAM LINE? This makes me furious.

I’d recommend Pydev for eclipse. SO much better. Its really great.

From google cache

 pythonhacker  pythonhacker is offline
Junior Member
	  	
Join Date: Feb 2007
Posts: 11
Default Re: Does Python have static methods ? If not what is the equivalent ?
Python does not have many of the frills and bits that languages like C++ and Java add to OOP.
For example, Python does not have access specifiers like public, protected & private. All member
functions and data are public by default. Privateness can be enforced by certain Pythonic tricks
such as prefixing private attributes with a '__' (double underscore) etc.

In a similar fashion, Python does not have static data members. Any data member defined at the
class level defaults to static in Python. Also since Python has no support for qualifiers (since it is
a dynamic language) it is not easy to support such syntax.

However Python does have support for static functions though they are not exactly the same as
those in C++ or Java. In Python a static function is nothing but a function that is unbounded i.e
it does not define the explicit "self" as the first argument. It also needs to be converted to a static
method by using the "staticmethod" typing for functions. This can be done by an explicit cast
after the function definition or by using a decorator (Python 2.4 & later).

Example...

# Before Python 2.4
class C(object):

def func():
print 'Hi, I am a function!'

func = staticmethod(func)


# Python 2.4 or later
class C(object):

@staticmethod
def func()
print 'Hi, I am a function!'

This can be called on the class or on an instance similar to C++ or Java.

>>> C.func()
'Hi, I am a function!'
>>> c = C()
>>> c.func()
'Hi, I am a function!'

Just like C++ or Java, a static function can only access static attributes, not non-static ones.

Example...
>>> class C(object):
... X = 100
... @staticmethod
... def func():
... print 'Hi I am a function'
... print C.X
... # Try calling a non-static member
... self.func2()
... def func2(self):
... print 'This is function number 2!'

>> c= C()
>>> c.func()
Hi I am a function
100
Traceback (most recent call last):
File "", line 1, in ?
File "", line 8, in func
NameError: global name 'self' is not defined

This is because all instance functions have to define 'self' as an explicit first parameter. This is not
there for static functions.

A point to note is that if you try to convert an instance function to a static member function using
@staticmethod, Python silently allows you to do it. But the function is "lost", i.e it becomes uncallable
from either the instance level or class level because the interpreter gets confused.

Example...
>>> class C(object):
... @staticmethod
... def func(self):
... print 'Hi I am a function!'
...
...
>>> c=C()
>>> c.func()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: func() takes exactly 1 argument (0 given)
>>> C.func()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: func() takes exactly 1 argument (0 given)


This is because, staticmethod conversion is normally done for methods which do not define
the explicit 'self' parameter. When you did the conversion, the interpreter wraps up the original
function in a method wrapper which removes the 'self' from the list of arguments. However the
original function still has 'self' as the first argument. The method wrapper does not pass it.
The error comes out of it.

So be careful when writing static member functions in Python

I’m just wondering.


class Grunt :
  """ Defines a Grunt """
  hp = 650
  attackDamage = 21

  def attack( self, enemy ) :
    print 'Time for killing the %s'%enemy
    return self.attackDamage

  def kill( memememe, myENEMY ) :
    print '%s killing = %s'%(memememe, myENEMY)

print 'Testing classes'
g = Grunt()

dmg = g.attack( 'ogre' )

print 'The grunt did %d damage'%(dmg)

g.kill( 'Centaur' )


It seems so dumb to make the programmer pass “self” into every single member function he defines. Sure, you can rename it apparently

Now that I look at it longer, perhaps this guy has a point.

But still.

its just

test = “hello there”
test[0:5] # gives you characters 0 TO 5 of the string test

You know, Google sucks sometimes.

When doing just a plain old search for “digital audio recorder” the shit floats to the top and the good stuff just isn’t to be seen.

I mean, there are a shitload of really crappy ones at this nextag search result that Google pointed me to at first.

It was only through word of mouth that I heard about the Roland Edirol R-1.

So, I guess the message is, consult all major “sound” companies and see what sound products they create with your needs. Call companies if you have to. Google searching isn’t the end all response (“there aren’t any”).

This is what I use

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

public class Game1 : Microsoft.Xna.Framework.Game
{
  GraphicsDeviceManager graphics;
  SpriteBatch spriteBatch;

  public Game1()
  {
    graphics = new GraphicsDeviceManager( this );
    Content.RootDirectory = "Content";

    this.IsMouseVisible = true ;
  }

  protected override void LoadContent()
  {
    spriteBatch = new SpriteBatch( GraphicsDevice );

  }

  protected override void Update( GameTime gameTime )
  {
    // Allows the game to exit
    if( Keyboard.GetState().IsKeyDown( Keys.Escape ) )
      this.Exit();

    base.Update( gameTime );
  }

  protected override void Draw( GameTime gameTime )
  {
    GraphicsDevice.Clear( Color.CornflowerBlue );

    base.Draw( gameTime );
  }
}

ALSO, I wrap BasicEffect in something I call SimpleEffect. Its also less annoying when you’re just trying to get prims on the screen quick.


public class SimpleEffect : BasicEffect
{
  public SimpleEffect( GraphicsDevice gpu, EffectPool ep )
    : base( gpu, ep )
  {

  }

  public new void Begin()
  {
    base.Begin();

    this.CurrentTechnique.Passes[ 0 ].Begin();
  }

  public new void End()
  {
    this.CurrentTechnique.Passes[ 0 ].End();

    base.End();
  }

}

I’m watching through Mad About You now, and I’m on season 2, episode 20.

I’m so thoroughly disappointed and frustrated with the characters. Well, moreso the relationship between the actors. Something happened, starting from season 2 episode 15 – Virtual Reality. Its hilarious. I laughed out loud quite a few times that episode, hardest at the end.

“I was wrong.”

But that episode is the last good one before things go really downhill for this season.

Its not the writing. Its the actors and how they’re acting. They’re ruining it for me.

Paul acts like he hates his wife. They don’t seem to get along together at all. Yet they go through the motions of the “romantic” stuff that’s part of the script.

The fight scenes are .. disturbing. There’s real anger coming out there, it seems as if everyone’s against Paul.

It seems Paul is a dick.

It seems .. I don’t know. After watching these past few episodes, I started to feel this show is a lie.

They should change the title of this show from Mad About you to just Mad At You.

They’re not mad about each other. All the romance is completely gone and they seem to do nothing but get on each others nerves.

This show _should_ tank after this season, but something good must happen because apparently it doesn’t.

HLSL starter shader

A little background. I find the shader that gets filled in automatically when you .Add new Effect.fx file in XNA 3.0 a little annoying.

For starters, its too long and has too many silly comments that mean nothing to someone who doesn’t know what they’re doing, and are redundant and useless to someone who knows what they’re doing. So the first thing I do is strip them out.

Next, I don’t like/approve of the use of STRUCTS in a shader. Its annoying and bulks up the code. Observe what I mean below. Instead of structs and return values, I’m attaching keyword out to the output parameters. This works perfectly well and doesn’t have any problems or difference from using structs – only it appears cleaner – to me.

float4x4 World;
float4x4 View;
float4x4 Projection;



void VertexShaderFunction(

  float4 Position : POSITION0,
  float4 Color : COLOR0,

  // Outputs (feed directly into the PixelShaderFunction)
  out float4 oPosition : POSITION0,
  out float4 oColor : COLOR0
)
{
  // See http://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter04.html
  
  // Take vertex to world space
  float4 worldPosition = mul( Position, World );
  
  // Take vertex to eye-space
  float4 viewPosition  = mul( worldPosition, View );
  
  // Take vertex to clip-space
  oPosition            = mul( viewPosition, Projection );

  // Simply pass through the color.  If we were using lighting,
  // the color would be affected by the light.
  oColor = Color ;
}



void PixelShaderFunction(
  
  float4 Color : COLOR0,
 
  out float4 oColor : COLOR0
  
)
{
  // just pass through the color as calculated
  // by the vertex shader
  oColor = Color ;
}



technique Technique1
{
  pass Pass1
  {
    VertexShader = compile vs_3_0 VertexShaderFunction();
    PixelShader = compile ps_3_0 PixelShaderFunction();
  }
}

on the qwerty keyboard, you type the following words with the left hand only (more being added all the time!)

words that can be pluralized (e.g. fad and fads) are only included once in the singular (fad only).

see this article also, and this colemak site

bastard

ear
east
eat
ed

daft
deft
dart
dare
dastard

face
fad
fart
fast
fat
fear
fed
feed
fees
fez

gaffer
gas
gat
gear

rasta
recede
receded
red
regressed

sac
sad
sax
saw
seed
sex
swear
sweat
sweet
street

were
waste

right hand

hull
hum

ion

kin
kim

lip

nip
nippy

yuk
yup

andre lamothe’s got it

Follow

Get every new post delivered to your Inbox.

Join 37 other followers