<s> try : <EOL> import json <EOL> except ImportError : <EOL> try : <EOL> import simplejson as json <EOL> except ImportError : <EOL> from django . utils import simplejson as json <EOL> from urllib import urlencode <EOL> from urllib2 import urlopen <EOL> from geopy . geocoders . base import Geocoder <EOL> from geopy . util import logger , decode_page , join_filter <EOL> class Bing ( Geocoder ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , api_key , format_string = '<STR_LIT:%s>' , output_format = None ) : <EOL> """<STR_LIT>""" <EOL> if output_format != None : <EOL> from warnings import warn <EOL> warn ( '<STR_LIT>' + <EOL> '<STR_LIT>' , DeprecationWarning ) <EOL> self . api_key = api_key <EOL> self . format_string = format_string <EOL> self . url = "<STR_LIT>" <EOL> def geocode ( self , string , exactly_one = True ) : <EOL> if isinstance ( string , unicode ) : <EOL> string = string . encode ( '<STR_LIT:utf-8>' ) <EOL> params = { '<STR_LIT>' : self . format_string % string , <EOL> '<STR_LIT:key>' : self . api_key <EOL> } <EOL> url = self . url % urlencode ( params ) <EOL> return self . geocode_url ( url , exactly_one ) <EOL> def geocode_url ( self , url , exactly_one = True ) : <EOL> logger . debug ( "<STR_LIT>" % url ) <EOL> page = urlopen ( url ) <EOL> return self . parse_json ( page , exactly_one ) <EOL> def parse_json ( self , page , exactly_one = True ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( page , basestring ) : <EOL> page = decode_page ( page ) <EOL> doc = json . loads ( page ) <EOL> resources = doc [ '<STR_LIT>' ] [ <NUM_LIT:0> ] [ '<STR_LIT>' ] <EOL> if exactly_one and len ( resources ) != <NUM_LIT:1> : <EOL> raise ValueError ( "<STR_LIT>" "<STR_LIT>" % len ( resources ) ) <EOL> def parse_resource ( resource ) : <EOL> stripchars = "<STR_LIT>" <EOL> a = resource [ '<STR_LIT:address>' ] <EOL> address = a . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( stripchars ) <EOL> city = a . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( stripchars ) <EOL> state = a . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( stripchars ) <EOL> zipcode = a . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( stripchars ) <EOL> country = a . get ( '<STR_LIT>' , '<STR_LIT>' ) . strip ( stripchars ) <EOL> city_state = join_filter ( "<STR_LIT:U+002CU+0020>" , [ city , state ] ) <EOL> place = join_filter ( "<STR_LIT:U+0020>" , [ city_state , zipcode ] ) <EOL> location = join_filter ( "<STR_LIT:U+002CU+0020>" , [ address , place , country ] ) <EOL> latitude = resource [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ <NUM_LIT:0> ] or None <EOL> longitude = resource [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ <NUM_LIT:1> ] or None <EOL> if latitude and longitude : <EOL> latitude = float ( latitude ) <EOL> longitude = float ( longitude ) <EOL> return ( location , ( latitude , longitude ) ) <EOL> if exactly_one : <EOL> return parse_resource ( resources [ <NUM_LIT:0> ] ) <EOL> else : <EOL> return [ parse_resource ( resource ) for resource in resources ] </s>
