Archive for the ‘Uncategorized’ Category

Cost of forgetting to create database index when needed

08 Apr

Spending the weekend cleaning up and refactoring a project i maintain which i wrote with Python-twisted, i discovered a certain database call seemed to be taking too much time to return.

Time before call: 17:01:16.206000
Time after call: 17:01:24.092000

That is a whooping 7.886 seconds wasted per request.
I am of the habit of going back to my SQLs and looking out for the WHERE clauses to grab my index candidates but on this one, I probably added a fix which got me introducing some database look-ups without matching indexes.

Here is the result after the index fixes

Time before call: 17:26:25.533000
Time after call: 17:26:25.765000

Now this is one of those fixes that brighten your weekend.



Interacting with photoshop, microsoft word and other apps from python via COM API

10 Sep

So i have been working on a python application that must talk to Solid Edge

Solid Edge is a 2d/3d CAD software from Siemens used to create drawings for engineering parts, etc
My job is to modify an existing excel file, launch solid edge’s .par and .dft files, update .dft based on .par,
save both and export both to PDFs.

Looked pretty straightforward, hmm?
This wasn’t, at least for me, so i will try to document how i got this working.

there you go!

import win32com.client,  os, xlsxwriter, struct, pywintypes, sys

from PyQt4 import QtCore, QtGui

def fix_com_exception(e):
    e.hresult = fix_com_hresult(e.hresult)
    e.args = [e.hresult] + list(e.args[1:])
    return e

def fix_com_hresult(hr):
    return struct.unpack("L", struct.pack("l", hr))[0]

def alert(e="Unknown error!"):
    app = QtGui.QApplication(sys.argv)
    QtGui.QMessageBox.warning(QtGui.QWidget(),"Error!", repr(e))

class Drawer:
    def __init__(self):
        print "starting drawing module"

    def modifyExcelFile(self):
        print "modifying excel"

            # Create or overwrite Excel file and add a worksheet.
            workbook = xlsxwriter.Workbook('Excel_Linked_File.xlsx')
            worksheet = workbook.add_worksheet()

            # expand 1st column
            worksheet.set_column('A:A', 20)

            # make first row bold
            bold = workbook.add_format({'bold': True})
            worksheet.write('A1', 'Linked Excel file to a Solid Edge file for a hub.',bold)
            #add description text
            worksheet.write('A3', 'Outer Diameter')
            worksheet.write('A4', 'Wall Thickness')
            worksheet.write('A5', 'Inner Diameter')
            worksheet.write('A6', 'Hole Size')
            worksheet.write('A7', 'Number of Holes')
            worksheet.write('A8', 'Flange Diameter')
            worksheet.write('A9', 'Flange Thickness')
            worksheet.write('A10', 'Height')
            worksheet.write('A11', 'Pitch Circle Diameter')
            #add values
            worksheet.write('B3', 100)
            worksheet.write('B4', 15)
            worksheet.write('B5', 60)
            worksheet.write('B6', 16)
            worksheet.write('B7', 4)
            worksheet.write('B8', 200)
            worksheet.write('B9', 10)
            worksheet.write('B10', 120)
            worksheet.write('B11', 160)

            worksheet.write('B14', 150)

            #add units
            worksheet.write('C3', 'mm')
            worksheet.write('C4', 'mm')
            worksheet.write('C5', 'mm')
            worksheet.write('C6', 'mm')
            worksheet.write('C8', 'mm')
            worksheet.write('C9', 'mm')
            worksheet.write('C10', 'mm')
            worksheet.write('C11', 'mm')
            #write to disk

            print "Excel created successfully!"
        except IOError as e:
            print repr(e)
            print "unknown error"

    def openSolidEdge(self):
        #get date so we know when this got generated
        #launch solid

        print "launching solid edge"
            se = win32com.client.Dispatch("SolidEdge.Application")
            se.Visible=False #when set to false, exported pdfs doesn't show measurements

            print "opening part document"
            objDocuments = se.Documents
            objPart = objDocuments.Open(os.getcwd()+"\Hub.par", "SolidEdge.PartDocument")
            objPart.SaveAs(os.getcwd()+"\Hub_"+gen_date+".par.pdf", )

            print "opening draft document"
            objDraft = objDocuments.Open(os.getcwd()+"\Hub.dft", "SolidEdge.DraftDocument")
            for doc in objDraft.ActiveSheet.DrawingViews:
        except pywintypes.com_error as e:
            print repr(e)
            print "unknown error"

        print "done! opening pdfs..."
        #uncomment next line to kill application after each usage, may be a bad idea if you process files often

        except WindowsError as e:
            print "unknown error"


Dont let this beat you, you can apply same to Photoshop, microsoft excel and other softwares with COM APIs



Fashion Ideas Nigeria

15 Mar

I have been falling deeply in love with pattern inspired designs that i had to write a better app for it.
it is a simple yet useful android app i wrote in actionscript 3 (FYI, flash isn’t dead).

uploaded to Google play on 12th december 2015, The app quickly gathered 1000-5000 downloads and keeps progressing.

Fashion Ideas let you upload your designs for other app users to see and get IDEAS from, that’s the idea.

you can download it here

feel free to upload your designs, how to contact you in case app users want to engage you, if it is good, clear enough, and complies with our “standards” we will feature it for free.



SQL wont return predefined values if table is empty

13 Oct

I have been working on a billing system in python-twisted for a while now. This system used scratch/serial to clear payments.
I had this callback that returns a Decimal.Decimal which is the value of the scratch card.

A little mod was required to allow direct API calls to clear payments, since the scratch/serial approach is still very much active, i figured it will be best to just refactor it all to work such that, if you pass in a scratch/serial, it checks on the database table, if a decimal e.g 1000.0  is passed in, then we have SELECT 1000.0 from scratch_pin_table;

We have 2 twisted servers running, a live and a test server.

everything works fine on the test server but failed on the live server.

Guess why, The test server has some entry in the scratch_pin_table while the Live has nothing because it has been truncated and scratch/pin has never been generated.

The result is

SELECT 1000.0 from scratch_lin_table returns 1000.0 as expected on test server but returns nothing on live.

Am i the only one or we are many who expects that selecting a predefined value in a query will return it even if table it empty?

it turns out that we are wrong.

you really cannot get anything from an empty table if you try that approach.


PyQT not sending browser credentials with subsequent requests

04 Feb

I have been busy lately with Python’s Twisted and PyQT

I built this twisted based API server that requires basic username and password authentication to generate an acces token to be used with subsequent requests.

server works fine when tested with a web browser but i started having issues with the GUI works
I adopted PyQT because of it’s SIGNAL-SLOT approach to threading.

the issue i have with the GUI part is, after getting the access token, i store it in the singleton main application instance
so for every child widget that will interact with the main application instance, i simple pass the famous ‘self’ into the widget

one behaviour i get is this, subsequent requests with the access token passed along fails.

this is because of the way the twisted server reason.

Twisted assumes it is a new request everytime subsequent request is made, this is because at the background, Twisted returns a cookie named TWISTED_SESSION which it expects back. Unfortunately Qhttp isn’t sending it back to the server.


The solution to this is to send it back to the server with subsequent request.

it took about 2 hours to narrow down the problem, i hope you dont have to waste that much time on this.


PyQT 5 had a lot of it’s classes restructured, Classes may not be where they used to be

22 Jun

Well, bandwidth here in Nigeria as at june 2014 is very expensive, so you are better off downloading youtube videos, watch them, re-watch and even show your friends. you will be saving on your internet bill at the end of the day.

Until i figure out why my laptops are always very attractive to …, i have no choice than to put my stuff on github
and everytime someone modifies the ownership of my laptop, i always end up getting to re-install all my stuffs on a new one.

One favorite tool of choice; Youtube downloader.

I never lay my hands on a clean one, always written in java and somehow performs slowly or riddled with ads

so i decided to write one in python and QT and put it up here
feel free to download and re-use


So i decided to write it using PyQT5 and then i noticed a lot has changed since PyQT4

QMainWindow no longer reside in QtGui but now in QWidgets

the signal slot seems to have changed and each signal now seem to have been integrated into each object so instead of binding signals to slots in this old manner

QtCore.QObject.connect(self.main_ui.addURL, QtCore.SIGNAL(“triggered()”), self.showInputForm )

you now must do it like this


I am still discovering them so i shall post them here as i notice the changes.



FTP MLSD problem [Solved]

09 Jan

Well, i always have issues whenever i install a new ftp server and end up spending hours to resolve it

It is wise to document this issue once and for all.

here is the solution

You'll need an additional rule to allow "related" connections. This is due to the FTP protocol using one port for commands and another for data.

iptables -A INPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

Also, there’s a kernel module you’ll need to load for tracking the related connections. It’s called ip_conntrack_ftp but how you load it depends on your distro.

On redhat-ish systems, edit this /etc/sysconfig/iptables-config


Facebook AS3 api Facebook.init() and .login() not Callback Not Called

26 Jun

Just a quick one because i have wasted 2 days on this issue already, i need to get back to work

I have a problem with Facebook graph api where the callback method or function is not being called.

Facebook-as3-api uses javascript to transport the response from the facebook popup back to flash.
For those who dont know, the javascript bridge file is no longer required as it has been replaced with an actionscript version.

back to the solution to your problem. the problem that brought you here.

here are the check lists of what you need to get actionscript working with facebook properly

1. you need 2 javascript file all.js and swfobject.js in the <head></head> section of your page to get this to work at all
you can include the remote versions like this

<script type=”text/javascript” src=””></script>
<script type=”text/javascript” src=””></script>

though i prefer saving a local copy and using that. reason is because some companies will restrict certain websites and i dont want that to mess up my application.


2. you need to add a special div at the top of your page, right after the opening body tag <body>

<div id=”fb-root”></div>


3.  use this snippet to embed your flash movie

<script type=”text/javascript”>
swfobject.embedSWF(“yourfile.swf”, “flashContent”, “1000”, “700”, “9.0”, null, null, null, {name: “flashContent”});



4. Last and the most important of all. Do all your facebook stuff in the Main timeline of your flash application.
use classes and import them freely but make sure you call your Facebook.init() and login() from the main timeline and that the handler function if on this timeline.

somehow, i figured the event gets thrown to the main timeline and wont reach the instance that called it.
this issue also happens with NetConnection when working with a media server. the way out with that it to do a nc.client=this

right inside the class so that updates are forwarded to that class instance when using SharedObjects


i hope this helps someone out there



Fatal error:(Solution) Uncaught exception ‘BadContentTypeException’ with message ‘Required Content-Type not set’ in

27 Aug

Well, i had a nightmare on this, though i have fixed this in the past, i really never thought of documenting it.
well, i paid dearly for with for 3 good days.

here is the famous error that comes up ONLY after you must have gotten everything right, I mean the file permissions, file ownership etc.

Fatal error: Uncaught exception ‘BadContentTypeException’ with message ‘Required Content-Type not set’ in ….

I assume you have the fileinfo extension and magic mime setup already.
if you still get the error after those extensions have been enabled the here is how i finally fixed mine?

Line 1959 of cloudfiles.php is the culprit.

it says

//$local_magic = dirname(__FILE__) . “/share/magic”;

dirname(__FILE__) will resolve to the directory where you have the file you ar running, in my case /var/www/html
so it uses /var/www/html/share/magic as the local magic file, a file that is not there.

so i just removed the dirname() call and specified the full path of the magic file
like this

$local_magic = “/usr/share/magic”; //changed by sledjama

you want to check that the file is in that location or you specify the correct location
try it.


Here is how to setup python 3.2 in Netbeans 6.7

24 Jul

First install python 3.2 on your system

1. Navigate to TOOLS >> PLUGINS
2. on the “Available Plugins” tab, look for python & Jython, and install it.
3. Navigate to TOOLS >> Python Platforms (if you cant find this, go back to step 1.)
4. By default, when you tell Netbeans to autodetect, It wont see 3.2.
so just grab version it sees and modify the path.

on Main tab, set

command: c:\Python32\python.exe
console command: c:\Python32\python.exe
command argument: -u or whatever works for you

on Python Paths tab, add the python paths you will require,
mine here has close to 12 paths


next hit “close”
you can now create new python projects, you may also want update your python template file so that when you ask netbean to create a new py file for you, it doesn’t use the old python print without parenthesis.

And make sure you set netbeans to use the new python setting and not jython or older
One other issue i faced was with getting cx_freeze to create my executables.

when you click build or clean build in netbeans, netbeans passes in the wrong command line argument.
to fix this, you need to update the a particular jar file to reflect the command line argument for cx_freeze

setup build

the file to update it located here

C:\Program Files\NetBeans 6.7\python1\modules\

the file name is

open that file using winrar, the navigate to org\netbeans\modules\python\project\ui\actions

the 2 culprits are


download class editor and open each file with it
class editor can be gotten from here

search and edit the word bd_inst
change it to build and save it

now overwrite the copy using same winrar
restart Netbeans.