AS3 — Creating TextFields in a loop. Also with dynamic variable names

Judging by the amount of keywords my other AS3 post picked up like “Creating a new text loop in AS3”, I was obliged to answer.

Well, creating textfields in a loop is quite simple. Lets define a bare-minimum TextFormat outside of our loop (unless it needs to change per iteration).

var textFormat:TextFormat = new TextFormat("verdana", 11)

By the way, lets use our little trick we learned about assigning dynamic variable names to movieclips here because the same issue applies: we want access to our textfields in case we want to modify them later. The problem is that after this loop, we have no way of accessing them!

Let’s create an array to store our textfield and create a loop to generate our text fields.

var textFormat:TextFormat = new TextFormat("verdana", 11)

// lets create an array to store all of our textfield references.
var textArray:Array = new Arrray()

// and now the loop
for (var i:int; i < 3; i++) {
    var textField:TextField = new TextField()
    textField.defaultTextFormat = textFormat
    textField.text = 'This is my TextField' + i
    textField.x = 50*i
    addChild(textField)
    textArray.push(textField)
}

This would create 3 textFields with text: “This is my TextField0”, 1, 2.

We can now access those textfields (say the x position was too arbitrary) with our textArray.

textArray[0] = our first textField, textArray[1] = our second one, etc.
textArray[0].x = 500 // to access each object

Here’s a tip for having more useable text in the textFields. After all, the same thing plus a number is quite boring.

We can make another Array that holds the text each textField is supposed to have.

How about:

var text:Array = new Array('First TextField','TextField Two', 'Anything, really')

Now we can run through our loop again according to how many things are defined in our Array called text.

for (var i:int; i < text.length; i++) {
    var textField:TextField = new TextField()
    textField.defaultTextFormat = textFormat
    textField.text = text[i]
    textField.x = 50*i
    addChild(textField)
    textArray.push(textField)
}

This time, our loop will conveniently create as many textFields as you put in the “text” array. In retrospect, naming the textfield reference array textArray was a bad idea, as it forced me to use an uninformative name for the second array. It probably should have been something like: tfReferenceArray, and tfTextArray.

Hope something was useful. There are endless applications for this stuff.

About Tomita Designs (My Brother’s Company)

I decided to write a little page about my brother, Ken Tomita, who sells high end bamboo furniture.

In case you can’t find the big link up top titled: “About Ken Tomita”. Here it is.

I’m giving him a huge spot on this blog in the hopes people might check it out!

I figured people who stumble upon this blog might have an interest in his stuff. If you appreciate great furniture, read what I wrote about him & his work and then check out his site .

Get it while it’s cheap, because the world won’t know what hit him/her/it.

Django — Attaching arbitrary data to anonymous sessions.

Often times it’s necessary to have data stored PER user. A perfect example of this (and my particular problem) is/was a shopping cart: the core of any e-commerce site.

How do we do that? One of the problems is that the users in question are anonymous users. If they were registered users, we could easily take request.user and identify them that way. For anonymous users, we need cookies to identify who’s who.

Luckily Django automatically generates nice cookies that ID the user in a secure fashion (not anything like: logged_in=1) so most of the work is done.

Basically, request.session is a mutable dictionary. Fantastic!

That means you can literally do something like this:
request.session['Arbitrary'] = 'This is Arbitrary Data'

and retrieve it any time you wish in the same fashion:

data = request.session['Arbitrary']

This is useful for a shopping cart because you can create a cart, and put its ID in request.session to know which user session it belongs to.

like so:
newcart = Cart()
request.session['shopping_cart'] = newcart.id

and every time you need to access a users cart request.session['shopping_cart']identifies the cart they are using!

Note: You would have write a statement so that a new cart is created if request.session[‘cart’] is blank. You should have a check in place to do that. If not request.session['shopping_cart'], create cart, else get cart.

This clearly isn’t limited to shopping carts though… Cool stuff.

Django/MySQL: Operand should contain 1 column(s)

Update 12/31/2009:

Straight to the point: This MySQL error in combination with Django might be because django’s ORM is expecting one value when it receives two (example: Model.objects.filter(slug=(‘value1′,’value2’))) or anything that causes 2 values to be returned and passed into the ORM.

Look for places directly affecting the ORM (anything that converts your python code to SQL.. so anything that does a Query).

This is an error I recently got in Django and I couldn’t figure out why.

It is errors like this that don’t give an explanation for WHERE it’s being called that get me on a wild goose chase.

This is a MySQL error meaning you need to use AND. But since Django’s ORM takes care of the SQL for us, it’s hard for us casual users to know whats up.

Turns out one of my statements was passing a pair of values (value1, value2) to the object manager (filter).

So: If you have something like: some_model.objects.filter(field__lte=something), make sure that ‘something’ is a single value, not a pair.

Now it makes sense why a two value pair would throw that MySQL error, if Django treats it like a single value.

Update: Comment from Ben might help others with this problem:

For others who may hit this, I suspect your problem is that get_or_create actually returns a tuple! (the value you think it should return, boolean telling you if the value was created)

Duplicate Key IntegrityError Django

If you are wondering what part of your Django model is wrong because it is spitting out a nameless IntegrityError, it might be this:

I had a model with Unique=True & Blank=True that caused description-less IntegrityErrors because with two objects that have a field ” (blank), or Null, it was no longer unique.

I wanted the field to be Unique, IF and only if it was not blank or null.

I’ll just use Blank=True, null=True and let it be not unique if it ever does.

Website Idea

Shipping zones are a pain to figure out. I’m surprised there isn’t a shipping-zones.com kind of website plastered with ads like the “what time is it” sites.

I should make one in my free time, along with some calculators that integrate with UPS/FedEx/USPS

Why? I need to build a shipping table / zone table for Anuva anyways.

Zone
Number

State
FK Zone

ShippingTable
FK Zone
1 – $x
2 – $y
3 – $z

state = State.objects.get(code=OR)
state.zone.shippingtable_set.get(zone=state.zone).filter(qty<=4).reverse()[0]?

That sounds like a terrible way to go.

Filter the price list by qty so you only see the right prices, reverse them to make [0] the last item, and take that item?

(1 or more, 2 or more, 3 or more, 4 or more)
Filter by at <= 2
(1 or more, 2 or more)
reverse
(2 or more, 1 or more)
[0]
2 or more = price / bottle

Works.. but seems dirty.

I work much better at night.

I work much better when there are zero distractions. No people, no sounds, not anything. Right now it is 2:44AM which is getting late. I feel like I Just woke up though.

I consistently flow more at night. In fact, I’m not sure I have ever gotten into flow during the day while there is so much going on. Phone ringing, people talking, people moving, the world outside moving.

Unfortunately I need to sleep soon, even though I am only starting to get most productive.

Tomorrow there are two of our new guys coming in which is a great (quantitative) distraction. It doesn’t help we have a tasting tomorrow as well. I certainly hope I can meet my deadline for next friday.

Pseudo functioning replacement up & looking all nice.

I doubt I can get all of the shipping calculations working by then so perhaps we will start the marketing with only the club, as previously planned.

How to use pyExcelerator

I found this blog after hours of searching, and I keep referring back to it. I forgot what it was and started searching for it again and had to use terms like pyExcelerator + blog to find the guide.

Anyways, this is a great help for the not so documented pyExcelerator.

http://ntalikeris.blogspot.com/2007/10/create-excel-file-with-python-my-sort.html

 

Note that what comes after here is mainly for me to read back on in the future. I don’t think it makes a whole lotta sense.

I just created something to handle our orders. Currently we have to manually take orders and type out an excel file to do that.

Its the classic programming idea: Spend an hours to finish something in 5 minutes, instead of spending an hour to do it by hand.

Our platform gives us orders in CSV format. Our logistics people take it in a different format. I don’t want to do each by hand.

I wrote something to take the CSV with data, and then a CSV that has a template.

I used the python csv library to split the CSV into keys (the first row) and filled a dictionary with each key having its corresponding value. I then split the template CSV’s data fields into dict keys containing a pair of numbers (row, column).
Therefore, if the original CSV had a field called “BillAddress1”, I would make a template that has the same field and the script would spit back the coordinates.

That way I can write the data from this list into the right spots in the template.

Template CSV to Keys and Coordinates:
reader = csv.reader(file(filename))
 self.d = {}
  reader_list = []
  for item in reader:
  %nbsp;reader_list.append(item)

  for item in reader_list:
    for subitem in item:
      if subitem:
        self.d[subitem] = (reader_list.index(item), item.index(subitem))
    return self.d

This spits out a dictionary of whatever items are in the CSV that correspond to their positions.
If you filled one field in the entire sheet with “Hello” in position (10, 5), it would return a dictionary with key: “Hello” and value (10, 5)

I used those values to position my data in the actual sheet.
For example, say the real CSV has 3 rows.
| Name | Sex | Age |
| Yuji | M | 21 |
| Bob | M | 50 |

My script converts the CSV into a list, so that it can be iterated over.
Simply declare a new list and loop through the object returned by csv.reader() and append each row to the blank list.

I then make a copy of the first item (the keys), and remove that from the list. List.pop(0)
Then, I convert each item in the list to dictionary keys.

So List[0][‘KEY’] = value

Now I just need to create the writing mechanism.

I convert a CSV template to decide where our data goes.

Say I have this template:
| Name | | |
| Age | | |
| | | Sex |

My script converts those into dict keys w/ location pairs. So dict[‘Name’] = 0,0

Therefore, when I write using pyExcelerator:
self.keys = the dictionary with location pairs (the template)
self.orders = list of dictionaries like so [{a:b,c:d}, {a:b, c:d}]


for order in self.orders:
 sheet = self.workbook.add_sheet("Order")
 for item in self.keys:
  a, b = self.keys[item]
  sheet.write(a, b, item)
  sheet.write(a, b+1, order[item])

Done!

To Do

Create Anuva 1.5 with pseudo functionality (this would be simple writes to the DB/File as opposed to credit card integration)

Determine basic pseudo features (they don’t need to be integrated) + model structure

Determine availability of our wines in the states (wine-searcher) for Alder

Close and create new AMEX account
Close and create new Merchant Account

Pay the CC that is being closed?

Listen for WLI invoice + determine whether to wire full amount

Forward Matt’s email address back to us

Features:
I need a wine store now, apparently. This could be problematic.
Make sure we can do a “Sale” price. Previous price being greyed/strikethrough with new price prominent.

A Pre Pay option limited to something I specify
A variable shipping interval.

Issues embedding OpenType Fonts in Flash

Fonts are a real pain to deal with in flash. To do anything useful with them you have to embed them.

For example, you can’t change a textfields alpha without embedding it, or using some hack like turning it into a bitmap and changing the alpha on that. Look at this previous post for how to embed the fonts for alpha control.

I have ttf fonts working as such:
[Embed(source = "C:/Windows/Fonts/Verdana.ttf", fontName = "verdana")]
public static var verdana:Class;
Font.registerFont(AssetManager.HelveticaULE);

but OTF won’t work in the same manner. I have tried using systemFont as well, but this is also a pain for various reasons.

I am simply trying to convert these OTF fonts to TTF, and can’t find many reliable windows programs. Widows makes everything a pain.

FontForge allows you to convert easily but naturally it is open source and Linux. I am working on installing Cygwin the project that tries to create a Unix like environment on Windows.

http://cygwin.com/

But this is another pain. These days I’ve been wondering how useful a Mac would be at this point.