case
12Apr/099

How To – Center a image on a canvas in flex


This is the solution for the anoying behaivor of the image control into a canvas or hbox or whatever. If the image is set to be scaled to a maximum width and height and maintaining the aspect ration, it won't center itself even if it has the horizontalCenter set to "0". So...here's how it looks (top) and how it suppose to look (bottom)

canvas How To   Center a image on a canvas in flex

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
    <mx :Script>
        < ![CDATA[
 
                // Maximum  width
                private var mxw:Number = 500;
                // Maximum height
               private var mxh:Number = 250;
 
               public function onImageComplete(e:Event):void
               {
                var wthMaxRatio:Number = mxw / mxh;
 
                // no resize needed
                if (e.target.contentWidth <= mxw && e.target.contentHeight <= mxh)
                {
                    e.target.x = (mxw - e.target.contentWidth) / 2;
                    e.target.y = (mxh - e.target.contentHeight) / 2;
                }
                else
                {
                    var wthImgRatio:Number = e.target.contentWidth / e.target.contentHeight;
 
                    if (wthImgRatio > wthMaxRatio)
                    {
                        // will max out the width
                        e.target.width = mxw;
                        var imgHeight:Number = Math.round( (mxw / e.target.contentWidth) * e.target.contentHeight );
                        var newY:Number = Math.round( (mxh - imgHeight) / 2 );
                        e.target.x = 0;
                        e.target.y = newY;
                    }
                    else
                    {
                        // will max out the height
                        e.target.height = mxh;
                        var imgWidth:Number = Math.round( (mxh / e.target.contentHeight) * e.target.contentWidth );
                        var newX:Number = Math.round( (mxw - imgWidth) / 2 );
                        e.target.x = newX;
                        e.target.y = 0;
                    }
                }
              }
         ]]>
    </mx>
 
 
      <mx :Canvas width="500" height="250"
            verticalScrollPolicy="off" horizontalScrollPolicy="off"
            backgroundColor="#000000">
 
            <mx :Image id="theimage"
                maintainAspectRatio="true"
		scaleContent="true"
                complete="onImageComplete(event)" />
 
        </mx>

3Apr/0951

Right click and custom context menu in Flash/Flex


Anyone know you can customize your flash context menu with ContextMenu class. But what if you want to really get rid of that and use your on context menu or just use the functionality of the right button of the mouse ?

The idea is fairly simple:

1 - Use Javascript in the HTML container page to disable the right-click on top of the SWF.
2 - Capture the event and pass it to a function that communicates with Flash via the External Interface
3 - In Actionscript the function called from Javascript does whatever you need to display your own custom context-menu.

Why would anyone want to do this?

Well, there are several very important reasons:

1. Games – the power of AS3 has brought Flash to the world of digital entertainment. At last it is possible to focus on the idea of your game rather than on how to improve the laggy experience. One thing that is still missing – right click functionality. We had this forever in desktop games, now it is time to let your casual RTS, RPG and FPS creations conquer the web.

2. User Experience – 2 buttons are better than 1. Every experimentalist's dream is to be able to have more input options, not just one button. I can bet someone would soon create a stunning interface using this new functionality

3. RIA – Rich Internet Applications. My clients are often asking if it is possible to remove embeded Flash Player menus from their applications and replace them with their company’s branding stuff.

And the answer is : YES! You can hack it to use custom right-click functionality in Flash and Flex.

Here is the demo and because you won't be able to right click it to View the Sources icon smile Right click and custom context menu in Flash/Flex here they are

Javascript source code looks like this:

var RightClick = {
	init: function () {
		this.FlashObjectID = "RightClickDemo";
		this.FlashContainerID = "flashcontent";
		this.Cache = this.FlashObjectID;
		if(window.addEventListener){
			 window.addEventListener("mousedown", this.onGeckoMouse(), true);
			 document.oncontextmenu = function() { document.getElementById("RightClickDemo").rightClick(); }
		} else {
 
			document.getElementById(this.FlashContainerID).onmouseup = function() { document.getElementById(RightClick.FlashContainerID).releaseCapture(); }
			document.oncontextmenu = function(){ if(window.event.srcElement.id == RightClick.FlashObjectID) { return false; } else { RightClick.Cache = "nan"; }}
			document.getElementById(this.FlashContainerID).onmousedown = RightClick.onIEMouse;
		}
	},
	killEvents: function(eventObject) {
		if(eventObject) {
			if (eventObject.stopPropagation) { eventObject.stopPropagation(); }
			if (eventObject.preventDefault) { eventObject.preventDefault(); }
			if (eventObject.preventCapture) { eventObject.preventCapture(); }
		    if (eventObject.preventBubble) { eventObject.preventBubble(); }
		}
	},
	onGeckoMouse: function(ev) {
		return function(ev) {
		if (ev.button != 0) {
			RightClick.killEvents(ev);
			if(ev.target.id == RightClick.FlashObjectID && RightClick.Cache == RightClick.FlashObjectID) {
                document.getElementById(RightClick.FlashObjectID).rightClick();
			}
			RightClick.Cache = ev.target.id;
		}
	  }
	},
	onIEMouse: function() {
        // stupid ie fix
        if (document.getElementById(RightClick.FlashObjectID + 'x'))
            document.getElementById(RightClick.FlashObjectID + 'x').id =  RightClick.FlashObjectID;
 
		if (event.button> 1) {
			if(window.event.srcElement.id == RightClick.FlashObjectID && RightClick.Cache == RightClick.FlashObjectID) {
				RightClick.call();
			}
			document.getElementById(RightClick.FlashContainerID).setCapture();
			if(window.event.srcElement.id)
			RightClick.Cache = window.event.srcElement.id;
		}
	},
	call: function() {
		document.getElementById(RightClick.FlashObjectID).rightClick();
	}
}

On the Flash side is as simple as this code (AS3):

private function init() : void
{
    ExternalInterface.addCallback("rightClick", onRightClick);
}
 
private function onRightClick():void
{
    var mx:int = stage.mouseX;
    var my:int = stage.mouseY;
 
    if(my > 0 && my < stage.stageHeight && mx > 0 && mx < stage.stageWidth)
    {
        // show a custom context menu or do someting here
    }

On Opera this will not work, the browser forces the context menu to appear and blocks mouse events by default.

Few things you shouldn't forget to make this work

- 2 extra parameters you have to add to the flash object in your html
menu="false"
wmode="opaque"

- add to the body onload event RightClick.init(); function

Note: If you download the sources, you'll see in the html that the "object" tag has an extra 'x' character in the id. that's important to make it work in ie.


28Mar/090

Sudoku solver in python

lens1512255 sudoku12 Sudoku solver in pythonSudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid so that each column, each row, and each of the nine 3×3 boxes (also called blocks or regions) contains the digits from 1 to 9 only one time each. The puzzle setter provides a partially completed grid.
I'm really not a sudoku fan but I love solving problems and sudoku offers you a challenging one. So...here's a the shortest sudoku solver written in python

1
2
3
4
def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import *;r(argv[1])

If you want to test that, save it in a file and use the command line to execute the code. Execute the code as following: python solver.py puzzle - where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank space

python solver.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079

The problem with the above code is that is really slow. Here's another one that runs about 100x faster and is less cryptic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sys
 
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
 
def r(a):
  i = a.find('0')
  if i == -1:
    sys.exit(a)
 
  excluded_numbers = set()
  for j in range(81):
    if same_row(i,j) or same_col(i,j) or same_block(i,j):
      excluded_numbers.add(a[j])
 
  for m in '123456789':
    if m not in excluded_numbers:
      # At this point, m is not excluded by any row, column, or block, so let's place it and recurse
      r(a[:i]+m+a[i+1:])
 
if __name__ == '__main__':
  if len(sys.argv) == 2 and len(sys.argv[1]) == 81:
    r(sys.argv[1])
  else:
    print 'Usage: python sudoku.py puzzle'
26Mar/090

How Software Companies Die

orson scott card 03 225x300 How Software Companies DieThe environment that nurtures creative programmers kills management and marketing types - and vice versa. Programming is the Great Game. It consumes you, body and soul. When you're caught up in it, nothing else matters. When you emerge into daylight, you might well discover that you're a hundred pounds overweight, your underwear is older than the average first grader, and judging from the number of pizza boxes lying around, it must be spring already. But you don't care, because your program runs, and the code is fast and clever and tight. You won.

You're aware that some people think you're a nerd. So what? They're not players. To them C++ is a decent grade, almost a B - not a language. They barely exist. Like soldiers or artists, you don't care about the opinions of civilians. You're building something intricate and fine. They'll never understand it.

BEEKEEPING

Here's the secret that every successful software company is based on: You can domesticate programmers the way beekeepers tame bees. You can't exactly communicate with them, but you can get them to swarm in one place and when they're not looking, you can carry off the honey.

You keep these bees from stinging by paying them money. More money than they know what to do with. But that's less than you might think. You see, all these programmers keep hearing their fathers' voices in their heads saying "When are you going to join the real world?" All you have to pay them is enough money that they can answer (also in their heads) "Geez, Dad, I'm making more than you." On average, this is cheap.

And you get them to stay in the hive by giving them other coders to swarm with. The only person whose praise matters is another programmer. Less-talented programmers will idolize them; evenly matched ones will challenge and goad one another; and if you want to get a good swarm, you make sure that you have at least one certified genius coder that they can all look up to, even if he glances at other people's code only long enough to sneer at it.

He's a Player, thinks the junior programmer. He looked at my code. That is enough. If a software company provides such a hive, the coders will give up sleep, love, health, and clean laundry, while the company keeps the bulk of the money.

OUT OF CONTROL

Here's the problem that ends up killing company after company. All successful software companies had, as their dominant personality, a leader who nurtured programmers. But no company can keep such a leader forever. Either he cashes out, or he brings in management types who end up driving him out, or he changes and becomes a management type himself. One way or another, marketers get control.

But...control of what? Instead of finding assembly lines of productive workers, they quickly discover that their product is produced by utterly unpredictable, uncooperative, disobedient, and worst of all, unattractive people who resist all attempts at management. Put them on a time clock, dress them in suits, and they become sullen and start sabotaging the product. Worst of all, you can sense that they are making fun of you with every word they say.

SMOKED OUT

The shock is greater for the coder, though. He suddenly finds that alien creatures control his life. Meetings, Schedules, Reports. And now someone demands that he PLAN all his programming and then stick to the plan, never improving, never tweaking, and never, never touching some other team's code. The lousy young programmer who once worshipped him is now his tyrannical boss, a position he got because he played golf with some sphincter in a suit.

The hive has been ruined. The best coders leave. And the marketers, comfortable now because they're surrounded by power neckties and they have things under control, are baffled that each new iteration of their software loses market share as the code bloats and the bugs proliferate. Got to get some better packaging. Yeah, that's it.

Orson Scott Card {Windows Sources, March 1995, p. 208}

25Mar/090

Flex and Visual Studio

Visual Studio is really popular with developers and for good reasons. It's fast, has some of the best Intellisense and debuging there is and now you can also use it for Flex authoring. Amethyst is developed by SapphireSteel and it's currently in public Beta.

One of the smartest moves Adobe ever did was to release the Flex SDK and make it easy to integrate it with other code editors. We know of quite a few editors (commercial and open source) that use the SDK, so this is certainly extending the Flex echo-system. Amethyst is a free IDE that builds on Visual Studio. If you already have Visual Studio and the Flex SDK installed, you only need to run the Amethyst installer to get started.

ambeta3 debugger Flex and Visual Studio

Amethyst offers code completion, formatting and intellisense for AS3 and MXML. There's class templates for AS3, AIR, MXML, MXML components and more. The code is color coded and collapsible and all the neat Visual Basic panels such as Object and Solution Explorer works. The Personal Edition of Amethyst will be a free download for always, but some IntelliSense features may be provided in the ‘Professional’ edition only. The latest version was released only days ago and the beta now has super-fast intellisense, so if the slow intellisense in Flex Builder is killing your productivity, this could be worth a shot.

Check out more and download from here