Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

May fortune be my IM status.

// Tired of having others have cooler status on their IM clients,
// I decided that I shall put an end to that.
// Yet, I am no factory of coolness, but I figured my favorite buddy,
// "fortune" will help me out a little.

// By the way, this tool can definitely be done much better with regard
// to the way it updates the MSN, but hey, I just wanted to play with
// C#. My first time :P

// BTW, the MSN thing works only if you have your MSN not minimized PLUS
// the toolbar showing. (LAME! I know.)

// If you really want to do it right, use http://www.xihsolutions.net/dotmsn/
// and send me the code ;) bhtek@yahoo.com

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Runtime.InteropServices;


namespace ZenStatusUpdater
{
    class Program 
    {
        [DllImport("USER32.DLL", EntryPoint = "FindWindowA", CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr FindWindow(string sClassName, string sWindowName);

        [DllImport("USER32.DLL", EntryPoint = "PostMessageA", CallingConvention = CallingConvention.StdCall)]
        private static extern bool PostMessage(IntPtr hWnd, uint iMsg, long wParam, long lParam); 

        static void exploreElement(AutomationElement sub)
        {
            foreach (AutomationProperty prop in sub.GetSupportedProperties())
            {
                Console.WriteLine("\tProp[" + prop.ProgrammaticName + "]: " + sub.GetCurrentPropertyValue(prop));
            }

            foreach (AutomationPattern pat in sub.GetSupportedPatterns())
            {
                Console.WriteLine("\tPat[" + pat.ProgrammaticName + "]");
            }
        }

        static void explore(AutomationElement el)
        {
            Console.WriteLine("Self...");
            exploreElement(el);


            foreach (AutomationElement sub in el.FindAll(TreeScope.Descendants, Condition.TrueCondition))
            {
                Console.WriteLine("Sub...");
                exploreElement(sub);
            }
        }

        static void Main(string[] args)
        {
            String fortune = null;
            int tries = 0;

            do
            {
                fortune = GetFortune();
                tries++;
            } while (fortune.Length > 130);

            Console.WriteLine("Try #" + tries + ": " + fortune);

            updateMsnStatus(fortune);
            updateYahooStatus(fortune);

            System.Threading.Thread.Sleep(5000);
        }

        protected static void updateYahooStatus(String fortune)
        {
            // Get the current signed in user
            //
            string sUserName = "bhtek";
            Console.WriteLine("The currently logged in user is " + sUserName);

            // Now open the current user's profile and set the current status message, pass true to
            // OpenSubKey to request write access

            RegistryKey keyYahooCustomMessages = Registry.CurrentUser.OpenSubKey("Software\\Yahoo\\Pager\\profiles\\"
            + sUserName + "\\Custom Msgs", true);

            // Set the 5th message, seems like yahoo messenger has the functionality to move the newly set
            // message up as the first one.
            String status = fortune;
            keyYahooCustomMessages.SetValue("5", status);
            byte[] statusBin = (new ASCIIEncoding()).GetBytes(status);
            keyYahooCustomMessages.SetValue("5_bin", (byte[])statusBin); 
            keyYahooCustomMessages.Close();
                
            // We are done setting the value in the registry. We now need to notify y! of this change
            //

            // Find the yahoo messenger window and sent it the notification
            // 0x111: WM_COMMAND
            // 0x188: Code 392

            IntPtr hWndY = FindWindow("YahooBuddyMain", null);
            System.Diagnostics.Debug.WriteLine("Find window got: " + hWndY.ToString());
            PostMessage(hWndY, 0x111, 0x188, 0);
        }

        protected static void updateMsnStatus(String fortune)
        {
            AutomationElementCollection msnWindows = AutomationElement.RootElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "MSBLWindowClass"));
            if (msnWindows.Count > 1)
            {
                foreach (AutomationElement potentialMsn in msnWindows)
                {
                    exploreElement(potentialMsn);
                }

                return;
            }

            AutomationElement msn = msnWindows[0];
            msn.SetFocus();

            AutomationElement tools = msn.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AccessKeyProperty, "Alt+T"));
            ExpandCollapsePattern toolsPat = (ExpandCollapsePattern)tools.GetCurrentPattern(ExpandCollapsePattern.Pattern);
            toolsPat.Expand();

            AutomationElement options = tools.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options..."));
            InvokePattern optionsPat = (InvokePattern)options.GetCurrentPattern(InvokePattern.Pattern);
            optionsPat.Invoke();

            AutomationElement optionsWindow = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options"));

            AutomationElement personalMessage = optionsWindow.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ClassNameProperty, "RichEdit20W"),
                    new PropertyCondition(AutomationElement.NameProperty, "Type a personal message for your contacts to see:")
                    )
            );
            ValuePattern personalMessagePat = (ValuePattern)personalMessage.GetCurrentPattern(ValuePattern.Pattern);
            personalMessagePat.SetValue(fortune);

            AutomationElement ok = optionsWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK"));
            InvokePattern okPat = (InvokePattern)ok.GetCurrentPattern(InvokePattern.Pattern);
            okPat.Invoke();
        }

        private static String GetFortune()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "c:\\cygwin\\bin\\fortune.exe";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            String fortune = process.StandardOutput.ReadToEnd();

            fortune = System.Text.RegularExpressions.Regex.Replace(fortune, "\\s+", " ");
            return fortune;
        }

       
    }
}

jQuery Maps Interface - Easily create Google or Yahoo maps

/* jQuery Maps (jmaps) - A jQuery plugin for Google Maps API
* Author: Tane Piper (digitalspaghetti@gmail.com)
* With special thanks Dave Cardwell (who helped on getting the first version of this plugin to work).
* Website: http://code.google.com/p/gmapp/
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
* This plugin is not affiliated with Google or Yahoo.
* For Google Maps API and T&C see http://www.google.com/apis/maps/
* For Yahoo! Maps API and T&C see http://developer.yahoo.com/maps/
*
* === Changelog ===
* Version 1.3
* Added support for creating Yahoo! Maps, can create Map, Satallite or Hybrid. Check out available options below
* Added support for creating points on Yahoo! maps.
* Added support for creating Polylines on Yahoo! maps.
* Added support for GeoRSS files on both Yahoo! and Google maps, as well as existing KML support for Google, method
* name was changed from .addKml to .addRss
* Moved directions search out of main namespace, now function that is called from within plugin by providing fields
*
* Version 1.2 (25/07/2007)
* Moved GClientGeocoder into searchAddress method
* Fixed bug in searchAddress method regarding getPoint().
*
* Version 1.1 (16/07/2007)
* Changed name to remove Google from main name - namespace now .jmap.
* Added additional options:
* + Add map dragging enable/disable.
* + Add scroll wheel zooming.
* + Add smooth continuous zooming (on certain browsers).
* + Added clean unloading of Google objects.
* Added .addPoly method. Allows the creation of polylines on the map.
* Added .addKml support for rendering KML Files.
* Added .directions Driving Direction support.
*
* Version 1.0 (13/07/2007)
* Initial version.
* Creates Google Map.
* Add points to map.
* Takes address or postcode, Geocodes and centers map. Also creates a draggable marker.
*/


(function($) {
	/* function searchAddress(jmap, address, settings)
	 * This function is an internal plugin method that returns a GLatLng that can be passed
	 * to a Google map.
	 */
	function searchAddress(jmap, address, settings) {
		
		if (jmap._mapType) {
			alert('Yahoo Maps Geocoding not yet supported');
		}
		
		if (jmap.i.Au) {
			GGeocoder = new GClientGeocoder();
			GGeocoder.getLatLng(address, function(point){
				if (!point) {
					alert(address + " not found");
				} else {
					jmap.setCenter(point,settings.zoom);
					var marker = new GMarker(point, {draggable: true});
					jmap.addOverlay(marker);
					pointlocation = marker.getPoint();
					marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());
					GEvent.addListener(marker, "dragend", function(){
						mylocation = marker.getPoint();
						marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());			
					});
				}
			});
		}	
	}
	
	/* directions: function(map,query, panel)
	 * Takes a Direction query and returns directions for map.  Optional panel for text information
	 */
	function searchDirections(jmap,query,panel) {
		// Yahoo Maps
		if (jmap._mapType) {
			alert('Yahoo Directions support not yet added')	;
		}
		
		// Google Maps
		if (jmap.i.Au) {
			var dirpanel = document.getElementById(panel);
			directions = new GDirections(jmap, dirpanel);
			directions.load(query);
		}
	}

	$.fn.extend({
	/* jmap: function(settings)
	 * The constructor method
	 * Example: $().jmap();
	 */
	jmap: function(settings) {
		var version = "1.3";
		/* Default Settings*/	
		var settings = jQuery.extend({
			provider: "google",		// can be "google" or "yahoo"
			maptype: "hybrid",		// can be "map", "sat" or "hybrid"
			center: [55.958858,-3.162302],	// G + Y
			zoom: 12,				// G + Y
			controlsize: "small",	// G + Y
			showtype: true,			// G + Y
			showzoom: true,			// Y
			showpan: true,			// Y
			showoverview: true,		// G
			showscale: true,		// Y
			dragging: true,			// G + Y
			scrollzoom: true,		// G + Y
			smoothzoom: true,		// G
			searchfield: "#Address",
			searchbutton: "#findaddress",
			directionsto: "#to",
			directionsfrom: "#from",
			directionsfind: "#getDirections",
			directionspanel: "myDirections"
		},settings);
		
		return this.each(function(){
			switch(settings.provider)
			{
				case "yahoo":
					var jmap = this.jMap = new YMap(this);
					switch(settings.maptype) {
						case "map":
							var loadmap = YAHOO_MAP_REG;
							break;
						case "sat":
							var loadmap = YAHOO_MAP_SAT;
							break;
						default:
							var loadmap = YAHOO_MAP_HYB;
							break;
					}
					jmap.setMapType(loadmap);
					jmap.drawZoomAndCenter(new YGeoPoint(settings.center[0],settings.center[1]), settings.zoom);
					if (settings.showtype == true){
						jmap.addTypeControl();	// Type of map Control
					}
					if (settings.showzoom == true && settings.controlsize == "small" ){
						jmap.addZoomShort();	// Small zoom control
					}
					if (settings.showzoom == true && settings.controlsize == "large" ){
						jmap.addZoomLong();		// Large zoom control
					}
					if (settings.showpan == true) {
						jmap.addPanControl();	// Pan control
					}
					if (settings.showscale == false) {
						/* On by default */
						jmap.removeZoomScale();	// Show scale bars
					}
					if (settings.dragging == false) {
						/* On by default */
						jmap.disableDragMap();	// Is map draggable?
					}
					if (settings.scrollzoom == false) {
						/* On by default */
						jmap.disableKeyControls(); // Mousewheel and Keyboard control
					}
					break;
					
				case "mslive":
					alert('Microsoft Live Maps are currently not supported but planned for version 1.4')
					break;
					
				default:	
					var jmap = this.jMap = new GMap2(this);
					switch(settings.maptype) {
						case "map":
							var loadmap = G_NORMAL_MAP;
							break;
						case "sat":
							var loadmap = G_SATELLITE_MAP;
							break;
						default:
							var loadmap = G_HYBRID_MAP;
							break;
					}
					jmap.setCenter(new GLatLng(settings.center[0],settings.center[1]),settings.zoom,loadmap);
					switch(settings.controlsize)
					{
						case "small":
							jmap.addControl(new GSmallMapControl());
							break;
						case "large":
							jmap.addControl(new GLargeMapControl());
							break;
						case "none":
							break;
						default:
							jmap.addControl(new GSmallMapControl());
					}
					if (settings.showtype == true){
						jmap.addControl(new GMapTypeControl());
					}
					if (settings.showoverview == true){
						jmap.addControl(new GOverviewMapControl());
					}
					if (settings.scrollzoom == true) {
						/* Off by default */
						jmap.enableScrollWheelZoom();
					}
					if (settings.smoothzoom == true) {
						/* Off by default*/
						jmap.enableContinuousZoom();
					}
					if (settings.dragging == false) {
						/* On by default */
						jmap.disableDragging();
					}
			}	
			/* Seach for the lat & lng of our address*/
			jQuery(settings.searchbutton).bind('click', function(){
				searchAddress(jmap, jQuery(settings.searchfield).attr('value'), settings);
			});
			/* Search for Directions */
			jQuery(settings.directionsfind).bind("click", function(){
				var from = $(settings.directionsfrom).attr('value');
				var to = $(settings.directionsto).attr('value');
				searchDirections(jmap, "from: " + from + " to: " + to, settings.directionspanel);	
				$(settings.directionsfrom).attr('value', to);
				$(settings.directionsto).attr('value', '');
				return false;
			});
			/* On document unload, clean unload Google API*/
			jQuery(document).unload(function(){ GUnload(); });
		});
		},
	/* myMap: function()
	 * Returns a map object from the API, so it's available to the user
	 * Example: $().myMap().setCenter(...) for Google;
	 * Example: $().myMap().drawZoomAndCenter(...) for Yahoo;
	 */
	myMap: function() {
		return this[0].jMap;	
	},
	/* addPoint: function()
	 * Returns a marker to be overlayed on the Google map
	 * Example: $().addPoint(...);
	 */
	addPoint: function(pointlat, pointlng, pointhtml, isdraggable, removable) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {			
			var marker = new YMarker(new YGeoPoint(pointlat, pointlng));	// Create the Yahoo marker type
			YEvent.Capture(marker, EventsList.MouseClick, function(){		// Add mouseclick to open HTML
				marker.openSmartWindow(pointhtml);
			});
			// Below code does not work as expected
			/*if (removable == true) {
				YEvent.Capture(marker, EventsList.MouseDoubleClick, function(){
					jmap.removeOverlay(marker);
				});
			}*/
			jmap.addOverlay(marker);	// Add marker to map
		}
		
		// Google Maps	
		if (jmap.i.Au) {
			var marker = new GMarker(new GLatLng(pointlat,pointlng), { draggable: isdraggable } );
			GEvent.addListener(marker, "click", function(){
				marker.openInfoWindowHtml(pointhtml);
			});
			if (removable == true) {
				GEvent.addListener(marker, "dblclick", function(){
					return jmap.removeOverlay(marker);
				});
			}
			return jmap.addOverlay(marker);
		}
	},
	/* addPoly: function(poly)
	 * Takes an array of GLatLng points, converts it to a vector Polyline to display on the map
	 * Example: $().addPoly(...);
	 */
	addPoly: function (poly, colour, width, alpha) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			return	jmap.addOverlay(poly, colour, width, alpha);
		}
		// Google Maps
		if (jmap.i.Au) {
			return jmap.addOverlay(poly);
		}
	},
	/* addRss: function()
	 * Takes a KML file and renders it to the map.
	 * Example: $().addPoint(...);
	 */
	addRss: function (rssfile) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			var geoXml = new YGeoRSS(rssfile);
			return jmap.addOverlay(geoXml);
		}
		// Google Maps
		if (jmap.i.Au) {
			var geoXml = new GGeoXml(rssfile);
			return jmap.addOverlay(geoXml);
		}
		
	}
});
})(jQuery);

Snippet to grab historical data for stocks

This is a quick little snippet I'm whipping up to import some historical data in for a graphing app we're building for stock data. I figured I'd post this snippet before I maul it into something application-specific...

It downloads a csv file through yahoo's finance site and then parses it and prints out the date and adjusted close for each business day that has data.

require 'open-uri'
require 'csv'

def get_adjusted_close stock_symbol
  puts "-- #{stock_symbol} Adjusted Close - Historical --"
  url = "http://ichart.finance.yahoo.com/table.csv?s=#{stock_symbol}&d=7&e=1&f=2006&g=d&a=2&b=26&c=1990&ignore=.csv"
  puts "Connecting to #{url}\n"

  csv = CSV.parse(open(url).read)

  csv.each{|row|
    puts "#{row[0]} - #{row.last}"
  }
  puts "---------------------------------"
end

example_stocks = "CSCO GOOG"
print "Enter a series of stock symbols separated by spaces (example: #{example_stocks}) to retrieve the historical adjusted close.\n"
stock_symbols = gets
stock_symbols ||= example_stocks

stock_symbols.split.each{|symbol|
  get_adjusted_close(symbol)
}

technology

//



//

<rss version="2.0">

<channel>
<title>Yahoo! News: Technology News</title>

<copyright>
Copyright (c) 2006 Yahoo! Inc. All rights reserved.
</copyright>
<link>http://news.yahoo.com/i/738</link>
<description>Technology News</description>
<language>en-us</language>
<lastBuildDate>Tue, 25 Jul 2006 11:46:28 GMT</lastBuildDate>
<ttl>5</ttl>

<image>
<title>Yahoo! News</title>
<width>142</width>
<height>18</height>
<link>http://news.yahoo.com/i/738</link>

<url>
http://us.i1.yimg.com/us.yimg.com/i/us/nws/th/main_142b.gif
</url>
</image>

<item>
<title>AOL poised to offer more free services
(AP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/ap/20060724/ap_on_hi_te/aol_s_crumbling_walls
</link>
<guid isPermaLink="false">ap/20060724/aol_s_crumbling_walls</guid>
<pubDate>Mon, 24 Jul 2006 17:56:52 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.37869f35456c490188a7fec7fb2bacca.aol_s__crumbling_walls_gfx518.jpg?x=79&y=130&sig=NLu2zExMKR5AIEJ5tft3Uw--" align="left" height="130" width="79" alt="RETRANSMISSION; graphic orinally moved July 21; chart shows quarterly AOL subscriber numbers since 2002. (AP Graphic)" border="0" />AP - The company responsible for introducing millions of people to the Internet is poised to undergo a transformation that would likely accelerate its decline as a gatekeeper of access to the information superhighway.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.37869f35456c490188a7fec7fb2bacca.aol_s__crumbling_walls_gfx518.jpg?x=79&y=130&sig=NLu2zExMKR5AIEJ5tft3Uw--" type="image/jpeg" height="130" width="79"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.37869f35456c490188a7fec7fb2bacca.aol_s__crumbling_walls_gfx518.jpg?x=79&y=130&sig=NLu2zExMKR5AIEJ5tft3Uw--" align="left" height="130" width="79" alt="photo" title="RETRANSMISSION; graphic orinally moved July 21; chart shows quarterly AOL subscriber numbers since 2002. (AP Graphic)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(AP)</media:credit>
</item>

<item>

<title>
MySpace outage blamed on L.A. power loss
(AP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/ap/20060724/ap_on_hi_te/myspace_outage
</link>
<guid isPermaLink="false">ap/20060724/myspace_outage</guid>
<pubDate>Mon, 24 Jul 2006 17:41:56 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/nm/20060718/2006_07_18t105259_450x383_us_media_myspace_comedy.jpg?x=130&y=110&sig=hm7pNj13Z5ZmrthooHk1Sw--" align="left" height="110" width="130" alt="The homepage of MySpace.com. News Corp.'s popular online teen hangout, aims to give comedy the kind of boost the site has given new music. (ScreenGrab/Reuters)" border="0" />AP - The popular social-networking site MySpace.com suffered a pair of extended outages over the weekend because of power problems at a key data center in the Los Angeles area, the company said Monday.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/nm/20060718/2006_07_18t105259_450x383_us_media_myspace_comedy.jpg?x=130&y=110&sig=hm7pNj13Z5ZmrthooHk1Sw--" type="image/jpeg" height="110" width="130"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/nm/20060718/2006_07_18t105259_450x383_us_media_myspace_comedy.jpg?x=130&y=110&sig=hm7pNj13Z5ZmrthooHk1Sw--" align="left" height="110" width="130" alt="photo" title="The homepage of MySpace.com. News Corp.'s popular online teen hangout, aims to give comedy the kind of boost the site has given new music. (ScreenGrab/Reuters)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(AP)</media:credit>
</item>

<item>

<title>
BetOnSports PLC removes CEO after arrest
(AP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/ap/20060725/ap_on_hi_te/britain_betonsports
</link>
<guid isPermaLink="false">ap/20060725/britain_betonsports</guid>
<pubDate>Tue, 25 Jul 2006 10:55:51 GMT</pubDate>

<description>
AP - Online gambling company BetOnSports PLC said Tuesday it had fired its chief executive following his arrest in the United States on racketeering charges.
</description>
</item>

<item>

<title>
Bonds' bad news could be good for auction
(AP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/ap/20060725/ap_on_sp_ba_ne/bbo_giants_bonds_ball_auction
</link>
<guid isPermaLink="false">ap/20060725/bbo_giants_bonds_ball_auction</guid>
<pubDate>Tue, 25 Jul 2006 01:20:36 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.4baebfeed69c430794370999e08169ee.bonds_ball_auction_baseball_watw201.jpg?x=130&y=82&sig=KBFhhlEkTw1Z5ksObibp5g--" align="left" height="82" width="130" alt="From left, Greg Harrison, Matt Hulett, and Dave Cotter, all of the on-line shopping service Mpire.com, are shown in the Seattle-based company's computer room Wednesday, July 19, 2006 in Seattle with a laptop computer showing the site they will use in partnership with eBay.com to auction off the baseball San Francisco Giants' Barry Bonds hit for his 715th career home run. (AP Photo/Ted S. Warren)" border="0" />AP - The subject of Barry Bonds never gets old to some people.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.4baebfeed69c430794370999e08169ee.bonds_ball_auction_baseball_watw201.jpg?x=130&y=82&sig=KBFhhlEkTw1Z5ksObibp5g--" type="image/jpeg" height="82" width="130"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.4baebfeed69c430794370999e08169ee.bonds_ball_auction_baseball_watw201.jpg?x=130&y=82&sig=KBFhhlEkTw1Z5ksObibp5g--" align="left" height="82" width="130" alt="photo" title="From left, Greg Harrison, Matt Hulett, and Dave Cotter, all of the on-line shopping service Mpire.com, are shown in the Seattle-based company's computer room Wednesday, July 19, 2006 in Seattle with a laptop computer showing the site they will use in partnership with eBay.com to auction off the baseball San Francisco Giants' Barry Bonds hit for his 715th career home run. (AP Photo/Ted S. Warren)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(AP)</media:credit>
</item>

<item>
<title>AMD to buy graphics chip maker ATI
(AP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/ap/20060725/ap_on_hi_te/amd_acquisition
</link>
<guid isPermaLink="false">ap/20060725/amd_acquisition</guid>
<pubDate>Tue, 25 Jul 2006 11:34:45 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.c61a156258d84f3095d48b5e9fe7036f.amd_acquisition_nyr107.jpg?x=130&y=86&sig=6aOpNA4Q7.Fw1XraHpMDGQ--" align="left" height="86" width="130" alt="Hector Ruiz, CEO of Advanced Micro Devices Inc., smiles during a meeting Monday, July 24, 2006 in New York. AMD announced Monday it plans to pay $5.4 billion for top graphics chip maker ATI Technologies Inc., a bold move that could help the world's No. 2 maker of PC microprocessors match, or even exceed, the capabilities of larger rival Intel Corp. (AP Photo/Mark Lennihan)" border="0" />AP - Advanced Micro Devices Inc. struck another blow at Intel Corp., its bigger rival in the market for personal-computer microprocessors, as it disclosed plans Monday to buy one of the dominant makers of graphics chips in a $5.4 billion deal that analysts said could fundamentally alter competition in the semiconductor industry.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.c61a156258d84f3095d48b5e9fe7036f.amd_acquisition_nyr107.jpg?x=130&y=86&sig=6aOpNA4Q7.Fw1XraHpMDGQ--" type="image/jpeg" height="86" width="130"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/ap/20060724/capt.c61a156258d84f3095d48b5e9fe7036f.amd_acquisition_nyr107.jpg?x=130&y=86&sig=6aOpNA4Q7.Fw1XraHpMDGQ--" align="left" height="86" width="130" alt="photo" title="Hector Ruiz, CEO of Advanced Micro Devices Inc., smiles during a meeting Monday, July 24, 2006 in New York. AMD announced Monday it plans to pay $5.4 billion for top graphics chip maker ATI Technologies Inc., a bold move that could help the world's No. 2 maker of PC microprocessors match, or even exceed, the capabilities of larger rival Intel Corp. (AP Photo/Mark Lennihan)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(AP)</media:credit>
</item>

<item>

<title>
Rupert Murdoch surprised by MySpace growth
(Reuters)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/nm/20060725/wr_nm/murdoch_dc
</link>
<guid isPermaLink="false">nm/20060725/murdoch_dc</guid>
<pubDate>Tue, 25 Jul 2006 09:58:17 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/nm/20060725/2006_07_25t060106_450x299_us_murdoch.jpg?x=130&y=86&sig=hsuWg4ZZOk9JwCsAGIycBw--" align="left" height="86" width="130" alt="Media tycoon Rupert Murdoch is shown listening to prayers during a service at Saint Brides Church in London, in this June 15, 2005 file photo. The News Corp. chairman and CEO recently spoke about his company's interactive expansion and what it augurs for traditional media giants. (Dylan Martinez/Reuters)" border="0" />Reuters - Twenty years after Rupert
Murdoch upended the status quo in television with the launch of
Fox Broadcasting Co., News Corp. is in the vanguard of another
media revolution with its recently acquired Internet assets
including MySpace.com.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/nm/20060725/2006_07_25t060106_450x299_us_murdoch.jpg?x=130&y=86&sig=hsuWg4ZZOk9JwCsAGIycBw--" type="image/jpeg" height="86" width="130"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/nm/20060725/2006_07_25t060106_450x299_us_murdoch.jpg?x=130&y=86&sig=hsuWg4ZZOk9JwCsAGIycBw--" align="left" height="86" width="130" alt="photo" title="Media tycoon Rupert Murdoch is shown listening to prayers during a service at Saint Brides Church in London, in this June 15, 2005 file photo. The News Corp. chairman and CEO recently spoke about his company's interactive expansion and what it augurs for traditional media giants. (Dylan Martinez/Reuters)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(Reuters)</media:credit>
</item>

<item>

<title>
Get 'Lost Diaries' via cellphone
(USATODAY.com)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/usatoday/20060725/tc_usatoday/getlostdiariesviacellphone
</link>
<guid isPermaLink="false">usatoday/20060725/getlostdiariesviacellphone</guid>
<pubDate>Tue, 25 Jul 2006 11:07:32 GMT</pubDate>

<description>
USATODAY.com - - Get ready for Hurley the filmmaker in The Lost Diaries, a new series of mobile-phone episodes, or "mobisodes." In a preview shown to more than 4,000 Lost fans Saturday at Comic-Con, Hurley (Jorge Garcia) finds a video camera, which he uses to record events on the island.
</description>
</item>

<item>

<title>
AT&T posts higher second-quarter profit
(Reuters)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/nm/20060725/bs_nm/telecoms_att_earns_dc
</link>
<guid isPermaLink="false">nm/20060725/telecoms_att_earns_dc</guid>
<pubDate>Tue, 25 Jul 2006 11:55:29 GMT</pubDate>

<description>
Reuters - AT&T Inc. on Tuesday posted
higher quarterly profit, bolstered by strong growth in wireless
and high-speed Internet services.
</description>
</item>

<item>

<title>
Vyatta Takes On Cisco With New Open-Source Router
(TechWeb)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/cmp/20060725/tc_cmp/191000585
</link>
<guid isPermaLink="false">cmp/20060725/191000585</guid>
<pubDate>Mon, 24 Jul 2006 21:00:00 GMT</pubDate>

<description>
TechWeb - But an open-source product is no better than those who are working on its code, and that number is much larger for a company like Cisco than it is for Vyatta and the small open-source routing community.
</description>
</item>

<item>

<title>
Microsoft releases test version of new Exchange Server software
(AFP)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/afp/20060725/tc_afp/usitinternetsoftwaremicrosoft
</link>
<guid isPermaLink="false">afp/20060725/usitinternetsoftwaremicrosoft</guid>
<pubDate>Tue, 25 Jul 2006 03:52:17 GMT</pubDate>

<description>
<img src="http://d.yimg.com/us.yimg.com/p/afp/20060725/capt.sge.tmr79.250706035212.photo00.photo.default-352x512.jpg?x=89&y=130&sig=bBEayAZvLThnL7VY5ncR3w--" align="left" height="130" width="89" alt="A street worker rests outside a computer shop in Ho Chi Minh city. Microsoft released test versions of its Exchange Server 2007 e-mail managing software and a security package designed to complement it(AFP/File)" border="0" />AFP - Microsoft released test versions of its Exchange Server 2007 e-mail managing software and a security package designed to complement it.
<br clear="all"/>
</description>
<media:content url="http://d.yimg.com/us.yimg.com/p/afp/20060725/capt.sge.tmr79.250706035212.photo00.photo.default-352x512.jpg?x=89&y=130&sig=bBEayAZvLThnL7VY5ncR3w--" type="image/jpeg" height="130" width="89"/>

<media:text type="html">
<img src="http://d.yimg.com/us.yimg.com/p/afp/20060725/capt.sge.tmr79.250706035212.photo00.photo.default-352x512.jpg?x=89&y=130&sig=bBEayAZvLThnL7VY5ncR3w--" align="left" height="130" width="89" alt="photo" title="A street worker rests outside a computer shop in Ho Chi Minh city. Microsoft released test versions of its Exchange Server 2007 e-mail managing software and a security package designed to complement it(AFP/File)" border="0"/>
<br clear="all"/>
</media:text>
<media:credit role="publishing company">(AFP)</media:credit>
</item>

<item>

<title>
Maxager Technology Announces Release 7
(TechWeb)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/cmp/20060725/tc_cmp/191000742
</link>
<guid isPermaLink="false">cmp/20060725/191000742</guid>
<pubDate>Mon, 24 Jul 2006 23:06:00 GMT</pubDate>

<description>
TechWeb - Enterprise profit optimization software uses velocity concept to maximize ROA.
</description>
</item>

<item>

<title>
Apple to cut the cord on the Mighty Mouse
(Macworld.com)
</title>

<link>
http://us.rd.yahoo.com/dailynews/rss/tech/*http://news.yahoo.com/s/macworld/20060725/tc_macworld/mouse20060725
</link>
<guid isPermaLink="false">macworld/20060725/mouse20060725</guid>
<pubDate>Tue, 25 Jul 2006 10:57:00 GMT</pubDate>

<description>
Macworld.com - Apple Computer has developed a wireless version of its Mighty Mouse, according to a U.S. regulatory filing.
</description>
</item>
</channel>
</rss>
<!-- server p129.news.scd.yahoo.com -->

Python - randomYahoo

// Create a sample directory yahooIMGs

import os
import random
import re
import urllib
import urllib2

class yahooImages(object):
    
    RE_IMAGEURL = re.compile('&imgurl=(.+?)&', re.DOTALL | re.IGNORECASE)
    
    def __init__(self):
        
        self.imagesURLs = {}
    
    def getRandomImages(self, imageName=None):
        '''
        imageName = Nome dell'immagine da cercare, se non impostato viene generato un nome Random
        
        Scarica dal sito YahooImages delle immagini in maniera random...
        '''
        
        htmlPage = ''
        request = ''
        
        if imageName == None: imageName = self._randomWords()
        
        requestURL = 'http://it.search.yahoo.com/search/images?p=%s&b=%d' % (imageName, (random.randint(0, 50)*10))
        requestHeaders = {'User-Agent':'yahooImages/1.0'}
        
        try:
            request = urllib2.Request(requestURL, None, requestHeaders)
            htmlPage = urllib2.urlopen(request).read(500000)
        except:
            pass
        
        results = yahooImages.RE_IMAGEURL.findall(htmlPage)
        
        if len(results) > 0:
            for image in results:
                imageURL = urllib.unquote_plus(image)
                if not imageURL.startswith('http://'): imageURL = 'http://'+imageURL
                self.imagesURLs[imageURL] = 0
    
    def _randomWords(self):
        '''
        Viene generata una parola in maniera Random...
        '''
        
        words = ''
        charset = 'abcdefghijklmnopqrtuvwxyz'*2 + '0123456789'
        
        for i in range(random.randint(2, 7)): words += random.choice(charset)
                
        return words
    
    def downloadImages(self):
        '''
        Scarica nella cartella yahooIMGs le foto che vengono trovate in rete...
        '''
        
        numberIMGs = len(self.imagesURLs)
        posIMGs = 1
        
        for imageName in self.imagesURLs:
            print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
            urllib.urlretrieve(imageName, 'yahooIMGs' + os.sep + os.path.split(imageName)[1])
            posIMGs += 1
        
if __name__ == '__main__':
    
    test = yahooImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS