Esempio n. 1
0
 def remove(self, silent_for_socket: 'Socket' = None, silent=False):
     old_sockets = [self.start_socket, self.end_socket]
     if DEBUG: print(" - hide grEdge")
     self.grEdge.hide()
     if DEBUG: print(" - remove grEdge", self.grEdge)
     self.scene.grScene.removeItem(self.grEdge)
     if DEBUG: print("   grEdge:", self.grEdge)
     self.scene.grScene.update()
     if DEBUG: print("# Removing Edge", self)
     if DEBUG: print(" - remove edge from all sockets")
     self.remove_from_sockets()
     if DEBUG: print(" - remove edge from scene")
     try:
         self.scene.removeEdge(self)
     except ValueError:
         pass
     if DEBUG: print(" - everything is done.")
     try:
         for socket in old_sockets:
             if socket and socket.node:
                 if silent:
                     continue
                 if silent_for_socket is not None and socket == silent_for_socket:
                     continue
                 socket.node.onEdgeConnectionChanged(self)
                 if socket.is_input: socket.node.onInputChanged(socket)
     except Exception as e:
         dumpException(e)
Esempio n. 2
0
 def deserialize(self, data, hashmap={}):
     res = super().deserialize(data, hashmap)
     try:
         return True & res
     except Exception as e:
         dumpException(e)
     return res
Esempio n. 3
0
 def onDrop(self, event):
     if event.mimeData().hasFormat(LISTBOX_MIMETYPE):
         eventData = event.mimeData().data(LISTBOX_MIMETYPE)
         dataStream = QDataStream(eventData, QIODevice.ReadOnly)
         pixmap = QPixmap()
         dataStream >> pixmap
         op_code = dataStream.readInt()
         text = dataStream.readQString()
         mouse_position = event.pos()
         scene_position = self.scene.grScene.views()[0].mapToScene(
             mouse_position)
         if DEBUG:
             print("GOT DROP: [%d] '%s'" % (op_code, text), "mouse:",
                   mouse_position, "scene:", scene_position)
         try:
             node = get_class_from_opcode(op_code)(self.scene)
             node.setPos(scene_position.x(), scene_position.y())
             self.scene.history.storeHistory("Created node %s" %
                                             node.__class__.__name__)
         except Exception as e:
             dumpException(e)
         event.setDropAction(Qt.MoveAction)
         event.accept()
     else:
         event.ignore()
Esempio n. 4
0
 def restoreHistoryStamp(self, history_stamp: dict):
     if DEBUG: print("RHS: ", history_stamp['desc'])
     try:
         self.undo_selection_has_changed = False
         previous_selection = self.captureCurrentSelection()
         if DEBUG_SELECTION:
             print("selected nodes before restore:",
                   previous_selection['nodes'])
         self.scene.deserialize(history_stamp['snapshot'])
         for edge in self.scene.edges:
             edge.grEdge.setSelected(False)
         for edge_id in history_stamp['selection']['edges']:
             for edge in self.scene.edges:
                 if edge.id == edge_id:
                     edge.grEdge.setSelected(True)
                     break
         for node in self.scene.nodes:
             node.grNode.setSelected(False)
         for node_id in history_stamp['selection']['nodes']:
             for node in self.scene.nodes:
                 if node.id == node_id:
                     node.grNode.setSelected(True)
                     break
         current_selection = self.captureCurrentSelection()
         if DEBUG_SELECTION:
             print("selected nodes after restore:",
                   current_selection['nodes'])
         if current_selection['nodes'] != previous_selection[
                 'nodes'] or current_selection[
                     'edges'] != previous_selection['edges']:
             if DEBUG_SELECTION: print("\nSCENE: Selection has changed")
             self.undo_selection_has_changed = True
     except Exception as e:
         dumpException(e)
Esempio n. 5
0
 def on_muc(self, event):
     try:
         self.callback(
             'xmpp', 'muc', 'inbound',
             '%s/%s: %s' % (event['room'], event['name'], event['message']))
     except:
         utils.dumpException('exception during on_muc')
Esempio n. 6
0
 def onFileNew(self):
     try:
         subwnd = self.createMdiChild()
         subwnd.widget().fileNew()
         subwnd.show()
     except Exception as e:
         dumpException(e)
Esempio n. 7
0
    def __init__(self, server, userid, password, config, callback):
        self.server = server
        self.password = password
        self.connection = None
        self.channel = None
        self.exchanges = []
        self.config = {}

        self._parseConfig(config)

        try:
            log.info('rmq: building connection %s %s' % (server, userid))
            self.connection = amqp.Connection(server,
                                              userid,
                                              password,
                                              use_threading=False)

            log.debug('rmq: creating channel')
            self.channel = self.connection.channel()

            log.debug('rmq: ticket')
            self.ticket = self.channel.access_request('/data',
                                                      active=True,
                                                      write=True)

            for key in self.config:
                item = self.config[key]
                exchange = item['exchange']
                routing_key = item['key']

                if exchange not in self.exchanges:
                    log.debug('rmq: declaring exchange %s' % exchange)
                    self.channel.exchange_declare(exchange,
                                                  type="topic",
                                                  durable=False,
                                                  auto_delete=False)
                    self.exchanges.append(exchange)

                if 'queue' in item:
                    log.debug('declaring queue %s' % item['queue'])
                    qname, qcount, ccount = self.channel.queue_declare(
                        item['queue'],
                        durable=False,
                        exclusive=False,
                        auto_delete=False)

                    log.info('binding queue %s to exchange %s [%s]' %
                             (item['queue'], exchange, routing_key))
                    self.channel.queue_bind(item['queue'], exchange,
                                            routing_key)

                    if item['listen']:
                        self.channel.basic_consume(item['queue'],
                                                   callback=callback)

        except:
            self.channel = None
            self.connection = None
            utils.dumpException('error during RMQ setup')
Esempio n. 8
0
 def on_message(self, event):
     try:
         # source, type, exchange, key, body
         self.callback('xmpp', 'im', 'inbound',
                       'xmpp.%s/%s' % (event['jid'], event['resource']),
                       event['message'])
     except:
         utils.dumpException('exception during on_message callback')
Esempio n. 9
0
 def edgeDragStart(self, item:'QGraphicsItem'):
     try:
         if DEBUG: print('View::edgeDragStart ~ Start dragging edge')
         if DEBUG: print('View::edgeDragStart ~   assign Start Socket to:', item.socket)
         self.drag_start_socket = item.socket
         self.drag_edge = Edge(self.grScene.scene, item.socket, None, EDGE_TYPE_BEZIER)
         if DEBUG: print('View::edgeDragStart ~   dragEdge:', self.drag_edge)
     except Exception as e: dumpException(e)
 def onSetColorEvent(self):
     try:
         checker = self.color_checker_detector.getBestColorChecker()
         chartsRGB = checker.getChartsRGB()
         self.color_checker_rgb = chartsRGB[:, 1].copy().reshape(24, 1, 3)
         self.color_checker_rgb /= 255.0
     except Exception as e:
         utils.dumpException(e)
Esempio n. 11
0
 def deserialize(self, data, hashmap={}):
     res = super().deserialize(data, hashmap)
     try:
         value = data['value']
         self.edit1.setText(value)
         return True & res
     except Exception as e:
         dumpException(e)
     return res
Esempio n. 12
0
 def check(self):
     result = True
     for exchange in self.exchanges:
         try:
             self.post('***ping***', 'inbound', exchange)
         except:
             result = False
             utils.dumpException('error during rmq sanity check')
     return result
Esempio n. 13
0
 def on_payload(self, event):
     try:
         self.callback(
             'xmpp', 'payload', 'inbound', 'xmpp.payload',
             utils.tostring(event.xml,
                            namespace_map={},
                            cdata=('encoded', )))
     except:
         utils.dumpException('exception during on_payload')
Esempio n. 14
0
 def check(self):
     result = True
     for exchange in self.exchanges:
         try:
             self.post('***ping***', 'inbound', exchange)
         except:
             result = False
             utils.dumpException('error during rmq sanity check')
     return result
Esempio n. 15
0
 def getOutput(self, index: int = 0) -> ['Node', None]:
     try:
         output_socket = self.outputs[index]
         if len(output_socket.edges) == 0: return None
         connecting_edge = output_socket.edges[0]
         other_socket = connecting_edge.getOtherSocket(self.outputs[index])
         return other_socket.node
     except Exception as e:
         dumpException(e)
         return None
Esempio n. 16
0
 def getInputWithSocket(self, index:int=0) -> [('Node', 'Socket'), (None, None)]:
     try:
         input_socket = self.inputs[index]
         if len(input_socket.edges) == 0: return None, None
         connecting_edge = input_socket.edges[0]
         other_socket = connecting_edge.getOtherSocket(self.inputs[index])
         return other_socket.node, other_socket
     except Exception as e:
         dumpException(e)
         return None, None
Esempio n. 17
0
 def getInputWithSocketIndex(self, index:int=0) -> ('Node', int):
     try:
         edge = self.inputs[index].edges[0]
         socket = edge.getOtherSocket(self.inputs[index])
         return socket.node, socket.index
     except IndexError:
         return None, None
     except Exception as e:
         dumpException(e)
         return None, None
Esempio n. 18
0
 def deserialize(self, data, hashmap={}):
     if self.edit1.checkState() != 0:
         self.edit2.setChecked(False)
     if self.edit2.checkState() != 0:
         self.edit1.setChecked(False)
     res = super().deserialize(data, hashmap)
     try:
         return True & res
     except Exception as e:
         dumpException(e)
     return res
Esempio n. 19
0
 def loadFromFile(self, filename):
     with open(filename, "r") as file:
         raw_data = file.read()
         try:
             data = json.loads(raw_data, encoding='utf-8')
             self.deserialize(data)
             self.has_been_modified = False
         except json.JSONDecodeError:
             raise InvalidFile("%s is not a valid JSON file" %
                               os.path.basename(filename))
         except Exception as e:
             dumpException(e)
    def processColorCheckerDetection(self, image: np.ndarray):
        img_draw = image.copy()
        try:
            self.color_checker_detector.process(
                cv2.cvtColor(image, cv2.COLOR_RGB2BGR), cv2.mcc.MCC24)

            checker = self.color_checker_detector.getBestColorChecker()
            cdraw = cv2.mcc.CCheckerDraw_create(checker)
            cdraw.draw(img_draw)
        except Exception as e:
            utils.dumpException(e)

        return img_draw
Esempio n. 21
0
 def updateEditMenu(self):
     try:
         active = self.getCurrentNodeEditorWidget()
         hasMdiChild = (active is not None)
         self.actPaste.setEnabled(hasMdiChild)
         self.actCut.setEnabled(hasMdiChild and active.hasSelectedItems())
         self.actCopy.setEnabled(hasMdiChild and active.hasSelectedItems())
         self.actDelete.setEnabled(hasMdiChild
                                   and active.hasSelectedItems())
         self.actUndo.setEnabled(hasMdiChild and active.canUndo())
         self.actRedo.setEnabled(hasMdiChild and active.canRedo())
     except Exception as e:
         dumpException(e)
Esempio n. 22
0
 def contextMenuEvent(self, event):
     try:
         item = self.scene.getItemAt(event.pos())
         if DEBUG_CONTEXT: print(item)
         if type(item) == QGraphicsProxyWidget:
             item = item.widget()
         if hasattr(item, 'node') or hasattr(item, 'socket'):
             self.handleNodeContextMenu(event)
         elif hasattr(item, 'edge'):
             self.handleEdgeContextMenu(event)
         else:
             self.handleNewNodeContextMenu(event)
         return super().contextMenuEvent(event)
     except Exception as e:
         dumpException(e)
Esempio n. 23
0
 def eval(self):
     if not self.isDirty() and not self.isInvalid():
         print(" _> returning cached %s value:" % self.__class__.__name__, self.value)
         return self.value
     try:
         val = self.evalImplementation()
         return val
     except ValueError as e:
         self.markInvalid()
         self.grNode.setToolTip(str(e))
         self.markDescendantsDirty()
     except Exception as e:
         self.markInvalid()
         self.grNode.setToolTip(str(e))
         dumpException(e)
Esempio n. 24
0
def rmqCallback(msg):
        # for key, val in msg.properties.items():
        #     log.debug('property %s: %s' % (key, str(val)))
        # for key, val in msg.delivery_info.items():
        #     log.debug('info %s: %s' % (key, str(val)))

    try:
        log.debug('msg body: %s' % msg.body)

        try:
            inbound.put(('rmq', 'post', msg.delivery_info['exchange'], msg.delivery_info['routing_key'], msg.body))
            # push('rmq', 'post', msg.delivery_info['exchange'], msg.delivery_info['routing_key'], msg.body)
        except:
            utils.dumpException('error during rmq callback')
    finally:
        msg.channel.basic_ack(msg.delivery_tag)
Esempio n. 25
0
def rmqCallback(msg):
    # for key, val in msg.properties.items():
    #     log.debug('property %s: %s' % (key, str(val)))
    # for key, val in msg.delivery_info.items():
    #     log.debug('info %s: %s' % (key, str(val)))

    try:
        log.debug('msg body: %s' % msg.body)

        try:
            inbound.put(('rmq', 'post', msg.delivery_info['exchange'],
                         msg.delivery_info['routing_key'], msg.body))
            # push('rmq', 'post', msg.delivery_info['exchange'], msg.delivery_info['routing_key'], msg.body)
        except:
            utils.dumpException('error during rmq callback')
    finally:
        msg.channel.basic_ack(msg.delivery_tag)
Esempio n. 26
0
    def deserialize(self, data, hashmap={}, restore_id=True):
        try:
            if restore_id: self.id = data['id']
            hashmap[data['id']] = self

            self.setPos(data['pos_x'], data['pos_y'])
            self.title = data['title']

            data['inputs'].sort(key=lambda socket: socket['index'] + socket[
                'position'] * 10000)
            data['outputs'].sort(key=lambda socket: socket['index'] + socket[
                'position'] * 10000)

            num_inputs = len(data['inputs'])
            num_outputs = len(data['outputs'])

            self.inputs = []
            for socket_data in data['inputs']:
                new_socket = Socket(node=self,
                                    index=socket_data['index'],
                                    position=socket_data['position'],
                                    socket_type=socket_data['socket_type'],
                                    count_on_this_node_side=num_inputs,
                                    is_input=True)

                new_socket.deserialize(socket_data, hashmap, restore_id)
                self.inputs.append(new_socket)

            self.outputs = []
            for socket_data in data['outputs']:
                new_socket = Socket(node=self,
                                    index=socket_data['index'],
                                    position=socket_data['position'],
                                    socket_type=socket_data['socket_type'],
                                    count_on_this_node_side=num_outputs,
                                    is_input=False)

                new_socket.deserialize(socket_data, hashmap, restore_id)
                self.outputs.append(new_socket)
        except Exception as e:
            dumpException(e)

        # also deseralize the content of the node
        res = self.content.deserialize(data['content'], hashmap)

        return True
Esempio n. 27
0
 def startDrag(self, *args, **kwargs):
     try:
         item = self.currentItem()
         op_code = item.data(Qt.UserRole + 1)
         pixmap = QPixmap(item.data(Qt.UserRole))
         itemData = QByteArray()
         dataStream = QDataStream(itemData, QIODevice.WriteOnly)
         dataStream << pixmap
         dataStream.writeInt(op_code)
         dataStream.writeQString(item.text())
         mimeData = QMimeData()
         mimeData.setData(LISTBOX_MIMETYPE, itemData)
         drag = QDrag(self)
         drag.setMimeData(mimeData)
         drag.setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2))
         drag.setPixmap(pixmap)
         drag.exec_(Qt.MoveAction)
     except Exception as e: dumpException(e)
Esempio n. 28
0
    def __init__(self, server, userid, password, config, callback):
        self.server     = server
        self.password   = password
        self.connection = None
        self.channel    = None
        self.exchanges  = []
        self.config     = {}

        self._parseConfig(config)

        try:
            log.info('rmq: building connection %s %s' % (server, userid))
            self.connection = amqp.Connection(server, userid, password, use_threading=False)

            log.debug('rmq: creating channel')
            self.channel = self.connection.channel()

            log.debug('rmq: ticket')
            self.ticket = self.channel.access_request('/data', active=True, write=True)

            for key in self.config:
                item        = self.config[key]
                exchange    = item['exchange']
                routing_key = item['key']

                if exchange not in self.exchanges:
                    log.debug('rmq: declaring exchange %s' % exchange)
                    self.channel.exchange_declare(exchange, type="topic", durable=False, auto_delete=False)
                    self.exchanges.append(exchange)

                if 'queue' in item:
                    log.debug('declaring queue %s' % item['queue'])
                    qname, qcount, ccount = self.channel.queue_declare(item['queue'], durable=False, exclusive=False, auto_delete=False)
    
                    log.info('binding queue %s to exchange %s [%s]' % (item['queue'], exchange, routing_key))
                    self.channel.queue_bind(item['queue'], exchange, routing_key)
    
                    if item['listen']:
                        self.channel.basic_consume(item['queue'], callback=callback)

        except:
            self.channel    = None
            self.connection = None
            utils.dumpException('error during RMQ setup')
Esempio n. 29
0
 def deserialize(self, data:dict, hashmap:dict={}, restore_id:bool=True) -> bool:
     try:
         if restore_id: self.id = data['id']
         hashmap[data['id']] = self
         self.setPos(data['pos_x'], data['pos_y'])
         self.title = data['title']
         data['inputs'].sort(key=lambda socket: socket['index'] + socket['position'] * 10000 )
         data['outputs'].sort(key=lambda socket: socket['index'] + socket['position'] * 10000 )
         num_inputs = len( data['inputs'] )
         num_outputs = len( data['outputs'] )
         for socket_data in data['inputs']:
             found = None
             for socket in self.inputs:
                 if socket.index == socket_data['index']:
                     found = socket
                     break
             if found is None:
                 found = self.__class__.Socket_class(
                     node=self, index=socket_data['index'], position=socket_data['position'],
                     socket_type=socket_data['socket_type'], count_on_this_node_side=num_inputs,
                     is_input=True
                 )
                 self.inputs.append(found)  
             found.deserialize(socket_data, hashmap, restore_id)
         for socket_data in data['outputs']:
             found = None
             for socket in self.outputs:
                 if socket.index == socket_data['index']:
                     found = socket
                     break
             if found is None:
                 found = self.__class__.Socket_class(
                     node=self, index=socket_data['index'], position=socket_data['position'],
                     socket_type=socket_data['socket_type'], count_on_this_node_side=num_outputs,
                     is_input=False
                 )
                 self.outputs.append(found)  
             found.deserialize(socket_data, hashmap, restore_id)
     except Exception as e: dumpException(e)
     if isinstance(self.content, Serializable):
         res = self.content.deserialize(data['content'], hashmap)
         return res
     return True
Esempio n. 30
0
def start(eventHandler):
    global _callback, _rmq, _tyrant

    log.info('Starting process loop')
    try:
        _callback = eventHandler
        _tyrant   = pytyrant.PyTyrant.open('palala.org', 10101)
        _rmq      = rmqService(options.rmqServer, options.rmqUser, options.rmqPassword, options.rmqConfig, rmqCallback)

        if _rmq.check():
            Process(target=defaultHandler, args=(inbound,)).start()
            Process(target=processRMQ, args=(_rmq,)).start()
            result = True
        else:
            log.error('RMQ Environment is not setup as expected')
            result = False
    except:
        utils.dumpException('Error during pull.start()')

    return result
Esempio n. 31
0
def start(eventHandler):
    global _callback, _rmq, _tyrant

    log.info('Starting process loop')
    try:
        _callback = eventHandler
        _tyrant = pytyrant.PyTyrant.open('palala.org', 10101)
        _rmq = rmqService(options.rmqServer, options.rmqUser,
                          options.rmqPassword, options.rmqConfig, rmqCallback)

        if _rmq.check():
            Process(target=defaultHandler, args=(inbound, )).start()
            Process(target=processRMQ, args=(_rmq, )).start()
            result = True
        else:
            log.error('RMQ Environment is not setup as expected')
            result = False
    except:
        utils.dumpException('Error during pull.start()')

    return result
Esempio n. 32
0
 def onFileOpen(self):
     fnames, filter = QFileDialog.getOpenFileNames(
         self, 'Open graph from file', self.getFileDialogDirectory(),
         self.getFileDialogFilter())
     try:
         for fname in fnames:
             if fname:
                 existing = self.findMdiChild(fname)
                 if existing:
                     self.mdiArea.setActiveSubWindow(existing)
                 else:
                     nodeeditor = CalculatorSubWindow()
                     if nodeeditor.fileLoad(fname):
                         self.statusBar().showMessage(
                             "File %s loaded" % fname, 5000)
                         nodeeditor.setTitle()
                         subwnd = self.createMdiChild(nodeeditor)
                         subwnd.show()
                     else:
                         nodeeditor.close()
     except Exception as e:
         dumpException(e)
Esempio n. 33
0
 def edgeDragEnd(self, item:'QGraphicsItem'):
     self.mode = MODE_NOOP
     if DEBUG: print('View::edgeDragEnd ~ End dragging edge')
     self.drag_edge.remove(silent=True)      
     self.drag_edge = None
     try:
         if isinstance(item, QDMGraphicsSocket):
             if item.socket != self.drag_start_socket:
                 for socket in (item.socket, self.drag_start_socket):
                     if not socket.is_multi_edges:
                         if socket.is_input:
                             socket.removeAllEdges(silent=True)
                         else:
                             socket.removeAllEdges(silent=False)
                 new_edge = Edge(self.grScene.scene, self.drag_start_socket, item.socket, edge_type=EDGE_TYPE_BEZIER)
                 if DEBUG: print("View::edgeDragEnd ~  created new edge:", new_edge, "connecting", new_edge.start_socket, "<-->", new_edge.end_socket)
                 for socket in [self.drag_start_socket, item.socket]:
                     socket.node.onEdgeConnectionChanged(new_edge)
                     if socket.is_input: socket.node.onInputChanged(socket)
                 self.grScene.scene.history.storeHistory("Created new edge by dragging", setModified=True)
                 return True
     except Exception as e: dumpException(e)
     if DEBUG: print('View::edgeDragEnd ~ everything done.')
     return False
Esempio n. 34
0
 def leftMouseButtonRelease(self, event:QMouseEvent):
     item = self.getItemAtClick(event)
     try:
         if hasattr(item, "node") or isinstance(item, QDMGraphicsEdge) or item is None:
             if event.modifiers() & Qt.ShiftModifier:
                 event.ignore()
                 fakeEvent = QMouseEvent(event.type(), event.localPos(), event.screenPos(),
                                         Qt.LeftButton, Qt.NoButton,
                                         event.modifiers() | Qt.ControlModifier)
                 super().mouseReleaseEvent(fakeEvent)
                 return
         if self.mode == MODE_EDGE_DRAG:
             if self.distanceBetweenClickAndReleaseIsOff(event):
                 res = self.edgeDragEnd(item)
                 if res: return
         if self.mode == MODE_EDGE_CUT:
             self.cutIntersectingEdges()
             self.cutline.line_points = []
             self.cutline.update()
             QApplication.setOverrideCursor(Qt.ArrowCursor)
             self.mode = MODE_NOOP
             return
         if self.rubberBandDraggingRectangle:
             self.rubberBandDraggingRectangle = False
             current_selected_items = self.grScene.selectedItems()
             if current_selected_items != self.grScene.scene._last_selected_items:
                 if current_selected_items == []:
                     self.grScene.itemsDeselected.emit()
                 else:
                     self.grScene.itemSelected.emit()
                 self.grScene.scene._last_selected_items = current_selected_items
             return
         if item is None:
             self.grScene.itemsDeselected.emit()
     except: dumpException()
     super().mouseReleaseEvent(event)
Esempio n. 35
0
 def on_message(self, event):
     try:
         # source, type, exchange, key, body
         self.callback('xmpp', 'im', 'inbound', 'xmpp.%s/%s' % (event['jid'], event['resource']), event['message'])
     except:
         utils.dumpException('exception during on_message callback')
Esempio n. 36
0
 def on_muc(self, event):
     try:
         self.callback('xmpp', 'muc', 'inbound', '%s/%s: %s' % (event['room'], event['name'], event['message']))
     except:
         utils.dumpException('exception during on_muc')
Esempio n. 37
0
 def on_payload(self, event):
     try:
         self.callback('xmpp', 'payload', 'inbound', 'xmpp.payload', utils.tostring(event.xml, namespace_map={}, cdata=('encoded',)))
     except:
         utils.dumpException('exception during on_payload')
Esempio n. 38
0
def init(basename, configDefaults=None, configItems=None):
    global _daemon

    cwd  = os.path.abspath(os.getcwd())
    home = os.path.expanduser('~')

    _configDefaults = { 'basename':    basename,
                        'daemon':      False,
                        'pidpath':     cwd,
                        'logpath':     cwd,
                        'uid':         None,
                        'console':     True,
                        'debug':       True,
                        'rmqServer':   None,
                        'rmqUser':     '******',
                        'rmqPassword': None,
                        'rmqConfig':   None,
                       }

    palalaConfig = os.path.join(cwd, 'palala.cfg')

    if os.path.isfile(palalaConfig):
        for line in open(palalaConfig, 'r').readlines():
            if not line.startswith('#'):
                item = line[:-1].split('=')
                if len(item) == 2:
                    _configDefaults[item[0]] = item[1]

    if configDefaults is not None:
        for key in configDefaults:
            _configDefaults[key] = configDefaults[key]

    _configItems = { 
        'basename':    ('',   '--name',      _configDefaults['basename'],    'Name of the bot'),
        'daemon':      ('',   '--daemon',    _configDefaults['daemon'],      'run as a daemon',        'b'),
        'pidpath':     ('',   '--pidpath',   _configDefaults['pidpath'],     'pid file path'),
        'logpath':     ('',   '--logpath',   _configDefaults['logpath'],     'log file path'),
        'uid':         ('',   '--uid',       _configDefaults['uid'],         'uid to run as'),
        'console':     ('-e', '--echo',      _configDefaults['console'],     'echo to console',        'b'),
        'debug':       ('-d', '--debug',     _configDefaults['debug'],       'turn on debug messages', 'b'),
        'rmqServer':   ('',   '--rmqserver', _configDefaults['rmqServer'],   'Hostname for RMQ Server'),
        'rmqUser':     ('',   '--rmquser',   _configDefaults['rmqUser'],     'Username to login to RMQ Server'),
        'rmqPassword': ('',   '--rmqpw',     _configDefaults['rmqPassword'], 'User password for RMQ Server'),
        'rmqConfig':   ('',   '--rmqconfig', _configDefaults['rmqConfig'],   'Queue Config file for RMQ Server'),
    }

    if configItems is not None:
        for key in configItems:
            _configItems[key] = configItems[key]

    if 'config' not in _configItems:
        s = os.path.join(home, 'etc', '%s.cfg' % _configDefaults['basename'])
        _configItems['config'] = ('-c', '--config', s, 'Configuration file to load',)

    initOptions(_configItems)
    initLogging()

    if options.daemon:
        try:
            _daemon = daemon.Daemon(pidfile=options.pidfile, user=options.uid, sigterm=handle_sigterm, log=log.fileHandler)
        except:
            utils.dumpException('exception setting up daemon')
            sys.exit(1)

        log.info('forking daemon - pidfile is %s' % options.pidfile)
        _daemon.start()

    log.info('%s starting' % options.basename)