Esempio n. 1
0
    def __init__(self, action, myorca):
        self.action = action
        self.myorca = myorca
        self.config = self.myorca.config

        def cleanUp(*args):
            if hasattr(__main__,"_KCellsOrca"):
                getattr(__main__,"_KCellsOrca").finalized()
        self.action.connect("started(Kross::Action*)", cleanUp)
        self.action.connect("finalized(Kross::Action*)", cleanUp)

        self._view = KCells.view()
        self._setSheet( KCells.currentSheet() )

        def selectionChanged():
            print "Selection changed"
            s = KCells.currentSheet()
            if s:
                if s.sheetName() != self.sheetName:
                    self._setSheet(s)
                    if self.config.sheetNameOnSheetChanged:
                        self.speakSheetName()
                else:
                    if self.config.cellNameOnSelectionChanged:
                        self.speakCellName()
                    if self.config.cellValueOnSelectionChanged:
                        self.speakCellValue()
        self._view.connect("selectionChanged()", selectionChanged)
Esempio n. 2
0
 def startLogging(self, sheetname, cellrange = ""):
     self.sheet = KCells.sheetByName(sheetname)
     self.listener = KCells.createListener(sheetname, cellrange)
     if not self.listener:
         raise "Failed to create listener for sheetname '%s' and range '%s'" % (sheetname,cellrange)
     self.addLog( "Start logging sheet='%s' range='%s'" % (sheetname,cellrange) )
     self.listener.connect("regionChanged(QVariantList)", self.regionChanged)
     self.listener.connect("cellChanged(int,int)", self.cellChanged)
Esempio n. 3
0
 def startLogging(self, sheetname, cellrange=""):
     self.sheet = KCells.sheetByName(sheetname)
     self.listener = KCells.createListener(sheetname, cellrange)
     if not self.listener:
         raise "Failed to create listener for sheetname '%s' and range '%s'" % (
             sheetname, cellrange)
     self.addLog("Start logging sheet='%s' range='%s'" %
                 (sheetname, cellrange))
     self.listener.connect("regionChanged(QVariantList)",
                           self.regionChanged)
     self.listener.connect("cellChanged(int,int)", self.cellChanged)
Esempio n. 4
0
    def showExportDialog(self, reader):
        dialog = self.forms.createDialog("Kexi Export")
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        savepage = dialog.addPage("Save", "Export to Kexi Project File",
                                  "document-save")
        savewidget = self.forms.createFileWidget(
            savepage, "kfiledialog:///kcellskexidbexport")
        savewidget.setMode("Saving")
        savewidget.setFilter(
            "*.kexi *.kexis *kexic|Kexi Project Files\n*|All Files")

        datapage = dialog.addPage("Export", "Export sheets and ranges",
                                  "document-export")
        sheetslistview = KCells.createSheetsListView(datapage)
        sheetslistview.setSelectionType("MultiSelect")
        sheetslistview.setEditorType("Range")

        if dialog.exec_loop():
            projectfile = savewidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise "File '%s' not found." % projectfile
            reader.setSheets(sheetslistview.sheets())
            connection = self.createConnection(projectfile)
            return connection
        return None
Esempio n. 5
0
    def importVCardFile(self, vcardfilename, currentSheet):
        self.componentDict = {}
        self.componentList = []

        writer = KCells.writer()
        if not writer.setSheet(currentSheet):
            raise "Invalid sheet \"%s\" defined." % currentSheet

        writer.next()  #hack
        writer.next()  #hack

        f = open(vcardfilename, 'r')
        lines = []
        for line in f:
            if not line.strip() == "":
                lines.append(line)
                continue
            if len(lines) > 0:
                self.importVCardLines(writer, lines)
                lines = []
        if len(lines) > 0:
            self.importVCardLines(writer, lines)

        if writer.setSheet(currentSheet):
            writer.next()  #hack
            writer.setValues(self.componentList)
Esempio n. 6
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        self.currentpath = self.scriptaction.currentPath()

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog("CSV Export")
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage("Save","Export to CSV File","document-save")
        self.savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kcellscsvexportsave")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.csv *.txt|Comma-Separated-KCValue Files\n*|All Files")

        datapage = self.dialog.addPage("Export","Export Sheets and ranges","document-export")
        self.sheetslistview = KCells.createSheetsListView(datapage)
        self.sheetslistview.setSelectionType("MultiSelect")
        self.sheetslistview.setEditorType("Range")

        optionspage = self.dialog.addPage("Options","Comma Separated KCValue Options","configure")
        self.optionswidget = self.forms.createWidgetFromUIFile(optionspage, os.path.join(self.currentpath, "csvoptions.ui"))

        if self.dialog.exec_loop():
            try:
                self.doExport()
            except:
                self.forms.showMessageBox("Error", "Error", "%s" % "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
Esempio n. 7
0
    def doExport(self):
        reader = KCells.reader()
        reader.setSheets(self.sheetslistview.sheets())

        #if len(reader.sheetNames()) == 0:
        #raise "No sheet to export selected"

        csvfilename = self.savewidget.selectedFile()
        if not csvfilename:
            raise "No CSV file choosen"
        if os.path.splitext(csvfilename)[1] == '':
            csvfilename += '.csv'

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename, 'w')
        csvwriter = csv.writer(csvfile, dialect="custom")

        def changedSheet(sheetname):
            print "changedSheet sheetname=%s" % sheetname
            #csvfile.write("# %s\n" % sheetname)

        def changedRow(row):
            values = reader.currentValues()
            #print "changedRow row=%i values=%s" % (row,values)
            csvwriter.writerow(values)

        reader.connect("changedSheet(QString)", changedSheet)
        reader.connect("changedRow(int)", changedRow)
        reader.start()
        csvfile.close()
Esempio n. 8
0
    def __init__(self, action, config):
        self.action = action
        self.config = config

        forms = Kross.module("forms")
        dialog = forms.createDialog("Import vCard")
        # dialog.minimumWidth = 400
        # dialog.minimumHeight = 300
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  # Auto Plain List Tree Tabbed

        filepage = dialog.addPage("Open", "vCard File", "document-open")
        # deffile = "/home/kde4/vcardtest/addressbook.vcf" #"kfiledialog:///kcellsvcardimport"
        deffile = "kfiledialog:///kcellsvcardimport"
        self.openwidget = forms.createFileWidget(filepage, deffile)
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter("*.vcf|vCard Files\n*|All Files")

        datapage = dialog.addPage("Import", "Import to sheet beginning at cell", "document-import")
        self.sheetslistview = KCells.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("KCCell")

        if not dialog.exec_loop():
            return

        vcardfilename = self.openwidget.selectedFile()
        if not os.path.isfile(vcardfilename):
            raise "File '%s' not found." % vcardfilename

        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise "No current sheet."

        self.importVCardFile(vcardfilename, currentSheet)
Esempio n. 9
0
    def doImport(self):
        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise "No current sheet."

        writer = KCells.writer()
        if not writer.setSheet(currentSheet):
            raise "Invalid sheet \"%s\" defined." % currentSheet

        cell = self.sheetslistview.editor()
        if not writer.setCell(cell):
            raise "Invalid cell \"%s\" defined." % cell

        csvfilename = self.openwidget.selectedFile()
        if not os.path.isfile(csvfilename):
            raise "File '%s' not found." % csvfilename

        #writer.connect("valueChanged()",writer.next)

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename,'r')
        try:
            csvreader = csv.reader(csvfile, dialect="custom")
            try:
                while True:
                    record = csvreader.next()
                    if not writer.setValues(record):
                        print "Failed to set all of '%s' to cell '%s'" % (record,writer.cell())
                    #writer.insertValues(record)
                    writer.next()
            except StopIteration:
                pass
        finally:
            csvfile.close()
Esempio n. 10
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        #self.undostack = KCells.undoStack()
        #self.undostack.connect("indexChanged(int)",self.indexChanged)

        #file = os.path(self.getLogDir(),"KCells.log")

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog("Logger")
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("Plain") #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage("Save","Save to Log File","document-save")
        self.savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kcellslogger")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.txt *.log|Log File\n*|All Files")

        if self.dialog.exec_loop():
            filename = self.savewidget.selectedFile()
            if os.path.isfile(filename):
                if self.forms.showMessageBox("WarningContinueCancel", "Overwrite file?", "The file \"%s\" does already exist. Overwrite the file?" % filename) != "Continue":
                    raise "Aborted."
            sheetname = KCells.currentSheet().sheetName()
            cellrange = "A1:F50" #FIXME
            try:
                self.file = open(filename, "w")
                self.startLogging(sheetname, cellrange)
            except IOError, (errno, strerror):
                raise "Failed to write Log File \"%s\":\n%s" % (filename,strerror)
Esempio n. 11
0
    def _setSheet(self, sheet):
        self.sheet = sheet
        self.sheetName = self.sheet.sheetName()

        self._listener = KCells.createListener(self.sheetName, self.config.sheetRange)
        if not self._listener:
            raise "Failed to create listener"
        def cellChanged(column, row):
            text = self.sheet.text(column, row)
            if text:
                #if self.myorca.isSpeaking():
                #    self.myorca.stop()
                self.myorca.speak(text)
        self._listener.connect("cellChanged(int,int)", cellChanged)

        def sheetNameChanged(*args):
            self.myorca.speak("KCSheet name changed")
        self.sheet.connect("nameChanged()", sheetNameChanged)

        def sheetShowChanged(*args):
            self.myorca.speak("Show sheet %s" % self.sheetName)
        self.sheet.connect("showChanged()", sheetShowChanged)

        def sheetHideChanged(*args):
            self.myorca.speak("Hide sheet %s" % self.sheetName)
        self.sheet.connect("hideChanged()", sheetHideChanged)
Esempio n. 12
0
    def doExport(self):
        reader = KCells.reader()
        reader.setSheets( self.sheetslistview.sheets() )

        #if len(reader.sheetNames()) == 0:
            #raise "No sheet to export selected"

        csvfilename = self.savewidget.selectedFile()
        if not csvfilename:
            raise "No CSV file choosen"
        if os.path.splitext(csvfilename)[1] == '':
            csvfilename += '.csv'

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename,'w')
        csvwriter = csv.writer(csvfile, dialect="custom")

        def changedSheet(sheetname):
            print "changedSheet sheetname=%s" % sheetname
            #csvfile.write("# %s\n" % sheetname)

        def changedRow(row):
            values = reader.currentValues()
            #print "changedRow row=%i values=%s" % (row,values)
            csvwriter.writerow(values)

        reader.connect("changedSheet(QString)",changedSheet)
        reader.connect("changedRow(int)",changedRow)
        reader.start()
        csvfile.close()
Esempio n. 13
0
    def importVCardFile(self, vcardfilename, currentSheet):
        self.componentDict = {}
        self.componentList = []

        writer = KCells.writer()
        if not writer.setSheet(currentSheet):
            raise 'Invalid sheet "%s" defined.' % currentSheet

        writer.next()  # hack
        writer.next()  # hack

        f = open(vcardfilename, "r")
        lines = []
        for line in f:
            if not line.strip() == "":
                lines.append(line)
                continue
            if len(lines) > 0:
                self.importVCardLines(writer, lines)
                lines = []
        if len(lines) > 0:
            self.importVCardLines(writer, lines)

        if writer.setSheet(currentSheet):
            writer.next()  # hack
            writer.setValues(self.componentList)
Esempio n. 14
0
    def showImportDialog(self, writer):
        dialog = self.forms.createDialog("Kexi Import")
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        openpage = dialog.addPage("Open","Import from Kexi Project File","document-open")
        openwidget = self.forms.createFileWidget(openpage, "kfiledialog:///kcellskexidbimportopen")
        openwidget.setMode("Opening")
        openwidget.setFilter("*.kexi *.kexis *kexic|Kexi Project Files\n*|All Files")

        datapage = dialog.addPage("Import","Import to sheet beginning at cell","document-import")
        sheetslistview = KCells.createSheetsListView(datapage)
        sheetslistview.setEditorType("KCCell")

        if dialog.exec_loop():
            projectfile = openwidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise "File '%s' not found." % projectfile

            currentSheet = sheetslistview.sheet()
            if not currentSheet:
                raise "No current sheet."
            if not writer.setSheet(currentSheet):
                raise "Invalid sheet \"%s\" defined." % currentSheet

            cell = sheetslistview.editor()
            if not writer.setCell(cell):
                raise "Invalid cell \"%s\" defined." % cell

            connection = self.createConnection(projectfile)
            return connection
        return None
Esempio n. 15
0
 def selectionChanged():
     print "Selection changed"
     s = KCells.currentSheet()
     if s:
         if s.sheetName() != self.sheetName:
             self._setSheet(s)
             if self.config.sheetNameOnSheetChanged:
                 self.speakSheetName()
         else:
             if self.config.cellNameOnSelectionChanged:
                 self.speakCellName()
             if self.config.cellValueOnSelectionChanged:
                 self.speakCellValue()
Esempio n. 16
0
        def update(argument):
            print "Yweather.update !"
            location = argument[0]  #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KCells.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(
                    location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(
                    namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp
Esempio n. 17
0
        def update(argument):
            print "Yweather.update !"
            location = argument[0] #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KCells.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp
Esempio n. 18
0
    def start(self):
        reader = KCells.reader()

        connection = self.showExportDialog(reader)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()

            tableschema = self.showTableDialog(connection)
            if not tableschema:
                return

            fieldlist = tableschema.fieldlist()

            print "tableschema.name() = %s" % tableschema.name()
            print "tableschema.caption() = %s" % tableschema.caption()
            print "tableschema.description() = %s" % tableschema.description()
            print "fieldlist.names() = %s" % fieldlist.names()

            def changedSheet(sheetname):
                print "changedSheet sheetname=%s" % sheetname

            def changedRow(row):
                values = reader.currentValues()
                #values = [ "%s" % v for v in reader.currentValues() ]

                print "changedRow row=%i values=%s" % (row,values)
                if connection.insertRecord(fieldlist, values):
                    pass
                else:
                    print "=> insert failed: %s" % connection.lastError()

            reader.connect("changedSheet(QString)",changedSheet)
            reader.connect("changedRow(int)",changedRow)
            reader.start()

        finally:
            connection.disconnect()
Esempio n. 19
0
    def start(self):
        reader = KCells.reader()

        connection = self.showExportDialog(reader)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()

            tableschema = self.showTableDialog(connection)
            if not tableschema:
                return

            fieldlist = tableschema.fieldlist()

            print "tableschema.name() = %s" % tableschema.name()
            print "tableschema.caption() = %s" % tableschema.caption()
            print "tableschema.description() = %s" % tableschema.description()
            print "fieldlist.names() = %s" % fieldlist.names()

            def changedSheet(sheetname):
                print "changedSheet sheetname=%s" % sheetname

            def changedRow(row):
                values = reader.currentValues()
                #values = [ "%s" % v for v in reader.currentValues() ]

                print "changedRow row=%i values=%s" % (row, values)
                if connection.insertRecord(fieldlist, values):
                    pass
                else:
                    print "=> insert failed: %s" % connection.lastError()

            reader.connect("changedSheet(QString)", changedSheet)
            reader.connect("changedRow(int)", changedRow)
            reader.start()

        finally:
            connection.disconnect()
Esempio n. 20
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        self.currentpath = self.scriptaction.currentPath()

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog("CSV Import")
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        openpage = self.dialog.addPage("Open", "Import from CSV File",
                                       "document-open")
        self.openwidget = self.forms.createFileWidget(
            openpage, "kfiledialog:///kcellscsvimportopen")
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter(
            "*.csv *.txt|Comma-Separated-KCValue Files\n*|All Files")

        datapage = self.dialog.addPage("Import",
                                       "Import to sheet beginning at cell",
                                       "document-import")
        self.sheetslistview = KCells.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("KCCell")

        optionspage = self.dialog.addPage("Options",
                                          "Comma Separated KCValue Options",
                                          "configure")
        self.optionswidget = self.forms.createWidgetFromUIFile(
            optionspage, os.path.join(self.currentpath, "csvoptions.ui"))

        if self.dialog.exec_loop():
            try:
                self.doImport()
            except:
                self.forms.showMessageBox(
                    "Error", "Error", "%s" % "".join(
                        traceback.format_exception(sys.exc_info()[0],
                                                   sys.exc_info()[1],
                                                   sys.exc_info()[2])))
Esempio n. 21
0
    def showExportDialog(self, reader):
        dialog = self.forms.createDialog("Kexi Export")
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        savepage = dialog.addPage("Save","Export to Kexi Project File","document-save")
        savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kcellskexidbexport")
        savewidget.setMode("Saving")
        savewidget.setFilter("*.kexi *.kexis *kexic|Kexi Project Files\n*|All Files")

        datapage = dialog.addPage("Export","Export sheets and ranges","document-export")
        sheetslistview = KCells.createSheetsListView(datapage)
        sheetslistview.setSelectionType("MultiSelect")
        sheetslistview.setEditorType("Range")

        if dialog.exec_loop():
            projectfile = savewidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise "File '%s' not found." % projectfile
            reader.setSheets( sheetslistview.sheets() )
            connection = self.createConnection(projectfile)
            return connection
        return None
Esempio n. 22
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        #self.undostack = KCells.undoStack()
        #self.undostack.connect("indexChanged(int)",self.indexChanged)

        #file = os.path(self.getLogDir(),"KCells.log")

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog("Logger")
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("Plain")  #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage("Save", "Save to Log File",
                                       "document-save")
        self.savewidget = self.forms.createFileWidget(
            savepage, "kfiledialog:///kcellslogger")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.txt *.log|Log File\n*|All Files")

        if self.dialog.exec_loop():
            filename = self.savewidget.selectedFile()
            if os.path.isfile(filename):
                if self.forms.showMessageBox(
                        "WarningContinueCancel", "Overwrite file?",
                        "The file \"%s\" does already exist. Overwrite the file?"
                        % filename) != "Continue":
                    raise "Aborted."
            sheetname = KCells.currentSheet().sheetName()
            cellrange = "A1:F50"  #FIXME
            try:
                self.file = open(filename, "w")
                self.startLogging(sheetname, cellrange)
            except IOError, (errno, strerror):
                raise "Failed to write Log File \"%s\":\n%s" % (filename,
                                                                strerror)
Esempio n. 23
0
    def start(self):
        writer = KCells.writer()

        connection = self.showImportDialog(writer)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()
            print "queryNames = %s" % connection.queryNames()

            queryschema = self.showTableDialog(connection)
            if not queryschema:
                return

            print "queryschema.name() = %s" % queryschema.name()
            print "queryschema.caption() = %s" % queryschema.caption()
            print "queryschema.description() = %s" % queryschema.description()

            cursor = connection.executeQuerySchema(queryschema)
            if not cursor:
                raise "Failed to create cursor."
            if not cursor.moveFirst():
                raise "The cursor has no records to read from."

            while not cursor.eof():
                record = []
                for i in range( cursor.fieldCount() ):
                    record.append( cursor.value(i) )
                if writer.setValues(record):
                    writer.next()
                else:
                    print "Failed to set all of '%s' to cell '%s'" % (record,writer.cell())
                cursor.moveNext()
        finally:
            connection.disconnect()
Esempio n. 24
0
    def __init__(self, action, config):
        self.action = action
        self.config = config

        forms = Kross.module("forms")
        dialog = forms.createDialog("Import vCard")
        #dialog.minimumWidth = 400
        #dialog.minimumHeight = 300
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        filepage = dialog.addPage("Open", "vCard File", "document-open")
        #deffile = "/home/kde4/vcardtest/addressbook.vcf" #"kfiledialog:///kcellsvcardimport"
        deffile = "kfiledialog:///kcellsvcardimport"
        self.openwidget = forms.createFileWidget(filepage, deffile)
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter("*.vcf|vCard Files\n*|All Files")

        datapage = dialog.addPage("Import",
                                  "Import to sheet beginning at cell",
                                  "document-import")
        self.sheetslistview = KCells.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("KCCell")

        if not dialog.exec_loop():
            return

        vcardfilename = self.openwidget.selectedFile()
        if not os.path.isfile(vcardfilename):
            raise "File '%s' not found." % vcardfilename

        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise "No current sheet."

        self.importVCardFile(vcardfilename, currentSheet)
Esempio n. 25
0
    def doImport(self):
        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise "No current sheet."

        writer = KCells.writer()
        if not writer.setSheet(currentSheet):
            raise "Invalid sheet \"%s\" defined." % currentSheet

        cell = self.sheetslistview.editor()
        if not writer.setCell(cell):
            raise "Invalid cell \"%s\" defined." % cell

        csvfilename = self.openwidget.selectedFile()
        if not os.path.isfile(csvfilename):
            raise "File '%s' not found." % csvfilename

        #writer.connect("valueChanged()",writer.next)

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename, 'r')
        try:
            csvreader = csv.reader(csvfile, dialect="custom")
            try:
                while True:
                    record = csvreader.next()
                    if not writer.setValues(record):
                        print "Failed to set all of '%s' to cell '%s'" % (
                            record, writer.cell())
                    #writer.insertValues(record)
                    writer.next()
            except StopIteration:
                pass
        finally:
            csvfile.close()
Esempio n. 26
0
#!/usr/bin/env kross

import time, Kross, KCells

func = KCells.function("PYTIME")
func.minparam = 0
func.maxparam = 1
func.comment = "The PYTIME() function displays the current datetime."
func.syntax = "PYTIME(string)"
func.addParameter("String", "The datetime format string.")
func.addExample("PYTIME()")
func.addExample("PYTIME(\"%H:%M.%S\")")
func.addExample("PYTIME(\"%Y-%M-%d\")")


def update(args):
    try:
        func.result = time.strftime(args[0] or "%H:%M.%S")
    except:
        func.error = "Invalid format"


func.connect("called(QVariantList)", update)
func.registerFunction()
Esempio n. 27
0
 def speakSheetName(self):
     n = KCells.view().sheet()
     self.myorca.speak(n)
Esempio n. 28
0
#!/usr/bin/env kross

import re, Kross, KCells

func = KCells.function("PYREGEXP")
func.minparam = 3
func.maxparam = 3
func.comment = "The PYREGEXP() function displays the current datetime."
func.syntax = "PYREGEXP(string)"
func.addParameter("String", "The input string.")
func.addParameter("String", "The regular expression.")
func.addParameter("String", "Replace with.")
func.addExample("PYREGEXP(\"Some String\",\"(S|m)\",\"A\")")

def update(args):
    s = args[0]
    regexp = args[1]
    repl = args[2]
    try:
        p = re.compile(regexp)
        func.result = p.sub(repl, s)
    except:
        func.error = "Invalid regexp"

func.connect("called(QVariantList)", update)
func.registerFunction()
Esempio n. 29
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KCells.function("YFINANCE")
        func.minparam = 3
        func.maxparam = 3
        func.comment = (
            "The YFINANCE() function uses the Yahoo! Finance Web Service "
            "to display stock values of a defined ticker symbol. ")
        func.syntax = "YFINANCE(string,string,string)"
        func.addParameter("String", "The ticker symbol.")
        func.addParameter("String", "The date.")
        func.addParameter(
            "String",
            "The type: Date, Open, High, Low, Close, Volume or AdjClose.")
        func.addExample("YFINANCE(\"YHOO\";\"20060119\";\"Open\")")
        func.addExample("YFINANCE(\"=C14\";\"=C15\";\"=C16\")")

        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0]  #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KCells.currentSheet().text(ticker[1:])

            todate = argument[1]  #e.g. "20060119"
            if todate.startswith('='):
                todate = KCells.currentSheet().text(todate[1:])
            fromdate = todate

            typename = argument[2]  #e.g. "Open"
            if typename.startswith('='):
                typename = KCells.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = "Invalid symbol"
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = "Invalid date"
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = "Invalid type"
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = "Web services request failed"
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0, len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = "No stock"
                return
            if len(resultlist) < 7:
                func.error = "Invalid stock"
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v, resultlist)
            func.result = v

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Esempio n. 30
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KCells.function("YWEATHER")
        func.minparam = 1
        func.maxparam = 2
        func.comment = (
            "The YWEATHER() function uses the Yahoo! Weather Web Service "
            "to display the weather of a location. ")
        func.syntax = "YWEATHER(string;string)"
        func.addParameter(
            "String",
            "The US zip code, Location ID or cell that contains them.")
        func.addParameter("String",
                          "Units for temperature. f=Fahrenheit and c=Celsius")
        func.addExample("YWEATHER(\"=A1\")")
        func.addExample("YWEATHER(\"GMXX0151\";\"c\")")

        def update(argument):
            print "Yweather.update !"
            location = argument[0]  #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KCells.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(
                    location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(
                    namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Esempio n. 31
0
        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0] #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KCells.currentSheet().text(ticker[1:])

            todate = argument[1] #e.g. "20060119"
            if todate.startswith('='):
                todate = KCells.currentSheet().text(todate[1:])
            fromdate=todate

            typename = argument[2] #e.g. "Open"
            if typename.startswith('='):
                typename = KCells.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = "Invalid symbol"
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = "Invalid date"
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = "Invalid type"
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = "Web services request failed"
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0,len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = "No stock"
                return
            if len(resultlist) < 7:
                func.error = "Invalid stock"
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v,resultlist)
            func.result = v
Esempio n. 32
0
 def speakCellValue(self):
     sheet = KCells.currentSheet()
     (x1,y1,x2,y2) = KCells.view().selection()
     t = sheet.text(x1,y1)
     self.myorca.speak(t)
Esempio n. 33
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KCells.function("YFINANCE")
        func.minparam = 3
        func.maxparam = 3
        func.comment = (
            "The YFINANCE() function uses the Yahoo! Finance Web Service "
            "to display stock values of a defined ticker symbol. "
        )
        func.syntax = "YFINANCE(string,string,string)"
        func.addParameter("String", "The ticker symbol.")
        func.addParameter("String", "The date.")
        func.addParameter("String", "The type: Date, Open, High, Low, Close, Volume or AdjClose.")
        func.addExample("YFINANCE(\"YHOO\";\"20060119\";\"Open\")")
        func.addExample("YFINANCE(\"=C14\";\"=C15\";\"=C16\")")

        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0] #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KCells.currentSheet().text(ticker[1:])

            todate = argument[1] #e.g. "20060119"
            if todate.startswith('='):
                todate = KCells.currentSheet().text(todate[1:])
            fromdate=todate

            typename = argument[2] #e.g. "Open"
            if typename.startswith('='):
                typename = KCells.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = "Invalid symbol"
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = "Invalid date"
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = "Invalid type"
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = "Web services request failed"
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0,len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = "No stock"
                return
            if len(resultlist) < 7:
                func.error = "Invalid stock"
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v,resultlist)
            func.result = v

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Esempio n. 34
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KCells.function("YWEATHER")
        func.minparam = 1
        func.maxparam = 2
        func.comment = (
            "The YWEATHER() function uses the Yahoo! Weather Web Service "
            "to display the weather of a location. "
        )
        func.syntax = "YWEATHER(string;string)"
        func.addParameter("String", "The US zip code, Location ID or cell that contains them.")
        func.addParameter("String", "Units for temperature. f=Fahrenheit and c=Celsius")
        func.addExample("YWEATHER(\"=A1\")")
        func.addExample("YWEATHER(\"GMXX0151\";\"c\")")

        def update(argument):
            print "Yweather.update !"
            location = argument[0] #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KCells.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Esempio n. 35
0
        def __init__(self, functions, name, comment, format, params):
            self.__name__ = "R_%s" % name.upper()
            #self.__name__ = "R.%s" % name.upper()

            try:
                self.robj = getattr(rpy.r, name)
                self.isNewFunc = not KCells.hasFunction(self.__name__)
                if self.isNewFunc:

                    def format2name(fchar):
                        if fchar == 'f': return 'Float'
                        if fchar == 'i': return 'Int'
                        if fchar == 's': return 'String'
                        if fchar == 'b': return 'Boolean'
                        raise "Unknown format char '%s'" % fchar

                    def format2value(fchar, value):
                        if fchar == 'f': return float(value or 0.0)
                        if fchar == 'i': return int(value or 0)
                        if fchar == 's': return "%s" % (value or '')
                        if fchar == 'b':
                            if type(value) == types.StringType:
                                v = value.strip().lower()
                                return bool( len(v)>0 and v!='0' and v!='no' and v!='false' )
                            else:
                                return bool(value)
                        raise "Unknown format char '%s' with value '%s'" % (fchar,value)

                    try:
                        req,opt = format.split('|')
                    except ValueError:
                        req,opt = [ format, [] ]

                    func = KCells.function(self.__name__)

                    func.typeName = 'Float'
                    func.comment = comment

                    func.syntax = "%s(%s)" % (self.__name__,', '.join([ p.split(':')[0] for p in params ]))
                    #func.syntax = "%s(%s)" % (self.__name__,', '.join([ format2name(r) for r in req ]))

                    func.minparam = len(req)
                    func.maxparam = func.minparam + len(opt)
                    for i in range(0,len(req)):
                        func.addParameter(format2name(req[i]), params[i].split(':')[1])
                    for i in range(0,len(opt)):
                        func.addParameter(format2name(opt[i]), params[len(req)+i].split(':')[1])

                    def callback(arguments):
                        args = []
                        for i in range(0,len(req)):
                            args.append( format2value(req[i], arguments[i]) )
                        for i in range(0,len(opt)):
                            idx = len(req) + i + 1
                            if idx >= len(arguments):
                                break
                            args.append( format2value(opt[i], arguments[idx]) )

                        print "callback name=%s args=%s" % (self.__name__,args)

                        try:
                            func.result = self.robj(*args)
                            #func.result = getattr(self, name)(arguments)
                        except Exception, e:
                            func.error = "%s" % e
                    func.connect("called(QVariantList)", callback)
                    func.registerFunction()

                functions.append( self )
Esempio n. 36
0
        def __init__(self, functions, name, comment, format, params):
            self.__name__ = "R_%s" % name.upper()
            #self.__name__ = "R.%s" % name.upper()

            try:
                self.robj = getattr(rpy.r, name)
                self.isNewFunc = not KCells.hasFunction(self.__name__)
                if self.isNewFunc:

                    def format2name(fchar):
                        if fchar == 'f': return 'Float'
                        if fchar == 'i': return 'Int'
                        if fchar == 's': return 'String'
                        if fchar == 'b': return 'Boolean'
                        raise "Unknown format char '%s'" % fchar

                    def format2value(fchar, value):
                        if fchar == 'f': return float(value or 0.0)
                        if fchar == 'i': return int(value or 0)
                        if fchar == 's': return "%s" % (value or '')
                        if fchar == 'b':
                            if type(value) == types.StringType:
                                v = value.strip().lower()
                                return bool(
                                    len(v) > 0 and v != '0' and v != 'no'
                                    and v != 'false')
                            else:
                                return bool(value)
                        raise "Unknown format char '%s' with value '%s'" % (
                            fchar, value)

                    try:
                        req, opt = format.split('|')
                    except ValueError:
                        req, opt = [format, []]

                    func = KCells.function(self.__name__)

                    func.typeName = 'Float'
                    func.comment = comment

                    func.syntax = "%s(%s)" % (self.__name__, ', '.join(
                        [p.split(':')[0] for p in params]))
                    #func.syntax = "%s(%s)" % (self.__name__,', '.join([ format2name(r) for r in req ]))

                    func.minparam = len(req)
                    func.maxparam = func.minparam + len(opt)
                    for i in range(0, len(req)):
                        func.addParameter(format2name(req[i]),
                                          params[i].split(':')[1])
                    for i in range(0, len(opt)):
                        func.addParameter(format2name(opt[i]),
                                          params[len(req) + i].split(':')[1])

                    def callback(arguments):
                        args = []
                        for i in range(0, len(req)):
                            args.append(format2value(req[i], arguments[i]))
                        for i in range(0, len(opt)):
                            idx = len(req) + i + 1
                            if idx >= len(arguments):
                                break
                            args.append(format2value(opt[i], arguments[idx]))

                        print "callback name=%s args=%s" % (self.__name__,
                                                            args)

                        try:
                            func.result = self.robj(*args)
                            #func.result = getattr(self, name)(arguments)
                        except Exception, e:
                            func.error = "%s" % e

                    func.connect("called(QVariantList)", callback)
                    func.registerFunction()

                functions.append(self)
Esempio n. 37
0
#!/usr/bin/env kross

import time, Kross, KCells

func = KCells.function("PYTIME")
func.minparam = 0
func.maxparam = 1
func.comment = "The PYTIME() function displays the current datetime."
func.syntax = "PYTIME(string)"
func.addParameter("String", "The datetime format string.")
func.addExample("PYTIME()")
func.addExample("PYTIME(\"%H:%M.%S\")")
func.addExample("PYTIME(\"%Y-%M-%d\")")

def update(args):
    try:
        func.result = time.strftime(args[0] or "%H:%M.%S")
    except:
        func.error = "Invalid format"

func.connect("called(QVariantList)", update)
func.registerFunction()
Esempio n. 38
0
        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0]  #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KCells.currentSheet().text(ticker[1:])

            todate = argument[1]  #e.g. "20060119"
            if todate.startswith('='):
                todate = KCells.currentSheet().text(todate[1:])
            fromdate = todate

            typename = argument[2]  #e.g. "Open"
            if typename.startswith('='):
                typename = KCells.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = "Invalid symbol"
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = "Invalid date"
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = "Invalid type"
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = "Web services request failed"
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0, len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = "No stock"
                return
            if len(resultlist) < 7:
                func.error = "Invalid stock"
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v, resultlist)
            func.result = v
Esempio n. 39
0
 def speakCellName(self):
     sheet = KCells.currentSheet()
     (x1,y1,x2,y2) = KCells.view().selection()
     p1 = sheet.cellName(x1,y1)
     self.myorca.speak(p1)