示例#1
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()
示例#2
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()
示例#3
0
文件: yfinance.py 项目: KDE/koffice
    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()
示例#4
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()
示例#5
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)
示例#6
0
文件: pytime.py 项目: KDE/koffice
#!/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()
示例#7
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 )
示例#8
0
文件: yweather.py 项目: KDE/koffice
    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()
示例#9
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()