Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.
Status
Not open for further replies.
Aus weather icon help

Hey Guys,

I've been playing around with Geektool the last week and have things looking how I want - after quite a bit of tinkering.

Only problem is my weather icon. I've got current temp for Sydney - Australia, working from our local providers (The US ones are way off), but I can not work out for the life of me how to capture the image like the U.S. Yahoo glet.

Would really appreciate it if someone could help with the regular expression garbage (I've got no hope).

From: http://weather.yahoo.com.au/local-conditions/nsw/sydney
Direct image link: http://weather.yahoo.com.au/styles/icons/yahoo7/large/mostly_sunny.png?1268106362

Code:
<div class="weather">
<img alt="Mostly sunny" class="icon" src="/styles/icons/yahoo7/large/mostly_sunny.png?1268106362" style="float: left;" title="Mostly sunny">
 
Marry me? :D
Works perfect. Only one little modification, if you have time and you actually can, would be to be able to change the number of lines...
Thank you!

Here is the new script. There are now command line options for the number of items to display along with the url for the feed so you don't have to edit the file.

To use:
Code:
python /path/to/script/dropboxnews.py -c # -w "your url here"

And here is the script:
Code:
#!/usr/bin/env python

""" DROPBOX_FEED_GRABBER
 ROBERT WOLTERMAN (xtacocorex) - 2010

 PULLS THE CURRENT FEED FROM YOUR DROPBOX ACCOUND
 
"""

# DROPBOX FEED - VERSION 2
# ROBERT WOLTERMAN - 2011
# PULLS THE CURRENT FEED FROM YOUR DROPBOX ACCOUNT

# CHANGELOG
# 09 SEPTEMBER 2011:
#  - ADDED COMMAND LINE ARGUMENT SUPPORT FOR:
#    - NUMBER OF OUTPUT LINES
#    - FEED URL
# 08 SEPTEMBER 2011:
#  - INITIAL WRITE

# MODULE IMPORTS
import xml.dom.minidom
from optparse import OptionParser
import re
import urllib
import sys

# CLASS TO HOLD THE DATA FOR A FEED ITEM
class dboxItem():
    def __init__(self):
        self.title = ""
        self.link = ""
        self.desc = ""
        self.pubdate = ""

# THE FOLLOWING TWO FUNCTIONS ARE FROM:
# http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html
# THEY WORK PERFECTLY
def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)    

def remove_extra_spaces(data):
    p = re.compile(r'\s+')
    return p.sub(' ', data)

# INLINE FUNCTIONS - DON'T FEEL LIKE CLASSING THIS UP
def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def handleFeed(feed,dboxFeedItems):
    items = feed.getElementsByTagName("item")
    handleNewsItem(items,dboxFeedItems)

def handleNewsItem(items,dboxFeedItems):
    for item in items:
        # CREATE TEMPORARY TODO
        tmpCls = dboxItem()
        # GET THE DATA FROM THE CURRENT ITEM
        title = item.getElementsByTagName("title")[0]
        link = item.getElementsByTagName("link")[0]
        pubdate = item.getElementsByTagName("pubDate")[0]
        # DESCRIPTION USES CDATA INSIDE TO CONTAIN HTML ELEMENTS
        desc = item.getElementsByTagName("description")[0].firstChild.wholeText
        # GET THE VALUES FROM THE TAGS
        tmpCls.title = getText(title.childNodes).strip()
        tmpCls.link = getText(link.childNodes).strip()
        tmpCls.pubdate = getText(pubdate.childNodes).strip()
        # DESCRIPTION IS DIFFERENT BECAUSE OF THE CDATA USE
        tmpCls.desc = remove_extra_spaces(remove_html_tags(desc))
        # APPEND TEMP DROPBOX NEWS CLASS TO DROP BOX NEWS LIST
        dboxFeedItems.append(tmpCls)

def cmdLineOptionParser():
    """
        cmdLineOptionParser()
         - PARSES THE COMMAND LINE ARGUMENTS
         - INPUT:  NONE
         - OUPUTS: NONE
    """
    # CREATE OUR USAGE REPSONSE 
    usage = ("%prog [options]",__doc__)
    
    usage = "\n".join(usage)
    
    # CREATE OUR COMMAND LINE PARSER
    cmdparse = OptionParser(usage)
    
    # ADD COMMAND LINE OPTIONS
    cmdparse.add_option('-c', '--count', action='store', type='int',
        help="line count for output, default is 10",
        default=10
    )
    
    cmdparse.add_option('-w', '--webaddress', action="store", type='string', 
        help="url of the feed",
        default=''
    )
    
    # NOT IMPLEMENTED
    #cmdparse.add_option('-s', '--sort', action="store", type='string',
    #    help="sort direction for the news items: forward/reverse",
    #    default='forward'
    #)
    
    # RETURN THE PARSER
    return cmdparse

if __name__ == "__main__":

    # SET UP THE COMMAND LINE OPTION HOLDER
    cmdparse = cmdLineOptionParser()
        
    # PARSE THE COMMAND LINE OPITONS
    opts, args = cmdparse.parse_args(sys.argv[1:])

    # DETERMINE IF WE ARE USING A PROVIDED URL
    if opts.webaddress == '':
        # INFORM USER THAT THEY DID NOT SPECIFY A
        # URL ON THE COMMAND LINE
        print "URL NOT SPECIFIED WITH THE -w ARGUMENT"
    else:
        url = opts.webaddress

    # GET THE FEED - UPDATE TO CMD LINE ARGUMENT
    dom = xml.dom.minidom.parse(urllib.urlopen(url))

    # LIST TO HOLD ALL THE TASKS (toDo CLASS)
    dboxFeedItems = []

    # HANDLE THE XML
    handleFeed(dom,dboxFeedItems)

    # FIGURE OUT THE NUMBER OF ITEMS WE SHOULD PRINT
    if len(dboxFeedItems) > opts.count:
        numprint = opts.count
    else:
        numprint = len(dboxFeedItems)

    # PRINT OUT THE DROPBOX NEWS
    # THIS IS CUSTOMIZABLE
    for i in range(numprint):
        # PRINT OUT THE DATA HOWEVER YOU WANT
        # DATA STORED IN EACH dboxFeedItems SEGMENT
        # dboxFeedItems[i].title   = TITLE OF THE NEWS ITEM
        # dboxFeedItems[i].desc    = DESCRIPTION OF THE NEWS ITEM
        # dboxFeedItems[i].link    = NEWS ITEM LINK
        # dboxFeedItems[i].pubdate = DATE THE NEWS ITEM WAS PUBLISHED
        # CURRENTLY SET TO PRINT THE DIGG COUNT AND THEN THE TITLE
        print dboxFeedItems[i].desc
 
I notice you're in Italy, you probably have the shell set to ascii and your computer is most likely set to unicode.

Change the shell encoding from ascii to unicode and you should get the day of the week.

----------


i tried to change the encoding from UTF8 to every other option...still nothing...
 
A while back, mvasilakis asked for a CrossFit Workout of the Day script.

After starting on it right away I got hung up a bit on parsing the messy feed XML.

I have since figured it out and I'm providing it to you all at the amazing price of $free.99. :)

Save the code as crossfitgetwod.py and as always, chmod +x the script to make it executable.

Here are the command line options:
Code:
$ python crossfitgetwod.py -h
Usage: crossfitgetwod.py [options]
 CROSSFIT WOD
 ROBERT WOLTERMAN (xtacocorex) - 2011

 GRABS THE 5 CROSSFIT WORKOUT OF THE DAY (WOD)
 
 *** MAKE SURE TO KEEP THE REFRESH RATE IN GEEKTOOL/NERDTOOL TO A SLOWER VALUE


Options:
  -h, --help       show this help message and exit
  -d, --day        Displays the WOD for the current day
  -a, --all        Displays all of the WODs in the feed
  -u, --underline  Underlines the day header(s)
  -c, --convert    Converts the date format from YYMMDD to MM/DD/YY

For the geeklet:
Code:
python /path/to/script/crossfitgetwod.py

Here is the code:
Code:
#!/usr/bin/env python

""" CROSSFIT WOD
 ROBERT WOLTERMAN (xtacocorex) - 2011

 GRABS THE 5 CROSSFIT WORKOUT OF THE DAY (WOD)
 
 *** MAKE SURE TO KEEP THE REFRESH RATE IN GEEKTOOL/NERDTOOL TO A SLOWER VALUE
"""

# CHANGELOG
# 09 SEPTEMBER 2011
#  - FIGURED OUT BEST METHOD OF PARSING THE MESSY RSS FEED
#  - ADDED COMMAND LINE OPTIONS FOR: 
#      - CONVERTING DATE FORMAT
#      - UNDERLINING THE DATE HEADER
#      - OUTPUTTING JUST THE WOD FOR THE CURRENT DAY
#  - 
# 31 JULY 2011
#  - INITIAL WRITE (DIDN'T GET TOO FAR WITH THE CODE)

# MODULE IMPORTS
import urllib, os, re, sys, string, ast, optparse, time, datetime
from xml.dom.minidom import parse, parseString

FEEDURL = "http://feeds.feedburner.com/crossfit/eRTq"

class WOD:
    def __init__(self):
        self.wod_date = ""
        self.wod      = ""
    
    def wodprint(self,opts):
        if opts.underline:
            print "\033[4m%s\033[0m" % date_check(self.wod_date,opts)
        else:
            print date_check(self.wod_date,opts)
        print self.wod
        print ""

def date_check(cdate,opts):
    if opts.convert:
        # SPLIT ON THE SPACE IN BETWEEN THE DAY NAME AND THE YYMMDD
        tmp = cdate.split()
        # GET THE DAY NAME
        dayname = tmp[0]
        
        # SPLIT UP THE YYMMDD
        year  = tmp[1][0:2]
        month = tmp[1][2:4]
        day   = tmp[1][4:]
        
        # SET UP OUR RETURN STRING
        rtnstr = "%s %s/%s/%s" % (dayname,month,day,year)
        
        # RETURN THE NEWLY FORMATTED DATE
        return rtnstr
        
    else:
        # WE DON'T WANT TO CONVERT, SO RETURN THE INPUT ARGUMENT
        return cdate

def cmdLineOptionParser():
    """
        cmdLineOptionParser()
         - PARSES THE COMMAND LINE ARGUMENTS
         - INPUT:  NONE
         - OUPUTS: NONE
    """
    # CREATE OUR USAGE REPSONSE 
    usage = ("%prog [options]",__doc__)
    
    usage = "\n".join(usage)
    
    # CREATE OUR COMMAND LINE PARSER
    cmdparser = optparse.OptionParser(usage)
    
    # ADD OPTIONS 
    cmdparser.add_option('-d', '--day', action='store_true',
        help="Displays the WOD for the current day",
        default=False
    )
    
    cmdparser.add_option('-a', '--all', action='store_true',
        help="Displays all of the WODs in the feed",
        default=False
    )
    
    cmdparser.add_option('-u', '--underline', action='store_true',
        help="Underlines the day header(s)",
        default=False
    )
    
    cmdparser.add_option('-c', '--convert', action='store_true',
        help="Converts the date format from YYMMDD to MM/DD/YY",
        default=False
    )
    
    # RETURN THE PARSER
    return cmdparser

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

# THE FOLLOWING TWO FUNCTIONS ARE FROM:
# http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html
# THEY WORK PERFECTLY
def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)    

def remove_extra_spaces(data):
    p = re.compile(r'\s+')
    return p.sub(' ', data)

def getWOD(myopts):
    """
        getWOD()
         - GETS THE WORKOUT OF THE DAY DATA
         - INPUT:  myopts - option
         - OUPUTS: NONE
    """
    
    # CREATE TEMPORARY LIST
    twodlist = []
    
    # CREATE OUR DOM OBJECT TO GET THE HTML HIERARCHY
    dom = parse(urllib.urlopen(FEEDURL))
    
    # GET THE ITEMS TAG
    feeditems = dom.getElementsByTagName("item")
    
    # NOW LOOP THROUGH THE ITEMS AND GET THE TITLE AND DESCRIPTION
    for items in feeditems:
        # SET UP OUR TEMP WOD ITEM
        twod = WOD()
    
        # GET TITLE
        tmp = items.getElementsByTagName("title")[0]
        c_title = getText(tmp.childNodes)
        twod.wod_date = c_title
        #print twod.wod_date
    
        # GET DESCRIPTION
        tmp = items.getElementsByTagName("description")[0]
        #tmp = remove_extra_spaces(remove_html_tags(getText(tmp.childNodes)))
        tmp = remove_html_tags(getText(tmp.childNodes))
        
        # ============
        # THIS SECTION HAS THE CAPABILITY TO BREAK, CURRENTLY HAVE TO DO THE
        # FOLLOWING STEPS IN THIS ORDER
        
        # SEARCH FOR THE POST * TO COMMENTS AND GRAB EVERYTHING IN FRONT OF 
        # THAT TEXT FOR THE WOD             
        t3 = re.search(".*Post .* to comments.",tmp,re.DOTALL)
        #print "t3: ", t3
        if t3:
            t2 = t3.group(0).split("Post")[0].rstrip("\n\n")
            twod.wod = t2
            #print t2
        
        # DETERMINE IF IT IS A REST DAY, IF SO, OVERWRITE THE WOD WITH "REST DAY"
        t1 = re.search(".*Rest Day.*",tmp,re.DOTALL)
        #print "t1: ", t1
        if t1:
            #print "Rest Day"
            twod.wod = "Rest Day"
        
        # APPEND THE TEMP WOD ITEM TO THE TEMPORARY WOD LIST
        twodlist.append(twod)
    
    # RETURN THE WOD LIST
    return twodlist
    
def printWODs(wodlist,opts):
    """
        printWODs()
         - PRINTS THE WODS TO THE SCREEN BASED ON THE USER CLI OPTIONS
         - INPUT:  opts - COMMAND LINE ARGUMENTS
         - OUPUTS: NONE
    """
    # GET CURRENT DATE IN THE SPECIAL FORMAT
    currdate = time.strftime("%A %y%m%d")
    
    # LOOP THROUGH THE WOD LIST AND START PRINTING
    for item in wodlist:
        # DETERMINE IF WE ARE PRINTING ALL OPTIONS OR JUST THE CURRENT DAYS
        if opts.day:
            if currdate == item.wod_date:
                item.wodprint(opts)

        elif opts.all:
            item.wodprint(opts)
    
def wodGrabberMain(argv):
    """
        wodGrabberMain()
         - MAIN SCRIPT FUNCTION THAT ORGANIZES THE TASKS
         - INPUT:  args - COMMAND LINE ARGUMENTS
         - OUPUTS: NONE
    """

    # FIGURE OUT COMMAND LINE ARGUMENTS
    cmdparser = cmdLineOptionParser()
    opts, args = cmdparser.parse_args(argv)
    
    # CREATE OUR LIST FOR STORING THE WODS
    wodlist = []
    
    # GET THE WODS
    wodlist = getWOD(opts)
    
    # PRINT THE WOD LIST
    printWODs(wodlist,opts)

if __name__ == "__main__":
    wodGrabberMain(sys.argv[1:])

Here is sample output if you want to see just the current days workout and convert the date to a more readable format:
Code:
$ python crossfitgetwod.py -d -c
Saturday 09/10/11
Tabata "Bottom to Bottom" Squat
Run 1 mile

Clock starts for run on rising from last squat.

The Tabata Bottom to Bottom Squat is a Tabata Squat but each rep begins at the bottom and ends at the bottom. The turn around at the top is immediate - no pause. The ten-second rest for each interval is also held at the bottom of the squat as opposed to the top. Interestingly, this squat, in contrast to the "normal" Tabata squat, motivates full hip extension. Also, the ten second rests don't seem as short with this protocol!

Dave Leys 15/6:55.
 
I notice you're in Italy, you probably have the shell set to ascii and your computer is most likely set to unicode.

Change the shell encoding from ascii to unicode and you should get the day of the week.

----------


i tried to change the encoding from UTF8 to every other option...still nothing...


Can you post a screenshot of the geeklet and it's option window? We might be able to get some more information from that.
 
Can you post a screenshot of the geeklet and it's option window? We might be able to get some more information from that.

here it is! the first picture is related to the not working shell.
the second one is about the shell with a simple "echo" instruction.

i've tried every suggestion you gave me...

i can't see anything wrong. but, obviously 700 eyes are better than two! :)
 

Attachments

  • schermo_1.jpg
    schermo_1.jpg
    330.7 KB · Views: 160
  • schermo_2.jpg
    schermo_2.jpg
    334.3 KB · Views: 139
here it is! the first picture is related to the not working shell.
the second one is about the shell with a simple "echo" instruction.

i've tried every suggestion you gave me...

i can't see anything wrong. but, obviously 700 eyes are better than two! :)

All you need is
Code:
date +%A

Don't write entire scripts into shell geeklets, just commands (like your 'echo' one). To run scripts, simply enter the name of the file in to the command box.
 
All you need is
Code:
date +%A

Don't write entire scripts into shell geeklets, just commands (like your 'echo' one). To run scripts, simply enter the name of the file in to the command box.

what you're suggesting, it's what i've done in the first place, and it's the reason because i registered in this forum...:)
 
@flo90p

I'm running with Nerdtool and here is how mine is set up.
 

Attachments

  • Screen shot 2011-09-10 at 16.15.46 .png
    Screen shot 2011-09-10 at 16.15.46 .png
    1.1 MB · Views: 2,717
Is there any way for an 'IF' style command? For example, if Skype.app is running, then display the following image. Thanks!
 
Is there any way for an 'IF' style command? For example, if Skype.app is running, then display the following image. Thanks!

You'll have to roll with two geeklets:
- One to run a script to determine if Skype is running and to copy the picture you want to a temporary file
- The other will be an image geeklet set to display this temporary image

Here is a script I just wrote to do this and tested the writing portion by verifying the image changed when I browsed to the location in Finder.

Make sure the extension for all three images is the same, just update ext in the script below to your chosen extension.
Code:
-- SET ext TO THE IMAGE FILE EXTENSION OF YOUR CHOICE

-- SET THE ON/OFF IMAGE PATHS
set imageOnFile to "/Users/<username>/path/to/picture/picturefile_on.ext"
set imageOffFile to "/Users/<username>/path/to/picture/picturefile_off.ext"

-- SET THE TEMPORARY LOCATION TO WRITE THE TEMPORARY IMAGE FOR THE SECOND GEEKLET
-- POINT THE SECOND GEEKLET TO LOOK AT /tmp/skypeonoff.ext
set tmpLocation to "/tmp/skypeonoff.ext"

-- WE WANT TO KNOW IF SKYPE IS RUNNING...
if appIsRunning("Skype") then
	do shell script "/bin/cp " & imageOnFile & " " & tmpLocation
else
	do shell script "/bin/cp " & imageOffFile & " " & tmpLocation
end if

-- FUNCTION TO DETERMINE IF THE APPLICATION IS RUNNING
on appIsRunning(appName)
	tell application "System Events" to (name of processes) contains appName
end appIsRunning

For the first geeklet, you'll have to use the osascript command to call the applescript.
 
Last edited:
Thanks. That's a start. I just need to learn how to use Apple Script. :eek:

Edit: Also, why doesn't the lyrics script display other languages besides English? I have the lyrics for L'appuntamento in Italian and they won't display - switch them to English and they do.

Here is my script that I added the track time information too:
Code:
tell application "System Events" to set iTunesIsRunning to (name of processes) contains "iTunes"
if iTunesIsRunning is false then
	return "iTunes is not open"
end if
tell application "System Events"
	set powerCheck to ((application processes whose (name is equal to "iTunes")) count)
	if powerCheck = 0 then
		return ""
	end if
end tell
if iTunesIsRunning is true then
	tell application "iTunes"
		set theURL to the current stream URL as text
		set theStream to the current stream title as text
		if player state is playing then
			if theURL is "missing value" then
				set sartist to artist of current track
				set strack to name of current track
				set salbum to album of current track
			else
				set stitle to current stream title as text
				set sname to name of current track
			end if
		end if
		if player state is paused then
			if theURL is "missing value" then
				set strack to name of current track & " (paused)"
			else
				set stitle to (current stream title as text) & " (paused)"
			end if
		end if
		if player state is stopped then
			if theURL is "missing value" then
				set strack to name of current track & " (stopped)"
			else
				set stitle to (current stream title as text) & " (stopped)"
			end if
		end if
		
		-- SECTION FOR TRACK TIME
		set when to player position
		set whenStr to (when div 60) & ":" & (when mod 60) as text
		set long to time of current track
		set tinfo to "[" & whenStr & " / " & long & "]" as string
		
		if theURL is "missing value" then
			set info to strack & " " & tinfo & " | " & sartist & "
" & salbum as string
		else
			set info to stitle & " " & tinfo & "
 Stream: " & sname
		end if
		
		return info
	end tell
end if

As for the lyrics not being displayed in another language, it could be the encoding set for the geeklet. Make sure it isn't set to ascii.
 
You'll have to roll with two geeklets:
- One to run a script to determine if Skype is running and to copy the picture you want to a temporary file
- The other will be an image geeklet set to display this temporary image

Here is a script I just wrote to do this and tested the writing portion by verifying the image changed when I browsed to the location in Finder.

Make sure the extension for all three images is the same, just update ext in the script below to your chosen extension.
Code:
-- SET ext TO THE IMAGE FILE EXTENSION OF YOUR CHOICE

-- SET THE ON/OFF IMAGE PATHS
set imageOnFile to "/Users/<username>/path/to/picture/picturefile_on.ext"
set imageOffFile to "/Users/<username>/path/to/picture/picturefile_off.ext"

-- SET THE TEMPORARY LOCATION TO WRITE THE TEMPORARY IMAGE FOR THE SECOND GEEKLET
-- POINT THE SECOND GEEKLET TO LOOK AT /tmp/skypeonoff.ext
set tmpLocation to "/tmp/skypeonoff.ext"

-- WE WANT TO KNOW IF SKYPE IS RUNNING...
if appIsRunning("Skype") then
	do shell script "/bin/cp " & imageOnFile & " " & tmpLocation
else
	do shell script "/bin/cp " & imageOffFile & " " & tmpLocation
end if

-- FUNCTION TO DETERMINE IF THE APPLICATION IS RUNNING
on appIsRunning(appName)
	tell application "System Events" to (name of processes) contains appName
end appIsRunning

Great thank you! Works well, although I had to put the tmp image into another folder as within /tmp or lion's /private/tmp it didn't seem to work
For the first geeklet, you'll have to use the osascript command to call the applescript.
 
Here is my script that I added the track time information too:

Thanks, but I am a dummy with all the scripting. :eek: What exactly do I do with that code you posted?

As for the lyrics not being displayed in another language, it could be the encoding set for the geeklet. Make sure it isn't set to ascii.

It's set to UTF8. Is there a better setting to use?

lyricsgeektool.png
 
I've been trying to come up with a solution for this, but my limited knowledge of building scripts is failing me on this front!

I'm trying to find a "now playing" script for an app called Soundcloud, a music streaming service similar to spotify. It can be found on the Mac app store here (free download);
http://itunes.apple.com/gb/app/soundcloud/id412754595?mt=12

If anybody can come up with something functional I'd be reallllllly appreciative, this thing has taken over from spotify for me recently and would love to have track names on my desktop!

^^^Anybody have any idea on that?
 
Thanks, but I am a dummy with all the scripting. :eek: What exactly do I do with that code you posted?

It's set to UTF8. Is there a better setting to use?

For the current music script, you need to use a shell geeklet with the following command:
Code:
osascript /path/to/your/scripts/currentmusic.scpt

The encoding setting was my only idea for lyrics, I don't use a lyrics script.
 
Last edited:
Status
Not open for further replies.
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.