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 11-20 of 29 total

Numeric colums for latitude / longitude in Rails 1.2 migrations

In Rails 1.1.6, "numeric" datatypes didn't work in migrations. This confused a lot of people who wanted to store geographic data (latitude and longitude) for use in Google Maps and the like. Floats worked, but their precision is limited -- you'll lose three or more decimal places of precision if you store the results of a typical geocoding call in a Float column. And don't even think about using strings to store your latitudes/longitudes.

Fortunately, the numeric datatype problem is fixed in Rails 1.2, and you can now have do this in your migrations:

class CreatePlaces < ActiveRecord::Migration
  def self.up
    create_table :places do |t|
      t.column "lat", :decimal, :precision => 15, :scale => 10
      t.column "lng", :decimal, :precision => 15, :scale => 10
    end
  end

  def self.down
    drop_table :places
  end
end


FYI, if you're stuck on Rails 1.1.6, you can use this approach:
class CreatePlaces < ActiveRecord::Migration
  def self.up
    create_table :places do |t|
      t.column :lat, :float 
      t.column :lng, :float
    end
    execute("ALTER TABLE places MODIFY lat numeric(15,10);")
    execute("ALTER TABLE places MODIFY lng numeric(15,10);")
  end

  def self.down
    drop_table :places
  end
end

... but that's ugly, database-specific (works on MySQL), and not very DRY.

use google to search / find code snippet

// with google site search you can check for code snippets here

# google.com
search_term site:http://snippets.dzone.com

Draggable eInsert

// description of your code here

<script type="text/javascript">
    //<![CDATA[
    
    if (GBrowserIsCompatible()) { 

      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(53.849, -3.022),16);

      // Optionally set the cursors to be used for dragging
      GDraggableObject.setDraggableCursor("move");


      // Insert the "Nosuch Road" road 
      var insert1 = new EInsert(new GLatLng(53.85022, -3.01772), "nosuch.png", new GSize(145,233), 16);
      map.addOverlay(insert1);
      // Make it draggable
      insert1.makeDraggable();
      
      // A new event that returns the new latlng when the drag ends
      GEvent.addListener(insert1, "dragend", function (pt) {
        GLog.write("New position of insert = "+ pt.lat() + ","+pt.lng());
      });

    }

    //]]>
    </script>

Python - randomGoogle

// Create a sample directory googleIMGs

import os
import random
import re
import urllib
import urllib2

class googleImages(object):
    
    RE_IMAGEURL = re.compile('imgurl=(http://.+?)&', 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 GoogleImages delle immagini in maniera random...
        '''
        
        htmlPage = ''
        request = ''
        
        if imageName == None: imageName = self._randomWords()
        
        requestURL = 'http://images.google.it/images?q=%s&hl=it&start=%d' % (imageName, (random.randint(0, 50)*10))
        requestHeaders = {'User-Agent':'googleImages/1.0'}
        
        try:
            request = urllib2.Request(requestURL, None, requestHeaders)
            htmlPage = urllib2.urlopen(request).read(500000)
        except:
            pass
        
        results = googleImages.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 googleIMGs 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, 'googleIMGs' + os.sep + os.path.split(imageName)[1])
            posIMGs += 1
    
if __name__ == '__main__':
    
    test = googleImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'

Googleit WordPress Plugin

// description of your code here

<?php
/*
Plugin Name: Googleit
Plugin URI: http://lordrich.com/archives/2005/04/02/just-google-it/
Description: Link to google for the current title.  Usage: google_it();
Version: 0.1
Author: Richard Kirkcaldy
Author URI: http://lordrich.com
*/

function google_it(){
	$google = '<a href="http://www.google.com/search?q='.get_the_title().'">Google It</a>';
	echo $google;
	}
?>

Google Redirector

// ==UserScript==
// @name          Google Redirector
// @namespace     http://d.hatena.ne.jp/youpy/
// @include       *
// ==/UserScript==

(function() {
    var targets = document.evaluate('//a[starts-with(@href, "http")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0; i < targets.snapshotLength; i ++) {
	targets.snapshotItem(i).href = 'http://www.google.com/url?sa=D&q=' + encodeURIComponent(targets.snapshotItem(i).href);
    }
})();

Quick aliases for common searches in firefox

Badly formatted post broke our parser. Please edit!

Eliminating sites from searches

You can eliminate matches on queries based on the name of the site. For example, to search on all sites except 'experts-exchange.com', use the following hyphen-prefixed 'site' string:

-site:experts-exchange.com "convert cstring to int "


Or you can only seach a specified site by removing the dash
site:planetargon.com "rails hosting"


Tip by xinu

Google free proxy

From Google Hack
http://www.google.com/translate?langpair=en|en&u=www.forbiddensite.com

Shapefile2KML

#requires and ArcGIS 9.x licenses
#import standard libraries
import sys, os, win32com.client

#import the kml library
import pyKML

#create gp object
gp = win32com.client.Dispatch("esriGeoprocessing.GPDispatch.1")

#get the input layer path
layer = "C:/myProjects/CUAHSI/WebServices/NCDC/asos-20051110/asos-20051110.shp" #sys.argv[1]

#get the lat, lon, name, and id fields
lat_field = "LATITUDE"
lon_field = "LONGITUDE"
elev_field = "STN_ELEV"
name_field = "LOCATION"
id_field = "CALLSIGN"

#create a cursor on this layer 
feats = gp.SearchCursor(layer)
feat = feats.Next()

#open a kml file to write points into
kml = pyKML.KML_File("C:/myProjects/CUAHSI/WebServices/NCDC/asos-20051110/test.kml")
kml.open_folder("Weather_Stations")

#loop through features
while feat:

    shape1 = feat.shape
    part = shape1.GetPart(0)
    
    #get he features attributes
    lat =  part.y
    lon = part.x
    elev = feat.GetValue(elev_field)
    name = feat.GetValue(name_field)
    id = feat.GetValue(id_field)

    #create a description from the name and id attributes                         
    description = name + "<a href='http://www.nws.noaa.gov/asos/'>http://www.nws.noaa.gov/asos/</a>"

    #create a kml placemaker object    
    kml.add_placemarker(lat,lon,0.0,description,id)
                           
    feat = feats.Next()

#close the folder
kml.close_folder()

#close file
kml.close()

« Newer Snippets
Older Snippets »
Showing 11-20 of 29 total