Programming

Java: Multiple Functions and one ErrorHandler

Java: Multiple Functions and one ErrorHandler

Y2K Bug by Cards Against Humanity from The Noun Project

Let’s say you have function fooA() and function fooB() both functions are very similar and throw similar errors.

 public static void fooA(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

     public static void fooB(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }
 

If you have the possibility to avoid duplicating code you could write a single Error handler and pass the Error to the Error handling function. However you still want to be able to distinguish between different types of Exception and for logging purposes you should mention which function actually caused Exception. The easiest way to figure the Method name is to use e.getStackTrace()[0].getMethodName();
Alternatively you can pass the method name to the Errorhandlerfunction. To do that you can figure out the method name via:

 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
 

To determine the various Exceptions there are two possibilities:

Method 1: Use instanceof

The downside to this method is that it is not as readable and identifiable as ErrorHandling function. (However this depends on personal preferences)

     public static void exceptionHandler(Exception e){
         if (e instanceof FileNotFoundException){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         } else if (e instanceof Exception) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }
 

Method 2: re-throw the Error

Well you are still throwing around with errors, but it is clearly identifiable as Error handler.

  public static void exceptionHandler(Exception e){
         try {
             throw e;
         }
         catch (FileNotFoundException e){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         }
         catch(Exception e) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }
 
Posted by happyneal in Programming, 0 comments
Google App Engine: Import CSV to Datastore

Google App Engine: Import CSV to Datastore

Processing CSV Data with the Google App Engine is a two step process.
First you need to upload the data and store it in the blobstore.
Then you retrieve the file and process the information and save it to the Datastore(Database).
You can process the csv data with the standard python tools from the csv module, however instead of parsing a file you must parse a BlobReader.

Posted by happyneal in Python, Web Technologies, 6 comments
Aptana / Eclipse: Set up Git Repository (Github, Bitbucket)

Aptana / Eclipse: Set up Git Repository (Github, Bitbucket)

If you code for yourself or with a team you should be using a code repository. However getting started you need a dedicated server, installation etc. or you take the more convenient route and use one of the many repository providers.

Step 1: Get a Repository

For small teams you can get free Repositories. The two most popular providers are:

  • Github.com: Allows you to host as many open source projects as you like. (private projects cost a monthly fee)
  • Bitbucket.com: Allows a small team to host private projects. (As the team gets bigger you got to pay a monthly fee)

Larger teams, hopefully have the budget to pay for these awesome services.

Step 2: Set up your SSH key

Eclipse and Aptana Studio have Git already integrated. Git uses an encrypted connection to transmit data. You need to provide a SSH keypair.

Check for existing SSH keys

  1. Go to the directory “C:\Users\<username>\.ssh”
  2. Check if the files “id_rsa” and “id_rsa.pub” exist

Generate new SSH keys

If the two files already exist, you can skip this step.

  1. Open git-bash.bat (either by using windows search or navigate to C:\Users\%USRNAME%\Documents\Aptana Studio 3 Workspace\.metadata\.plugins\com.aptana.portablegit.win32\git-bash.bat)
  2. Enter the following command using your correct email-address.
    ssh-keygen -t rsa -C "name@email.com"
  3. For the first question, just press enter.
    Generating public/private rsa key pair.
    # Enter file in which to save the key (/c/Users/you/.ssh/id_rsa):
    
  4. Now enter a passphrase for your key (Password Generator) and confirm the password

Add SSH key to Repository

  1. Go to the directory “C:\Users\<username>\.ssh”
  2. Open the file ‘id_rsa.pub’ in a texteditor
  3. Copy the entire contents to the Clipboard (Ctrl-C)
  4. Open a web browser and login to github.com or bitbucket.com
    • (Github) Click on the “Edit my profile” button on the top right
    • (Bitbucket) Click on your Avatar > “Manage Account”
  5. On the left side navigate to “SSH Keys”
  6. Click “Add SSH key”
  7. Give the key a title (like username with the computer name) and paste the key into the form

Test Connection

  1. Open git-bash.bat
  2. Use the command
    • (Github) ssh git@github.com
    • (Bitbucket) ssh git@bitbucket.com

If everything went well you will get a message like:

Hi username! You’ve successfully authenticated, but GitHub does not provide shell access.

Note: At first I had difficulties to establish a connection. If you are having problems, check if the keys are in the right directory and have the proper names id_rsa and id_rsa.pub.

Source/Further information: Github – https://help.github.com/articles/generating-ssh-keys

Step 3: Set up Aptana/Eclipse

The initial setup is now complete you can now use Eclipse/Aptana to access your Repository.

New/Existing Project

To start using git create or use an existing project.

  1. In the Project Manager, Right-click on the project and select Team > Share Project…Screenshot - 11_19_2013 , 8_43_54 AM
  2. Select the Project, click Create and then Finish.Screenshot - 11_19_2013 , 8_45_51 AM

You now have a local git repository. You now can “Push” the repository to github/bitbucket.

  1. First create a Repository on the website and copy the address of the repository
  2. In the Project Manager, Right-click on the project and select Team > Remotes > Add RemoteScreenshot - 11_19_2013 , 8_52_00 AM
  3. Give the remote a name and paste the address of the repository
  4. Finally push your initial commit with Team > Push

Retrieve from Repository

If you already have a Project stored in your repository and want to retrieve it.

  1. Go to File > Import 
  2. Select Git > Git Repository as New ProjectScreenshot - 11_19_2013 , 8_31_50 AM
  3. Enter the URI of your repository:
    • (Github) git@github.com:<username>/<repository>
    • (Bitbucket) git@bitbucket.com:<username>/<repository>

Use your Repository

Here are some tips on using the repository (well they are based on my experience using SVN, but the same principles apply):

Commit as often as possible

The beauty of subversioning is that you can figure out step by step what parts of your code created the error. When working in a team, always make sure that the entire code is correct and valid and still be compiled/executed.

Write proper commit messages

Always comment what you are currently committing. It helps to rollback to a specific point, and it is a documentation of your work.

Regular updates

When working in a team regularly check that you have the newest version of the code available by doing a “Pull”.

Best Practices

A lot of experts have articles on how to use git effectively in a team. Read up on them and see if they are suitable for your team.  Check out this article about Git Best practices.

Posted by happyneal in Programming, 8 comments
PySide: QPushbutton Text below Icon

PySide: QPushbutton Text below Icon

Apparently using a QPushbutton with a Icon does not work. As alternative I am going to use a QToolbutton.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Widget(QWidget):
    
    def __init__(self, parent= None):
        super(Widget, self).__init__()
        
        layout = QVBoxLayout(self)
        
        #QToolButton
        btn = QToolButton()
        btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        btn.setText("test")
        btn.setIcon(btn.style().standardIcon(QStyle.SP_DirIcon))
        btn.setIconSize(QSize(54,54))
        
        layout.addWidget(btn)
        
        self.setLayout(layout)
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    dialog = Widget()
    dialog.show()

    app.exec_()
Posted by happyneal in Python, 0 comments
PySide: QVBoxLayout with QScrollArea

PySide: QVBoxLayout with QScrollArea

Here is an example that adds Scrollbars to a QVBoxLayout. The one thing that tripped me up was that you need to explicitly create a Widget for the QScrollArea.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Widget(QWidget):
    
    def __init__(self, parent= None):
        super(Widget, self).__init__()
        self.setFixedHeight(200)
        
        #Container Widget        
        widget = QWidget()
        #Layout of Container Widget
        layout = QVBoxLayout(self)
        for _ in range(20):
            btn = QPushButton("test")
            layout.addWidget(btn)
        widget.setLayout(layout)

        #Scroll Area Properties
        scroll = QScrollArea()
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidgetResizable(False)
        scroll.setWidget(widget)
        
        #Scroll Area Layer add 
        vLayout = QVBoxLayout(self)
        vLayout.addWidget(scroll)
        self.setLayout(vLayout)
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    dialog = Widget()
    dialog.show()

    app.exec_()
Posted by happyneal in Python, 1 comment
PySide: QTreeListWidget deleting an Item, editing an Item

PySide: QTreeListWidget deleting an Item, editing an Item

This example creates a QTreeListWidget to display a folder-structure.

import sys, os
from PySide.QtCore import *
from PySide.QtGui import *

class TreeTest(QTreeWidget):
    
    def __init__(self, parent = None):
        super(TreeTest, self).__init__(parent)
        self.setColumnCount(1)
        self.setHeaderLabel("Folders")
        
        actionEdit = QAction("New Folder", self)
        actionEdit.triggered.connect(self.addItemAction)
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.addAction(actionEdit)
        
        actionDelete = QAction("Delete", self)
        actionDelete.triggered.connect(self.deleteItem)
        self.addAction(actionDelete)
        
        self.style()
        
    def addItem(self, name, parent):
        self.expandItem(parent) 
        item = QTreeWidgetItem(parent)
        item.setText(0, name)
        #It is important to set the Flag Qt.ItemIsEditable
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled | Qt.ItemIsEditable)

        item.setIcon(0,self.style().standardIcon(QStyle.SP_DirIcon))
        return item
    
    def addItemAction(self):
        parent = self.currentItem()
        if parent is None:
            parent = self.invisibleRootItem()
        new_item = self.addItem("New Folder", parent)
        self.editItem(new_item)
    
    def deleteItem(self):
        root = self.invisibleRootItem()
        for item in self.selectedItems():
            (item.parent() or root).removeChild(item)
    
if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = QWidget()
    treeWidget = TreeTest()
    layout = QHBoxLayout()
    layout.addWidget(treeWidget)
    
    test.setLayout(layout)
    test.show()
    
    treeWidget.addItem("top", treeWidget.invisibleRootItem())
    item = treeWidget.addItem("item", treeWidget.invisibleRootItem())
    treeWidget.addItem("subitem", item)
    
    app.exec_()
Posted by happyneal in Python, 0 comments