Tuesday, April 24, 2012

Ardor3D transparent quad

I am using Ardor3D for a 3D application in Java. I can draw a quad to the screen with a texture mapped to it. Part of the texture image is transparent, and the quad background shows through there.

How do you make the quad itself transparent, so the rendered scene will show through?

Writing files to Dropbox account from GAE

I am trying to create files in a Dropbox.com folder from a GAE application.
I have done all the steps the register a Dropbox application and installed the Python SDK from Dropbox locally on my development machine. (see dropbox.com API).
It all works perfectly when I use the cli_client.py test script in the dropbox SDK on my local machine to access dropbox - can 'put' files etc.

I now want to start working in GAE environment, so things get a bit tricky.
Some help would be useful.

For those familiar with the Dropbox API code, I had the following issues thus far:

Issue 1

The rest.py Dropbox API module uses pkg_resources to get the certs installed in site-packages of a local machine installation.
I replaced

TRUSTED_CERT_FILE = pkg_resources.resource_filename(__name__, 'trusted-certs.crt')


TRUSTED_CERT_FILE = file('trusted-certs.crt')

and placed the cert file in my GAE application directory. Perhaps this is not quite right; see my authentication error code below.

Issue 2

The session.py Dropbox API module uses oauth module, so I changed the include to appengine oauth.

But raised an exception that GAE's oauth does not have OAuthConsumer method used by the Dropbox session.py module. So i downloaded oauth 1.0 and added to my application an now import this instead of GAE oauth.

Issue 3

GAE ssl module does not seem to have CERT_REQUIRED property.

This is a constant, so I changed

self.cert_reqs = ssl.CERT_REQUIRED


self.cert_reqs = 2

This is used when calling

ssl.wrap_socket(sock, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)

Authentication Error

But I still can't connect to Dropbox:

Status: 401
Reason: Unauthorized
Body: {"error": "Authentication failed"}
Headers: [('date', 'Sun, 19 Feb 2012 15:11:12 GMT'), ('transfer-encoding', 'chunked'), ('connection', 'keep-alive'), ('content-type', 'application/json'), ('server', 'dbws')]

MySQLdb not running on Mac 10.7

I am trying to install MySQL-Python (MySQLdb) locally on my Mac and I am having trouble. I have been working on this for HOURS and I continue to get this error:

>>> import MySQLdb
/Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.pyc, but /Users/dp/Code/MySQL-python-1.2.3 is being added to sys.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "MySQLdb/__init__.py", line 19, in <module>
import _mysql
File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/dp/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Users/dp/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so
Reason: image not found

I am trying to set up a python 2.7/Django/MySQL development environment and keep running into this problem. I have a feeling this could a problem with my .bash_profiles PATH so I am also including that below:

export PATH="/usr/local/mysql/bin:$PATH"

Thank you!!!


Strategy for Dynamic Tags in MongoDB

On Facebook statues, you can start typing an @ and tag a user in a status. This question is not about the frontend, but rather how to store the data for that feature. What is the best way to achieve this functionality in a generic way for representing any mongodb entity in a string in a dynamic way. The goal being if the entity changes, it representation in the stored string also changes. For example one idea I had was this:

Post: {
_id: "48ajsdlfhsdjfkjsljsd"
name: "Post One",
text: "@user is the best for liking @thing, and @thing"
tags: [user:1234, thing:456, thing:789]

So I would load this post, then look at the tags, load the models for each tag type and id, then rewrite the string to be: "Chris is the best for liking StackOverflow, and Mongo". This seems inefficient, any better ideas?

Is it right to say that not all superclass is the high-level component of the subclass?

A "High-Level" component is a class with behavior defined in terms of other "low level" components. Example of this is Bulb class needs Socket class to implements its LightOn() behavior.

Not all superclass is the high-level component and not all subclass is the low-level component. Because of the following examples.

Template method pattern from head first design pattern.

public abstract class CaffeineBeverage {

final void prepareRecipe() {

abstract void brew();

abstract void addCondiments();

void boilWater() {
System.out.println("Boiling water");

void pourInCup() {
System.out.println("Pouring int cup");

public class Coffee extends CaffeineBeverage {

public void brew() {
System.out.println("Dripping Coffee through filter");

public void addCondiments() {
System.out.println("Adding Sugar and Milk");

In this example CaffeineBeverage class has a behavior prepareRecipe(). This behavior needs subclass implementation of brew() and addCondiments().

so... this means here CaffeineBeverage (superclass) is the high-level component and Coffee (subclass) is the low-level component.

public class superClass {
public go() {
//super class implementation

public class subClass extends superClass {
public go() {
//sub class implementation

In this case superClass didnt need subclass to implement its go() method.

Even if a class has abstract method that needs the subclass to implement it DOESNT mean super class is the high level component. See example below.

public abstract class superClass {
public abstract go();

public class subClass extends superClass {
public go() {
//subclass implementation;

main() {
superClass s = new subClass();

Here s is not superClass object... s here is the subClass object.

Byte to string for hash function?

How can I convert passwordHash to string?

    protected RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

public byte[] GenerateSalt()
byte[] salt = new byte[10];
return salt;

public static byte[] Hash(string value, byte[] salt)
return Hash(Encoding.UTF8.GetBytes(value), salt);

public static byte[] Hash(byte[] value, byte[] salt)
byte[] saltedValue = value.Concat(salt).ToArray();

return new SHA256Managed().ComputeHash(saltedValue);

public void AddStudent(Student student)
student.StudentID = (++eCount).ToString();
byte[] passwordHash = Hash(student.Password, GenerateSalt());
student.Password = passwordHash; //this line?
student.TimeAdded = DateTime.Now;

If I try:

    public void AddStudent(Student student)
student.StudentID = (++eCount).ToString();
byte[] passwordHash = Hash(student.Password, GenerateSalt());
student.Password = Convert.ToString(passwordHash); //this line?
student.TimeAdded = DateTime.Now;

When I GET my Student collection the password field will say System.Byte[] where as I want to get the hashed/salted password back?

Getting error with simple select statement on web2py's 'image blog'

For my project, I need to connect to multiple databases and get information from them. I didn't think this would be a problem with web2py, but it was. I thought maybe I need to rebuild the db from scratch, but still had problems. Finally, I went through the introductory 'images' tutorial and changed it to use an alternate mysql database. I still got the same errors, below is the code:


db = DAL("mysql://root:@localhost/web2py")
images_db = DAL("mysql://root:@localhost/images_test")

Field('title', unique=True),
Field('file', 'upload'),
format = '%(title)s')

Field('image_id', images_db.image),
Field('body', 'text'))

Then I went to the admin page for 'images' and clicked the 'shell' link under 'controllers' and did the following: (after I went to the index page to generate the 'images':


In [1] : print db(images_db.image).select()
Traceback (most recent call last):
File "/home/cody/Downloads/web2py/gluon/contrib/shell.py", line 233, in run
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
File "/home/cody/Downloads/web2py/gluon/dal.py", line 7577, in select
fields = adapter.expand_all(fields, adapter.tables(self.query))
File "/home/cody/Downloads/web2py/gluon/dal.py", line 1172, in expand_all
for field in self.db[table]:
File "/home/cody/Downloads/web2py/gluon/dal.py", line 6337, in __getitem__
return dict.__getitem__(self, str(key))
KeyError: 'image'

In [2] : print images_db.has_key('image')

In [3] : print images_db
<DAL {'_migrate_enabled': True, '_lastsql': "SET sql_mode='NO_BACKSLASH_ESCAPES';", '_db_codec': 'UTF-8', '_timings': [('SET FOREIGN_KEY_CHECKS=1;', 0.00017380714416503906), ("SET sql_mode='NO_BACKSLASH_ESCAPES';", 0.00016808509826660156)], '_fake_migrate': False, '_dbname': 'mysql', '_request_tenant': 'request_tenant', '_adapter': <gluon.dal.MySQLAdapter object at 0x2b84750>, '_tables': ['image', 'comment'], '_pending_references': {}, '_fake_migrate_all': False, 'check_reserved': None, '_uri': 'mysql://root:@localhost/images_test', 'comment': <Table {'body': <gluon.dal.Field object at 0x2b844d0>, 'ALL': <gluon.dal.SQLALL object at 0x2b84090>, '_fields': ['id', 'image_id', 'author', 'email', 'body'], '_sequence_name': 'comment_sequence', '_plural': 'Comments', 'author': <gluon.dal.Field object at 0x2b84e10>, '_referenced_by': [], '_format': None, '_db': <DAL {...}>, '_dbt': 'applications/images/databases/e1e448013737cddc822e303fe20f8bec_comment.table', 'email': <gluon.dal.Field object at 0x2b84490>, '_trigger_name': 'comment_sequence', 'image_id': <gluon.dal.Field object at 0x2b84050>, '_actual': True, '_singular': 'Comment', '_tablename': 'comment', '_common_filter': None, 'virtualfields': [], '_id': <gluon.dal.Field object at 0x2b84110>, 'id': <gluon.dal.Field object at 0x2b84110>, '_loggername': 'applications/images/databases/sql.log'}>, 'image': <Table {'ALL': <gluon.dal.SQLALL object at 0x2b84850>, '_fields': ['id', 'title', 'file'], '_sequence_name': 'image_sequence', 'file': <gluon.dal.Field object at 0x2b847d0>, '_plural': 'Images', 'title': <gluon.dal.Field object at 0x2b84610>, '_referenced_by': [('comment', 'image_id')], '_format': '%(title)s', '_db': <DAL {...}>, '_dbt': 'applications/images/databases/e1e448013737cddc822e303fe20f8bec_image.table', '_trigger_name': 'image_sequence', '_loggername': 'applications/images/databases/sql.log', '_actual': True, '_tablename': 'image', '_common_filter': None, 'virtualfields': [], '_id': <gluon.dal.Field object at 0x2b848d0>, 'id': <gluon.dal.Field object at 0x2b848d0>, '_singular': 'Image'}>, '_referee_name': '%(table)s', '_migrate': True, '_pool_size': 0, '_common_fields': [], '_uri_hash': 'e1e448013737cddc822e303fe20f8bec'}>

Now I don't quite understand why I am getting errors here, everything appears to be in order. I thought web2py supported multiple databases? Am I doing it wrong? The appadmin works fine, perhaps I'll edit it and get it to raise an error with the code it's generating... any help would be appreciated.

  • Cody


I just tried this:


db = DAL("mysql://root:@localhost/web2py")

images_db = DAL("mysql://root:@localhost/images_test")

Field('title', unique=True),
Field('file', 'upload'),
format = '%(title)s')

Field('image_id', images_db.image),
Field('body', 'text'))


def index():
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if images_db.has_key('image'):
rows = db(images_db.image).select()
rows = 'nope'
#rows = dir(images_db)
return dict(rows=rows)


{{extend 'layout.html'}}

these are the rows:
{{=rows }}

Again, very confused by all of this. Appreciate any help.

Meteor.http method is undefined on server?

So, I'm trying to write a method that makes an http call. When I run the method, I get the following error:

Exception while invoking method 'upload' TypeError: Cannot call method 'call' of undefined

Here is what the code looks like:


console.log(Meteor.call('upload', f, content));


upload: function(file, content) {
Meteor.http.call("PUT", "http://blah");

Close window in Tkinter message box

link text

How to handle the "End Now" error in the below code:

import Tkinter
from Tkconstants import *
import tkMessageBox

tk = Tkinter.Tk()

class MyApp:

def __init__(self,parent):

self.myparent = parent

self.frame = Tkinter.Frame(tk,relief=RIDGE,borderwidth=2)

self.message = Tkinter.Message(tk,text="Symbol Disolay")

label=Tkinter.Label(self.frame,text="Is Symbol Displayed")

self.button1.bind("<Button-1>", self.button1Click)

self.button2.bind("<Button-1>", self.button2Click)

self.myparent.protocol("WM_DELETE_WINDOW", self.handler)

def button1Click(self, event):
print "pressed yes"

def button2Click(self, event):
print "pressed no"

def handler(self):
if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):

myapp = MyApp(tk)

Why do I get this exception? {An item with the same key has already been added."})


NewSellerID is the result of a lookup on tblSellers. These tables (tblSellerListings and tblSellers) are not "officially" joined with a foreign key relationship, either in the model or in the database, but I want some referential integrity maintained for the future. So my issue remains. Why do I get the exception ({"An item with the same key has already been added."}) with this code, if I don't begin each iteration of the foreach loop with a new ObjectContext and end it with SaveChanges, which I think will affect performance. Also, could you tell me why ORCSolutionsDataService.tblSellerListings (An ADO.NET DataServices/WCF object is not IDisposable, like LINQ to Entities??


// Add listings to previous seller
int NewSellerID = 0;

// Look up existing Seller key using SellerUniqueEBAYID
var qryCurrentSeller = from s in service.tblSellers
where s.SellerEBAYUserID == SellerUserID
select s;

foreach (var s in qryCurrentSeller)
NewSellerID = s.SellerID;

// Save the selected listings for this seller

foreach (DataGridViewRow dgr in dgvRows)

ORCSolutionsDataService.tblSellerListings NewSellerListing = new ORCSolutionsDataService.tblSellerListings();
NewSellerListing.ItemID = dgr.Cells["txtSellerItemID"].Value.ToString();
NewSellerListing.Title = dgr.Cells["txtSellerItemTitle"].Value.ToString();
NewSellerListing.CurrentPrice = Convert.ToDecimal(dgr.Cells["txtSellerItemPrice"].Value);
NewSellerListing.QuantitySold = Convert.ToInt32(dgr.Cells["txtSellerItemSold"].Value);
NewSellerListing.EndTime = Convert.ToDateTime(dgr.Cells["txtSellerItemEnds"].Value);
NewSellerListing.CategoryName = dgr.Cells["txtSellerItemCategory"].Value.ToString();
NewSellerListing.ExtendedPrice = Convert.ToDecimal(dgr.Cells["txtExtendedReceipts"].Value);
NewSellerListing.RetrievedDtime = Convert.ToDateTime(dtSellerDataRetrieved.ToString());
NewSellerListing.SellerID = NewSellerID;





catch (Exception ex)
MessageBox.Show("Unable to add a new case. Exception: " + ex.Message);


Weka: ADTree and LADTree Illegal Options Error

Before I start my question, I should preface it by saying that the main Weka site is down, and I can't access its support pages.

I'm trying to call Weka classifiers from some automation software and I'm running into a problem - I'm calling it with options I know to be legal from the explorer GUI, but I'm getting an exception telling me that those options are illegal:

Explorer classifier path:

weka.classifiers.trees.ADTree -B 10 -E -3

My code:

classifier = trainWekaClassifier(matlab2weka('training', featurelabels, train), trees.ADTree', {strcat('-B 10 -E -3')});

The error is:

??? Java exception occurred:
java.lang.Exception: Illegal options: -B 10 -E -3

at weka.core.Utils.checkForRemainingOptions(Utils.java:482)

at weka.classifiers.trees.ADTree.setOptions(ADTree.java:1144)

Error in ==> trainWekaClassifier at 40

Error in ==> classifier_search at 223
classifier = trainWekaClassifier(matlab2weka('training', featurelabels,
train), 'trees.ADTree', {strcat('-B 10 -E -3')});

Any help you can offer would be greatly appreciated. Thank you!

"Resource interpreted as script but transferred with MIME type text/html."

Sorry if this is actual duplicate but I haven't managed to find answer for my problem.

I load the script with jQuery's $.getScript. But it causes the following error:

Resource interpreted as script but transferred with MIME type text/html.

The problem appears only in Safari under Mac OS

If to look on headers received from the server, they contain Content-Type:application/x-javascript, so I really don't understand what the problem is.

How to highlight a primefaces tree node from backing bean

I am working with primefaces tree component. There is a context menu for the tree (add a node, edit node, delete node). After performing some operation, I need to refresh the tree and then highlight the node added or edited.

This is my code.


<h:outputText value="#{node}" />
<p:contextMenu for="pTree" id="cmenu">
<p:menuitem value="Add topic as child" update="pTree, cmenu"
actionListener="#{treeBean.addChildNode}" />
<p:menuitem value="Add topic Below" update="pTree, cmenu"
actionListener="#{treeBean.addTopicBelow}" />
<p:menuitem value="Delete Topic" update="pTree, cmenu"
actionListener="#{treeBean.deleteNode}" />


public class TreeBean implements Serializable {

private TreeNode root;

public TreeBean() {
root = new DefaultTreeNode("Root", null);
// GET the root nodes first L0
List<TracPojo> rootNodes = SearchDao.getRootNodes111();
Iterator it = rootNodes.iterator();

while (it.hasNext()) {

TracPojo t1 = (TracPojo) it.next();

String tid = t1.getTopicID();

TreeNode node1 = new DefaultTreeNode(t1, root);


public TreeNode getRoot() {
return root;

public void addChildNode(ActionEvent actionEvent)

    List record = NewSearchDao.getRecord(selectedNode);

Iterator it = record.iterator();
while (it.hasNext()) {
Object[] record1 = (Object[]) it.next();
setParentID_dlg((String) record1[0]);
setSortIndex((Integer) record1[2]);


public void saveChilddNode() {
System.out.println("Save as Child Node ........");



Revised Wordpress function to put a Span around the first word of the Title?

I'm trying to use a function that adds a "span" around the first word of every post title in a Wordpress site, and found this extremely similar question. The function in the second answer works fine when there's a link inside the H2 element.

But In my site, I'm not using the post title as a link, so the found solution doesn't work. I've tried to come up with a new preg-replace pattern, as to skip the detection of the link part, but haven't been able to get it.

Basically, I want this:

<h2><?php the_title(); ?></h2> or <h2>Converted post title</h2>

... to become this:

<h2><span>Converted</span> post title</h2>

Setting mandatory permission for a facebook website app

Hello Facebook developpers community,

I'm currently working on a multiplayer online game with HTML/JS.
I just want to allow user to register with the game and I decided to allow them to login with their facebook account. I created a Facebook website application for that.

But when I set a fb:login button on my page, the dialog don't ask me for the permissions I set (FYI : i just configure them in the Authenticated Referrals section).

Maybe I need to configure the permissions in an other place but with the new Auth Dialog, I'm not sure where I need to go..

How to avoid race conditions when using the find_or_create method of DBIx::Class::ResultSet?

From the documentation for find_or_create:

Note: Because find_or_create() reads from the database and then
possibly inserts based on the result, this method is subject to a race
condition. Another process could create a record in the table after
the find has completed and before the create has started. To avoid
this problem, use find_or_create() inside a transaction.

Is it enough to just use find_or_create() inside a transaction in PostgreSQL?

How do I get php to open a pdf file in a new tab?

I don't understand the documentation I've been reading. Can anyone here explain how to do this?

I have a HTML link that goes to a function showFile(). There are two gets, an id, which is the file name, and an ext, the extension of the file.(Only extensions will be pdf, jpg, and gif) I'm using codeigniter framwework btw.

I read stuff about headers but when i tried that it just downloaded the file. Any help would be appreciated.

Function so far ---------

 public function showFile () {
$fileId = $this->input->get('id');
$fileExt = $this->input->get('ext');


Conditional HTML statements for Internet Explorer Detection

Having issues getting my html conditional statements to correctly pull in the IE specific CSS stylesheets. Could somebody please take a look at the top part of my code to see if I have syntax correct?

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<title>Cherokee Cat Clinic</title>
<link rel="stylesheet" type="text/css" href="styles/cherokee.css" />

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="styles/ie/cherokee_ie.css" />
<!--[if IE 9]>
<link rel="stylesheet" type="text/css" href="styles/ie/cherokee_ie.css" />
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="styles/ie/cherokee_ie.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="styles/ie/cherokee_ie.css" />
<!--[if lte IE 6]>
<link rel="stylesheet" type="text/css" href="styles/ie/cherokee_ie.css" />
<style type="text/css">

Also, I am very new to the process of re-building a site for different versions of IE. I have seen Quirks Mode's attribute table, but is there a good compendium of what CSS selectors are /wonky/ in which versions of IE? Or even a good reference thread for Stack Overflow articles on what to watch out for when designing for IE7 & 8?

Thanks in advance!!

Select with Multiple clauses

I have 3 tables with the following columns:

tblClients [ClientID, ClientName, Client Contact]
tblEvents [EventID, EventName]
tblEventBook [EventBookID, EventID, ClientID]


tblEventBook EventID matches tblEvents EventID

tblEventBook ClientID matches tblClients ClientID


I have two parameters, @useEventID and @useClientID

I like to retrieve all records from tblClient where tblEventBook not equals useEventID and useClientID.

I tried to use the below, but it does not works.

SELECT * FROM tblClients 
WHERE tblEventBook.EventID <> @useEventID
AND tblEventBook.ClientID <> @useClientID

AutoSuggestion in a WPF combobox

My combobox returns a set of values from s stored procedure as this

  private void BindCombo()
DataCombo.FillCombo(ComboDS(2313001), cmbClass, 0);
DataCombo.FillCombo(DDCombo(5007), cmbGroup, 0);


I managed to give a rudimentary auto complete suggestion as IsTextSearchenabled but cannot get a auto suggestion box that i would like.

I have seen loads of examples of autocomplete/suggestive textboxes but none of them seem to suit me.