repo
string | commit
string | message
string | diff
string |
---|---|---|---|
rtucker/rgeoutages
|
dc856090bdcecfaa89370528e7451f66e15ffc86
|
linking to github for last-revision information
|
diff --git a/generate_map.py b/generate_map.py
index 77bd656..a6325e0 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,413 +1,413 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
- git_version = open('.git/refs/heads/master','r').readline()
+ git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <p>This is revision %s (%s).</p>
+ <p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
847ec8ebb903daa9e2eaacbaa971eafef171c352
|
more CSS adjustments to improve visual display
|
diff --git a/generate_map.py b/generate_map.py
index 3d9cce8..77bd656 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,413 +1,413 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').readline()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
- <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
+ <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
- <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
+ <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p>This is revision %s (%s).</p>
</div>
- <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:505px">
+ <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="That was then; this is now."></a>
+ <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
- <img src="outagechart.png" title="Graph may be out of date by many hours.">
+ <div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
fe0e114469fbf686809bb6728ff175f152396984
|
minor typographical and formatting tweaks
|
diff --git a/generate_map.py b/generate_map.py
index 03f5a70..3d9cce8 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,413 +1,413 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').readline()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
- <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More info</a>,
- <a href="javascript:unhide('chartbox');">power outage graph</a></p>.
+ <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
+ <a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <p>This is version %s, last pulled %s.</p>
+ <p>This is revision %s (%s).</p>
</div>
- <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:500px">
+ <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:505px">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="That was then; this is now."></a>
</div>
<img src="outagechart.png" title="Graph may be out of date by many hours.">
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
506bd7aca563724541cc66b0912992013cca7adc
|
read the file, not the directory
|
diff --git a/generate_map.py b/generate_map.py
index 6ee97a1..03f5a70 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,413 +1,413 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
- git_version = open('.git/refs/heads','r').readline()
- git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads').st_mtime))
+ git_version = open('.git/refs/heads/master','r').readline()
+ git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More info</a>,
<a href="javascript:unhide('chartbox');">power outage graph</a></p>.
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <p>This is version %s, last modified %s.</p>
+ <p>This is version %s, last pulled %s.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:500px">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="That was then; this is now."></a>
</div>
<img src="outagechart.png" title="Graph may be out of date by many hours.">
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
a920749c54a5ea30ce27ac1ed9ad378976488cf0
|
renaming geocodecache.py to something more useful; also adding version number display
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 3f2dc22..53660fb 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,54 +1,54 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
-GENERATOR=$BASEDIR/geocodecache.py
+GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
# Fetch street data
cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
# Fetch a munin chart
wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise-rgeoutages-day.png
diff --git a/geocodecache.py b/generate_map.py
similarity index 98%
rename from geocodecache.py
rename to generate_map.py
index 7eee281..6ee97a1 100755
--- a/geocodecache.py
+++ b/generate_map.py
@@ -1,407 +1,413 @@
#!/usr/bin/python
import math
+import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
+ git_version = open('.git/refs/heads','r').readline()
+ git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads').st_mtime))
+
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More info</a>,
<a href="javascript:unhide('chartbox');">power outage graph</a></p>.
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
+
+ <p>This is version %s, last modified %s.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:500px">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="That was then; this is now."></a>
</div>
<img src="outagechart.png" title="Graph may be out of date by many hours.">
</div>
- """ % (lastupdated, len(markerlist), s, '; '.join(localelist))
+ """ % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
9c4e755d9152c32837d8af45bcebdf808e570619
|
adding a munin chart because i can
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index aaaa4f1..3f2dc22 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,51 +1,54 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/geocodecache.py
HTMLFILE=$BASEDIR/index.html
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
# Fetch street data
cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
+# Fetch a munin chart
+wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise-rgeoutages-day.png
+
diff --git a/geocodecache.py b/geocodecache.py
index ad28058..7eee281 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,398 +1,407 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
- <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
+ <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More info</a>,
+ <a href="javascript:unhide('chartbox');">power outage graph</a></p>.
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
+
+ <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:500px">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="That was then; this is now."></a>
+ </div>
+ <img src="outagechart.png" title="Graph may be out of date by many hours.">
+ </div>
+
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
9e6757629e7133714a252fe4ddadbdc5c8ae0e35
|
going to need some debugging i think
|
diff --git a/geocodecache.py b/geocodecache.py
index 4117805..ad28058 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,392 +1,398 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
+ out += """
+ /* distance: %.2f
+ minimum corner: %.4f, %.4f
+ maximum corner: %.4f, %.4f */
+ """ % (distance, minLat, minLng, maxLat, maxLng)
+
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
3b397e8b36e88e9bc5656f0bcd84efc49c06618c
|
more zoom tuning
|
diff --git a/geocodecache.py b/geocodecache.py
index 404de2d..4117805 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,392 +1,392 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
- elif distance < 17:
+ elif distance < 25:
zoom = 11
- elif distance < 19:
+ elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
9b3658ae9f3214b48109c66338ef49f9f7d13814
|
include correct multiplier for miles
|
diff --git a/geocodecache.py b/geocodecache.py
index bcb5421..404de2d 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,392 +1,392 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
- if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude']) < 50:
+ if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 17:
zoom = 11
elif distance < 19:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
9bd3c23cb07e74831f9435bd1a4123d1869825ce
|
discard outliers when computing map center
|
diff --git a/geocodecache.py b/geocodecache.py
index ec2ab15..bcb5421 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,391 +1,392 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
- # Iterate through and expand based upon viewport
+ # Iterate through and expand the range, ignoring outliers
for i in points:
- minLat = min(i['latitude'], minLat)
- maxLat = max(i['latitude'], maxLat)
- minLng = min(i['longitude'], minLng)
- maxLng = max(i['longitude'], maxLng)
+ if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude']) < 50:
+ minLat = min(i['latitude'], minLat)
+ maxLat = max(i['latitude'], maxLat)
+ minLng = min(i['longitude'], minLng)
+ maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 17:
zoom = 11
elif distance < 19:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
959f810e277e19ae7707a80733d37ed0b2c25271
|
zooming in even more...
|
diff --git a/geocodecache.py b/geocodecache.py
index cab4e5a..ec2ab15 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,391 +1,391 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand based upon viewport
for i in points:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
- if distance < 3:
+ if distance < 5:
zoom = 15
- elif distance < 5:
- zoom = 14
elif distance < 7:
- zoom = 13
+ zoom = 14
elif distance < 11:
- zoom = 12
+ zoom = 13
elif distance < 13:
- zoom = 11
+ zoom = 12
elif distance < 17:
+ zoom = 11
+ elif distance < 19:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
bbc502cb75a6f6ca2493c7a46cf82c69bdd0359e
|
zoom in a bit more
|
diff --git a/geocodecache.py b/geocodecache.py
index 0607774..cab4e5a 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,391 +1,391 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand based upon viewport
for i in points:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
- if distance < 2:
+ if distance < 3:
zoom = 15
- elif distance < 3:
- zoom = 14
elif distance < 5:
- zoom = 13
+ zoom = 14
elif distance < 7:
- zoom = 12
+ zoom = 13
elif distance < 11:
- zoom = 11
+ zoom = 12
elif distance < 13:
+ zoom = 11
+ elif distance < 17:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
1c79e898bcc2ce98371f2b5adb78e183bb7e2a14
|
using actual lat/long for the points instead of the viewport
|
diff --git a/geocodecache.py b/geocodecache.py
index 7cfe729..0607774 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,392 +1,391 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand based upon viewport
for i in points:
- sw_lat, sw_lng, ne_lat, ne_lng = i['viewport']
- minLat = min(sw_lat, minLat)
- maxLat = max(ne_lat, maxLat)
- minLng = min(ne_lng, minLng)
- maxLng = max(sw_lng, maxLng)
+ minLat = min(i['latitude'], minLat)
+ maxLat = max(i['latitude'], maxLat)
+ minLng = min(i['longitude'], minLng)
+ maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 2:
zoom = 15
elif distance < 3:
zoom = 14
elif distance < 5:
zoom = 13
elif distance < 7:
zoom = 12
elif distance < 11:
zoom = 11
elif distance < 13:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
13a4000e40b37fd4275ede281736daefb442b012
|
tuning the zoom ranges
|
diff --git a/geocodecache.py b/geocodecache.py
index da6f952..7cfe729 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,390 +1,392 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand based upon viewport
for i in points:
sw_lat, sw_lng, ne_lat, ne_lng = i['viewport']
minLat = min(sw_lat, minLat)
maxLat = max(ne_lat, maxLat)
minLng = min(ne_lng, minLng)
maxLng = max(sw_lng, maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
- if distance < 1:
+ if distance < 2:
+ zoom = 15
+ elif distance < 3:
zoom = 14
- elif distance < 2:
+ elif distance < 5:
zoom = 13
- elif distance < 3:
- zoom = 12
elif distance < 7:
+ zoom = 12
+ elif distance < 11:
zoom = 11
- elif distance < 15:
+ elif distance < 13:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
27c519346f3710dffdb9b18b074558b167c318f5
|
pass the point data to where i need to use it
|
diff --git a/geocodecache.py b/geocodecache.py
index ca1523d..da6f952 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,387 +1,390 @@
#!/usr/bin/python
import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
-def produceMapHeader(apikey, markers, centers):
+def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand based upon viewport
- for i in markers:
+ for i in points:
sw_lat, sw_lng, ne_lat, ne_lng = i['viewport']
minLat = min(sw_lat, minLat)
maxLat = max(ne_lat, maxLat)
minLng = min(ne_lng, minLng)
maxLng = max(sw_lng, maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 1:
zoom = 14
elif distance < 2:
zoom = 13
elif distance < 3:
zoom = 12
elif distance < 7:
zoom = 11
elif distance < 15:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
- citycenterlist = []
+ citycenterlist = []
+ pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
+ pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
+ pointlist.append(streetinfo)
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
- sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
+ sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
3606335e2eafa2fe7ad342d1f2d3ad142498f8ac
|
auto zoom and center the map
|
diff --git a/geocodecache.py b/geocodecache.py
index f886da1..ca1523d 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,319 +1,387 @@
#!/usr/bin/python
+import math
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
+def distance_on_unit_sphere(lat1, long1, lat2, long2):
+ # From http://www.johndcook.com/python_longitude_latitude.html
+
+ # Convert latitude and longitude to
+ # spherical coordinates in radians.
+ degrees_to_radians = math.pi/180.0
+
+ # phi = 90 - latitude
+ phi1 = (90.0 - lat1)*degrees_to_radians
+ phi2 = (90.0 - lat2)*degrees_to_radians
+
+ # theta = longitude
+ theta1 = long1*degrees_to_radians
+ theta2 = long2*degrees_to_radians
+
+ # Compute spherical distance from spherical coordinates.
+
+ # For two locations in spherical coordinates
+ # (1, theta, phi) and (1, theta, phi)
+ # cosine( arc length ) =
+ # sin phi sin phi' cos(theta-theta') + cos phi cos phi'
+ # distance = rho * arc length
+
+ cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
+ math.cos(phi1)*math.cos(phi2))
+ arc = math.acos( cos )
+
+ # Remember to multiply arc by the radius of the earth
+ # in your favorite set of units to get length.
+ return arc
+
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
- function initialize() {
- if (GBrowserIsCompatible()) {
- map = new GMap2(document.getElementById("map_canvas"));
- map.setCenter(new GLatLng(43.15661, -77.6253), 11);
- map.setUIToDefault();
- mgr = new MarkerManager(map);
- window.setTimeout(setupMarkers, 0);
-
- // Monitor the window resize event and let the map know when it occurs
- if (window.attachEvent) {
- window.attachEvent("onresize", function() {this.map.onResize()} );
- } else {
- window.addEventListener("resize", function() {this.map.onResize()} , false);
- }
- }
- }
-
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
+ # Determine center of map:
+ # Initialize variables
+ minLat = 43.15661
+ maxLat = 43.15661
+ minLng = -77.6253
+ maxLng = -77.6253
+
+ # Iterate through and expand based upon viewport
+ for i in markers:
+ sw_lat, sw_lng, ne_lat, ne_lng = i['viewport']
+ minLat = min(sw_lat, minLat)
+ maxLat = max(ne_lat, maxLat)
+ minLng = min(ne_lng, minLng)
+ maxLng = max(sw_lng, maxLng)
+
+ # Calculate center
+ centerLat = (minLat + maxLat) / 2
+ centerLng = (minLng + maxLng) / 2
+
+ # Guestimate zoom by finding diagonal distance (in miles)
+ distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
+ if distance < 1:
+ zoom = 14
+ elif distance < 2:
+ zoom = 13
+ elif distance < 3:
+ zoom = 12
+ elif distance < 7:
+ zoom = 11
+ elif distance < 15:
+ zoom = 10
+ else:
+ zoom = 9
+
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
+ zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
+ out += """
+ function initialize() {
+ if (GBrowserIsCompatible()) {
+ map = new GMap2(document.getElementById("map_canvas"));
+ map.setCenter(new GLatLng(%.4f, %.4f), %i);
+ map.setUIToDefault();
+ mgr = new MarkerManager(map);
+ window.setTimeout(setupMarkers, 0);
+
+ // Monitor the window resize event and let the map know when it occurs
+ if (window.attachEvent) {
+ window.attachEvent("onresize", function() {this.map.onResize()} );
+ } else {
+ window.addEventListener("resize", function() {this.map.onResize()} , false);
+ }
+ }
+ } """ % (centerLat, centerLng, zoom)
+
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
3d61d5e35abd62b5098a00d89e50573f55995e9c
|
adding link to github on faq box
|
diff --git a/geocodecache.py b/geocodecache.py
index 1dcc6b0..f886da1 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,319 +1,319 @@
#!/usr/bin/python
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(43.15661, -77.6253), 11);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
}
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
- <p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
+ <p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
76804ce2c961b96a81a0122c286a2a1ea5ffb9e1
|
adding *.sqlite3 to .gitignore now that the sqlite db lives in the work dir
|
diff --git a/.gitignore b/.gitignore
index 182dbca..0f720b4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
index.html
outages_*
secrets.py
*.pyc
+*.sqlite3
|
rtucker/rgeoutages
|
19876347e3601ee03ce846339aabf1cb7ae2fa00
|
adding a 10-minute auto-refresh
|
diff --git a/geocodecache.py b/geocodecache.py
index b2b0fc4..1dcc6b0 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,318 +1,319 @@
#!/usr/bin/python
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+ <meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(43.15661, -77.6253), 11);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
}
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
45d45e2ec401206dc7c9e35ac7e0cc757ad43709
|
copyright and readme files are nice to have
|
diff --git a/COPYRIGHT b/COPYRIGHT
new file mode 100644
index 0000000..ddf27ef
--- /dev/null
+++ b/COPYRIGHT
@@ -0,0 +1,19 @@
+Copyright (c) 2010 Ryan S. Tucker
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/README b/README
new file mode 100644
index 0000000..93e8fb5
--- /dev/null
+++ b/README
@@ -0,0 +1,8 @@
+rgeoutages: A mapping tool for power outage data
+
+This repository contains the backend code for http://hoopycat.com/rgeoutages/
+which displays a reasonably up-to-date map of power outages in the Rochester
+Gas and Electric service area.
+
+TODO: Consider using OpenStreetMap for mapping backend
+
|
rtucker/rgeoutages
|
492304d7dd825b23bf413e5edd32e398ba53480a
|
genericize pathnames
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 6705c62..aaaa4f1 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,43 +1,51 @@
#!/bin/bash
-GENERATOR=/var/www/hoopycat.com/html/rgeoutages/geocodecache.py
-HTMLFILE=/var/www/hoopycat.com/html/rgeoutages/index.html
+BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
+GENERATOR=$BASEDIR/geocodecache.py
+HTMLFILE=$BASEDIR/index.html
+
+# Test for sanity
+[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
+[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
-rm /var/www/hoopycat.com/html/rgeoutages/outages_*.txt 2>/dev/null
+
+# Fetch street data
+cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
+rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
- OUTFILE=/var/www/hoopycat.com/html/rgeoutages/outages_$i.txt
+ OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
diff --git a/geocodecache.py b/geocodecache.py
index c9d2bd0..b2b0fc4 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,318 +1,318 @@
#!/usr/bin/python
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
-def initDB(filename="/tmp/rgeoutages.sqlite3"):
+def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(43.15661, -77.6253), 11);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
}
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
- fd = open('/var/www/hoopycat.com/html/rgeoutages/outages_%s.txt' % i)
+ fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
774a4360d87bb56b6a32d761bfea2c7b48b78b1d
|
add exception handling for bizarre street names
|
diff --git a/geocodecache.py b/geocodecache.py
index fc7b547..c9d2bd0 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,310 +1,318 @@
#!/usr/bin/python
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="/tmp/rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
- data = json.loads(jsondata)['results'][0]
+ jsondict = json.loads(jsondata)
+
+ if jsondict['results'] == []:
+ raise Exception("Empty results string: " + jsondict['status'])
+
+ data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(43.15661, -77.6253), 11);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
}
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('/var/www/hoopycat.com/html/rgeoutages/outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
- streetinfo = geocode(db, cleanname, j)
- markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
- count += 1
+ try:
+ streetinfo = geocode(db, cleanname, j)
+ markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
+ count += 1
+ except Exception, e:
+ sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
00ae483377433a10c479b3bfd448d597d903bb86
|
git: ignore .pyc files
|
diff --git a/.gitignore b/.gitignore
index 2536b81..182dbca 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
index.html
outages_*
secrets.py
+*.pyc
|
rtucker/rgeoutages
|
1506d008f92bb95fc56b540646350c5fd04b1aeb
|
whoops, how about we not hard-code the google maps api key
|
diff --git a/.gitignore b/.gitignore
index 4fc0539..2536b81 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
index.html
outages_*
+secrets.py
diff --git a/geocodecache.py b/geocodecache.py
index 01ebf31..fc7b547 100755
--- a/geocodecache.py
+++ b/geocodecache.py
@@ -1,301 +1,310 @@
#!/usr/bin/python
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
+try:
+ import secrets
+except:
+ sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
+ sys.exit(1)
+
def initDB(filename="/tmp/rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
data = json.loads(jsondata)['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def produceMapHeader(apikey, markers, centers):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(43.15661, -77.6253), 11);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
}
function createMarker(point, text) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker.png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text):
"""Produces a google maps marker given a latitude, longitude, and text"""
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
- apikey = "ABQIAAAA30Jhq_DCCBUDYXZhoCyheRSUYQ6bykvEQfbcB8o1clNVPLJCmBS95D0ZW-pGwa1P39Qz-hMw8rGwxA"
+ try:
+ apikey = secrets.apikey
+ except:
+ apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('/var/www/hoopycat.com/html/rgeoutages/outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
streetinfo = geocode(db, cleanname, j)
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
count += 1
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist))
sys.stdout.write(produceMapBody(bodytext))
diff --git a/secrets.py.orig b/secrets.py.orig
new file mode 100644
index 0000000..70fa742
--- /dev/null
+++ b/secrets.py.orig
@@ -0,0 +1,3 @@
+# Google Maps API key
+apikey = "blahblahblah"
+
|
rtucker/rgeoutages
|
8f80e6e27e1e1a2204efb337853cde818cb839fe
|
split rgeoutages into its own repository
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4fc0539
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+index.html
+outages_*
|
rtucker/rgeoutages
|
cf505076adf6a3083bfd95df803a1760d3f73bde
|
rgeoutages: eliminate annoying errors by redirecting rm stderr to /dev/null
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 6df6bf1..6705c62 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,43 +1,43 @@
#!/bin/bash
GENERATOR=/var/www/hoopycat.com/html/rgeoutages/geocodecache.py
HTMLFILE=/var/www/hoopycat.com/html/rgeoutages/index.html
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
-rm /var/www/hoopycat.com/html/rgeoutages/outages_*.txt
+rm /var/www/hoopycat.com/html/rgeoutages/outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=/var/www/hoopycat.com/html/rgeoutages/outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
|
rtucker/rgeoutages
|
e795595e4d271c4703bd798dce2559e01341ca80
|
oops, typo on the rgeoutages munin support
|
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
index 6b4ef57..9274bb8 100755
--- a/rgeoutages_munin.sh
+++ b/rgeoutages_munin.sh
@@ -1,26 +1,26 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages
if [ "$1" = "config" ]; then
cat <<EOM
graph_title RG&E Power Outage Summary
graph_args --base 1000 -l 0
graph_vlabel outages
graph_category Climate
outages.draw AREA
outages.label outages
EOM
elif [ "$1" = "autoconf" ]; then
if [ -f $BASEDIR/fetch_outages.sh ]; then
echo "yes"
else
echo "no"
fi
else
outagecount=`cat $BASEDIR/outages_*.txt | wc -l`
- echo "outages.data $outagecount"
+ echo "outages.value $outagecount"
fi
|
rtucker/rgeoutages
|
046ba6a962581715636d5ae9e28ceade2eac68a9
|
some munin magic for rgeoutages
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 8e01992..6df6bf1 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,42 +1,43 @@
#!/bin/bash
GENERATOR=/var/www/hoopycat.com/html/rgeoutages/geocodecache.py
HTMLFILE=/var/www/hoopycat.com/html/rgeoutages/index.html
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
+rm /var/www/hoopycat.com/html/rgeoutages/outages_*.txt
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=/var/www/hoopycat.com/html/rgeoutages/outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
new file mode 100755
index 0000000..6b4ef57
--- /dev/null
+++ b/rgeoutages_munin.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+BASEDIR=/var/www/hoopycat.com/html/rgeoutages
+
+if [ "$1" = "config" ]; then
+ cat <<EOM
+graph_title RG&E Power Outage Summary
+graph_args --base 1000 -l 0
+graph_vlabel outages
+graph_category Climate
+outages.draw AREA
+outages.label outages
+EOM
+
+elif [ "$1" = "autoconf" ]; then
+ if [ -f $BASEDIR/fetch_outages.sh ]; then
+ echo "yes"
+ else
+ echo "no"
+ fi
+
+else
+ outagecount=`cat $BASEDIR/outages_*.txt | wc -l`
+ echo "outages.data $outagecount"
+fi
+
|
rtucker/rgeoutages
|
eebf6a383cfbf59dcfcbdc61965d4ecc31f4a0a4
|
rgeoutages: rm the tempfile, always
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index c07c525..8e01992 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,41 +1,42 @@
#!/bin/bash
GENERATOR=/var/www/hoopycat.com/html/rgeoutages/geocodecache.py
HTMLFILE=/var/www/hoopycat.com/html/rgeoutages/index.html
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=/var/www/hoopycat.com/html/rgeoutages/outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
- rm $TEMPFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
+rm $TEMPFILE
+
|
rtucker/rgeoutages
|
b0c85807cbb7310bf3a074f743a915ca62168e16
|
rgeoutages: a demo file with an actual outage (used for lightningtalk)
|
diff --git a/demo1.html b/demo1.html
new file mode 100644
index 0000000..6e8677e
--- /dev/null
+++ b/demo1.html
@@ -0,0 +1,133 @@
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
+ <head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+ <title>Current Power Outage Map for Rochester, New York</title>
+<style type="text/css">
+ v\:* {behavior:url(#default#VML);} html, body {width: 100%; height: 100%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
+
+ p, li {
+ font-family: Verdana, sans-serif;
+ font-size: 13px;
+ }
+
+ a {
+ text-decoration: none;
+ }
+
+ .hidden { visibility: hidden; }
+ .unhidden { visibility: visible; }
+
+</style>
+<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA30Jhq_DCCBUDYXZhoCyheRSUYQ6bykvEQfbcB8o1clNVPLJCmBS95D0ZW-pGwa1P39Qz-hMw8rGwxA" type="text/javascript"></script>
+<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
+<script type="text/javascript">
+
+ function hide(divID) {
+ var item = document.getElementById(divID);
+ if (item) {
+ item.className=(item.className=='unhidden')?'hidden':'unhidden';
+ }
+ }
+
+ function unhide(divID) {
+ var item = document.getElementById(divID);
+ if (item) {
+ item.className=(item.className=='hidden')?'unhidden':'hidden';
+ }
+ }
+
+ var map = null;
+ var mgr = null;
+
+ function initialize() {
+ if (GBrowserIsCompatible()) {
+ map = new GMap2(document.getElementById("map_canvas"));
+ map.setCenter(new GLatLng(43.15661, -77.6253), 11);
+ map.setUIToDefault();
+ mgr = new MarkerManager(map);
+ window.setTimeout(setupMarkers, 0);
+
+ // Monitor the window resize event and let the map know when it occurs
+ if (window.attachEvent) {
+ window.attachEvent("onresize", function() {this.map.onResize()} );
+ } else {
+ window.addEventListener("resize", function() {this.map.onResize()} , false);
+ }
+ }
+ }
+
+ function createMarker(point, text) {
+ var baseIcon = new GIcon(G_DEFAULT_ICON);
+ baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
+ baseIcon.iconSize = new GSize(20, 34);
+ baseIcon.shadowSize = new GSize(37, 34);
+ baseIcon.iconAnchor = new GPoint(9, 34);
+ baseIcon.infoWindowAnchor = new GPoint(9, 2);
+
+ var ouricon = new GIcon(baseIcon);
+ ouricon.image = "http://www.google.com/mapfiles/marker.png";
+
+ // Set up our GMarkerOptions object
+ markerOptions = { icon:ouricon };
+ var marker = new GMarker(point, markerOptions);
+
+ GEvent.addListener(marker, "click", function() {
+ marker.openInfoWindowHtml(text);
+ });
+ return marker;
+ }
+
+
+ function setupMarkers() {
+ var batch = [];
+ batch.push(new createMarker(new GLatLng(43.119722, -77.805833), "North Chili, NY, USA"));
+batch.push(new createMarker(new GLatLng(43.119722, -77.805833), "North Chili, NY, USA"));
+batch.push(new createMarker(new GLatLng(43.245875, -77.503479), "Fairview Cir, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.248458, -77.502348), "Forest Lawn Dr, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.248701, -77.502900), "Forest Lawn Rd, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.251603, -77.459161), "Lake Rd, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.244787, -77.507164), "Lake View Terrace, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.242993, -77.511528), "Locust Hill Dr, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.245911, -77.504571), "McArthur Rd, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.371109, -75.414559), "Webster Hill Rd/Oatman Rd, Western, NY 13309, USA"));
+batch.push(new createMarker(new GLatLng(43.245993, -77.501485), "Tanglewood Ct, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.242807, -77.499945), "Vosburg Rd, Webster, NY 14580, USA"));
+batch.push(new createMarker(new GLatLng(43.242181, -77.512481), "Windward Shores Dr, Webster, NY 14580, USA"));
+ mgr.addMarkers(batch, 1);
+ mgr.refresh();
+ }
+
+ </script>
+ </head>
+ <body onload="initialize()" onunload="GUnload()">
+ <div id="map_canvas" style="width: 100%; height: 100%;"></div>
+
+ <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%; opacity:0.8">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
+ </div>
+ <p><b>Map of Rochester-area Power Outages</b> as of Friday, May 14, 2010 at 5:24 PM
+ (13 streets). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
+ <p style="font-size:xx-small;"><a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=NORTH%20CHILI">NORTH CHILI</a>: 2 streets; <a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=WEBSTER">WEBSTER</a>: 11 streets</p>
+ </div>
+
+ <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
+ </div>
+ <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
+ <hr>
+ <p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
+ <p>Some important tips to keep in mind...</p>
+ <ul>
+ <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
+ <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
+ </ul>
+ <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
+ </div>
+
+ </body>
+</html>
|
rtucker/rgeoutages
|
be3af0b1e1472b24c217833929ed3880feeb01af
|
exit quietly if there are no outages -- fixme to actually update the page
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
new file mode 100755
index 0000000..c07c525
--- /dev/null
+++ b/fetch_outages.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+
+GENERATOR=/var/www/hoopycat.com/html/rgeoutages/geocodecache.py
+HTMLFILE=/var/www/hoopycat.com/html/rgeoutages/index.html
+
+# Fetch location list
+TEMPFILE=`tempfile`
+wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
+
+LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
+
+rm $TEMPFILE
+
+for i in $LOCATIONS
+do
+ TEMPFILE=`tempfile`
+ OUTFILE=/var/www/hoopycat.com/html/rgeoutages/outages_$i.txt
+ wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
+ grep "wcHeader_Label3" $TEMPFILE \
+ | cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
+ grep "<td nowrap=\"nowrap\">" $TEMPFILE \
+ | cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
+ rm $TEMPFILE
+ sleep 2
+done
+
+# All together now
+TEMPFILE=`tempfile`
+
+$GENERATOR $LOCATIONS > $TEMPFILE
+
+if [ -n "`cat $TEMPFILE`" ]; then
+ cp $TEMPFILE $HTMLFILE
+ rm $TEMPFILE
+elif [ -z "$LOCATIONS" ] ; then
+ # there are no outages! do something cool.
+ true
+else
+ echo "$TEMPFILE was empty, utoh"
+fi
+
diff --git a/geocodecache.py b/geocodecache.py
new file mode 100755
index 0000000..01ebf31
--- /dev/null
+++ b/geocodecache.py
@@ -0,0 +1,301 @@
+#!/usr/bin/python
+
+import sqlite3
+import sys
+import time
+import urllib
+import urllib2
+
+try:
+ import json
+except:
+ import simplejson as json
+
+def initDB(filename="/tmp/rgeoutages.sqlite3"):
+ """Connect to and initialize the cache database.
+
+ Optional: Filename of database
+ Returns: db object
+ """
+
+ db = sqlite3.connect(filename)
+ c = db.cursor()
+ c.execute('pragma table_info(geocodecache)')
+ columns = ' '.join(i[1] for i in c.fetchall()).split()
+ if columns == []:
+ # need to create table
+ c.execute("""create table geocodecache
+ (town text, streetname text, latitude real, longitude real,
+ formattedaddress text, locationtype text, lastcheck integer,
+ viewport text)""")
+ db.commit()
+
+ return db
+
+def fetchGeocode(location):
+ """Fetches geocoding information.
+
+ Returns dictionary of formattedaddress, latitude, longitude,
+ locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
+ """
+
+ sanelocation = urllib.quote(location)
+
+ response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
+
+ jsondata = response.read()
+ data = json.loads(jsondata)['results'][0]
+
+ viewport = ( data['geometry']['viewport']['southwest']['lat'],
+ data['geometry']['viewport']['southwest']['lng'],
+ data['geometry']['viewport']['northeast']['lat'],
+ data['geometry']['viewport']['northeast']['lng'] )
+ outdict = { 'formattedaddress': data['formatted_address'],
+ 'latitude': data['geometry']['location']['lat'],
+ 'longitude': data['geometry']['location']['lng'],
+ 'locationtype': data['geometry']['location_type'],
+ 'viewport': viewport }
+
+ time.sleep(1)
+
+ return outdict
+
+def geocode(db, town, location):
+ """Geocodes a location, either using the cache or the Google.
+
+ Returns dictionary of formattedaddress, latitude, longitude,
+ locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
+ """
+
+ town = town.lower().strip()
+ location = location.lower().strip()
+
+ using_cache = False
+
+ # check the db
+ c = db.cursor()
+ c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
+
+ rows = c.fetchall()
+ if rows:
+ (latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
+ if lastcheck < (time.time()+(7*24*60*60)):
+ using_cache = True
+ viewport = tuple(json.loads(viewport_json))
+
+ outdict = { 'formattedaddress': formattedaddress,
+ 'latitude': latitude,
+ 'longitude': longitude,
+ 'locationtype': locationtype,
+ 'viewport': viewport }
+ return outdict
+
+ if not using_cache:
+ fetchresult = fetchGeocode(location + ", " + town + " NY")
+
+ viewport_json = json.dumps(fetchresult['viewport'])
+
+ c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
+ db.commit()
+
+ return fetchresult
+
+def produceMapHeader(apikey, markers, centers):
+ """Produces a map header given an API key and a list of produceMarkers"""
+
+ out = """
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
+ <head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+ <title>Current Power Outage Map for Rochester, New York</title>
+<style type="text/css">
+ v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
+
+ p, li {
+ font-family: Verdana, sans-serif;
+ font-size: 13px;
+ }
+
+ a {
+ text-decoration: none;
+ }
+
+ .hidden { visibility: hidden; }
+ .unhidden { visibility: visible; }
+
+</style>
+<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
+<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
+<script type="text/javascript">
+
+ function hide(divID) {
+ var item = document.getElementById(divID);
+ if (item) {
+ item.className=(item.className=='unhidden')?'hidden':'unhidden';
+ }
+ }
+
+ function unhide(divID) {
+ var item = document.getElementById(divID);
+ if (item) {
+ item.className=(item.className=='hidden')?'unhidden':'hidden';
+ }
+ }
+
+ var map = null;
+ var mgr = null;
+
+ function initialize() {
+ if (GBrowserIsCompatible()) {
+ map = new GMap2(document.getElementById("map_canvas"));
+ map.setCenter(new GLatLng(43.15661, -77.6253), 11);
+ map.setUIToDefault();
+ mgr = new MarkerManager(map);
+ window.setTimeout(setupMarkers, 0);
+
+ // Monitor the window resize event and let the map know when it occurs
+ if (window.attachEvent) {
+ window.attachEvent("onresize", function() {this.map.onResize()} );
+ } else {
+ window.addEventListener("resize", function() {this.map.onResize()} , false);
+ }
+ }
+ }
+
+ function createMarker(point, text) {
+ var baseIcon = new GIcon(G_DEFAULT_ICON);
+ baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
+ baseIcon.iconSize = new GSize(20, 34);
+ baseIcon.shadowSize = new GSize(37, 34);
+ baseIcon.iconAnchor = new GPoint(9, 34);
+ baseIcon.infoWindowAnchor = new GPoint(9, 2);
+
+ var ouricon = new GIcon(baseIcon);
+ ouricon.image = "http://www.google.com/mapfiles/marker.png";
+
+ // Set up our GMarkerOptions object
+ markerOptions = { icon:ouricon };
+ var marker = new GMarker(point, markerOptions);
+
+ GEvent.addListener(marker, "click", function() {
+ marker.openInfoWindowHtml(text);
+ });
+ return marker;
+ }
+
+""" % apikey
+
+ if len(markers) > 300:
+ out += """
+ function setupMarkers() {
+ var batch = [];
+ %s
+ mgr.addMarkers(batch, 12);
+ var batch = [];
+ %s
+ mgr.addMarkers(batch, 1, 12);
+ mgr.refresh();
+ }
+ """ % ('\n'.join(markers), '\n'.join(centers))
+ else:
+ out += """
+ function setupMarkers() {
+ var batch = [];
+ %s
+ mgr.addMarkers(batch, 1);
+ mgr.refresh();
+ }
+ """ % '\n'.join(markers)
+
+ out += """
+ </script>
+ </head>
+ """
+
+ return out
+
+def produceMarker(lat, long, text):
+ """Produces a google maps marker given a latitude, longitude, and text"""
+ return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
+
+def produceMapBody(body):
+ return """ <body onload="initialize()" onunload="GUnload()">
+ <div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
+ %s
+ </body>
+</html>
+""" % body
+
+if __name__ == '__main__':
+ db = initDB()
+ apikey = "ABQIAAAA30Jhq_DCCBUDYXZhoCyheRSUYQ6bykvEQfbcB8o1clNVPLJCmBS95D0ZW-pGwa1P39Qz-hMw8rGwxA"
+
+ localelist = []
+ markerlist = []
+ citycenterlist = []
+
+ stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
+
+ for i in sys.argv[1:]:
+ if i in stoplist:
+ continue
+
+ fd = open('/var/www/hoopycat.com/html/rgeoutages/outages_%s.txt' % i)
+ lastupdated = fd.readline()
+ cleanname = i.replace('%20', ' ')
+
+ count = 0
+
+ citycenter = geocode(db, cleanname, '')
+ citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
+
+ for j in fd.readlines():
+ streetinfo = geocode(db, cleanname, j)
+ markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
+ count += 1
+
+ if count > 1:
+ s = 's'
+ else:
+ s = ''
+
+ localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
+
+ if len(markerlist) > 0:
+ if len(markerlist) > 300:
+ s = 's -- zoom for more detail'
+ elif len(markerlist) > 1:
+ s = 's'
+ else:
+ s = ''
+ sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist))
+
+ bodytext = """
+ <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
+ </div>
+ <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). <a href="javascript:unhide('faqbox');">More information about this page...</a></p>
+ <p style="font-size:xx-small;">%s</p>
+ </div>
+
+ <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
+ </div>
+ <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
+ <hr>
+ <p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>.</p>
+ <p>Some important tips to keep in mind...</p>
+ <ul>
+ <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
+ <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
+ </ul>
+ <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
+ </div>
+ """ % (lastupdated, len(markerlist), s, '; '.join(localelist))
+
+ sys.stdout.write(produceMapBody(bodytext))
+
diff --git a/xbox.png b/xbox.png
new file mode 100644
index 0000000..9d74826
Binary files /dev/null and b/xbox.png differ
|
igal/rcov_tutorial
|
878d4bca80d9a2902d601d8374fe1163975f5639
|
Added PDF of presentation.
|
diff --git a/rcov_tutorial.pdf b/rcov_tutorial.pdf
new file mode 100644
index 0000000..26e296c
Binary files /dev/null and b/rcov_tutorial.pdf differ
|
igal/rcov_tutorial
|
1b86c2e3ae902d39be49cb489b2f4d6b2a59d6ee
|
Improved mylibrary.rb, added more variants of statements whose path coverage is and isn't shown, and annotated these.
|
diff --git a/mylibrary/lib/mylibrary.rb b/mylibrary/lib/mylibrary.rb
index 9af3045..7b86d8a 100644
--- a/mylibrary/lib/mylibrary.rb
+++ b/mylibrary/lib/mylibrary.rb
@@ -1,38 +1,52 @@
class MyLibrary
def hello
return "Greetings!"
end
def lucky?
return true
end
def get_kitten
return :kitten
end
def get_hyena
1/0
end
def run
hello
+ # No branch coverage shown for these
mypet = lucky? ? get_kitten : get_hyena
+ mypet = lucky? && get_kitten || get_hyena
+
+ mypet = lucky? &&
+ get_kitten ||
+ get_hyena
+
+ # Branch coverage is shown for these
+ mypet = lucky? ?
+ get_kitten :
+ get_hyena
+
mypet = \
if lucky?
get_kitten
else
get_hyena
end
+ # No branch coverage shown
puts 1/0 unless lucky?
+ # Branch coverage is shown
unless lucky?
puts 1/0
end
return :yay
end
end
|
igal/rcov_tutorial
|
52ec291c3d427e274cc2a41fe0da7b95724462e5
|
Wrote code and presentation.
|
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..a8c1582
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,23 @@
+http://www.opensource.org/licenses/mit-license.php
+
+The MIT License
+
+Copyright (c) 2010 Igal Koshevoy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d921c8b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,8 @@
+RCov Tutorial
+=============
+
+A presentation and source code demonstrating the use of the RCov code coverage
+tool for Ruby:
+
+- rcov_tutorial.odp: The presention.
+- mylibrary: Directory with sample code, see its README.md for details.
diff --git a/mylibrary/.gitignore b/mylibrary/.gitignore
new file mode 100644
index 0000000..6af4973
--- /dev/null
+++ b/mylibrary/.gitignore
@@ -0,0 +1,3 @@
+coverage
+coverage.info
+*.swp
diff --git a/mylibrary/README.md b/mylibrary/README.md
new file mode 100644
index 0000000..f370874
--- /dev/null
+++ b/mylibrary/README.md
@@ -0,0 +1,19 @@
+MyLibrary: Sample code to demonstrate RCov code coverage tool
+=============================================================
+
+Files
+-----
+- Rakefile - Tasks for running specs and generating coverage reports
+- lib/mylibrary.rb - MyLibrary demonstrates code coverage
+- spec/mylibrary_spec.rb - Specs that describe behavior of MyLibrary
+
+Rake tasks
+----------
+- rake spec - Run the specs
+- rake rcov - Run the specs and generate code coverage report
+- rake rcov:save - Run the specs, generate code coverage report and save coverage info
+- rake rcov:diff - Run the specs and display uncovered code added since last save
+
+Coverage report
+---------------
+The "rcov" Rake tasks will generate a coverage report at "coverage/index.html".
diff --git a/mylibrary/Rakefile b/mylibrary/Rakefile
new file mode 100644
index 0000000..624cb80
--- /dev/null
+++ b/mylibrary/Rakefile
@@ -0,0 +1,36 @@
+require 'rubygems'
+require 'spec/rake/spectask'
+
+task :default => :spec
+
+# Provides :spec task
+@spectask = Spec::Rake::SpecTask.new do |t|
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+desc 'Run specs and generate a code coverage report with RCov'
+task :rcov do
+ @spectask.rcov = true
+ @spectask.rcov_opts += ['--include', 'lib']
+ @spectask.rcov_opts += ['--exclude', 'spec']
+ Rake::Task[:spec].invoke
+ puts "Generated code coverage report at: coverage/index.html"
+end
+
+desc 'Save coverage status'
+task 'rcov:save' do
+ @spectask.rcov_opts << '--save'
+ Rake::Task[:rcov].invoke
+end
+
+desc 'Display diff of coverage status since last save'
+task 'rcov:diff' do
+ @spectask.rcov_opts << '--text-coverage-diff'
+ Rake::Task[:rcov].invoke
+end
+
+desc 'Clean up, delete coverage report and coverage status'
+task :clean do
+ rm_r 'coverage' rescue nil
+ rm_r 'coverage.info' rescue nil
+end
diff --git a/mylibrary/lib/mylibrary.rb b/mylibrary/lib/mylibrary.rb
new file mode 100644
index 0000000..9af3045
--- /dev/null
+++ b/mylibrary/lib/mylibrary.rb
@@ -0,0 +1,38 @@
+class MyLibrary
+ def hello
+ return "Greetings!"
+ end
+
+ def lucky?
+ return true
+ end
+
+ def get_kitten
+ return :kitten
+ end
+
+ def get_hyena
+ 1/0
+ end
+
+ def run
+ hello
+
+ mypet = lucky? ? get_kitten : get_hyena
+
+ mypet = \
+ if lucky?
+ get_kitten
+ else
+ get_hyena
+ end
+
+ puts 1/0 unless lucky?
+
+ unless lucky?
+ puts 1/0
+ end
+
+ return :yay
+ end
+end
diff --git a/mylibrary/spec/mylibrary_spec.rb b/mylibrary/spec/mylibrary_spec.rb
new file mode 100644
index 0000000..5536fb0
--- /dev/null
+++ b/mylibrary/spec/mylibrary_spec.rb
@@ -0,0 +1,19 @@
+require File.join(File.dirname(__FILE__), '..', 'lib', 'mylibrary')
+
+describe MyLibrary do
+ before(:each) do
+ @library = MyLibrary.new
+ end
+
+ it "should greet us" do
+ @library.hello.should == "Greetings!"
+ end
+
+ it "should give us a kitten" do
+ @library.get_kitten.should == :kitten
+ end
+
+ it "should run successfully" do
+ @library.run.should == :yay
+ end
+end
diff --git a/rcov_tutorial.odp b/rcov_tutorial.odp
new file mode 100644
index 0000000..14fcfd2
Binary files /dev/null and b/rcov_tutorial.odp differ
|
mtmiller/dotfiles
|
5fd234b78a2183f74aa0da2a9de39e3c7043294e
|
shrc: Define SYSTEMD_LESS
|
diff --git a/shrc b/shrc
index 1412b1e..da77b02 100644
--- a/shrc
+++ b/shrc
@@ -1,125 +1,126 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in iceweasel firefox chromium chromium-browser google-chrome; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-ix8z-3FQRSX}"
MANPAGER='less -s'
- export LESS MANPAGER
+ SYSTEMD_LESS=$LESS
+ export LESS MANPAGER SYSTEMD_LESS
unset MANLESS
if man --help 2>&1 | grep -- "--prompt=" > /dev/null 2>&1; then
if man --version 2>&1 | grep -E " 2\.([45]|6\.[0123])" > /dev/null 2>&1; then
MANLESS=$LESS
export MANLESS
else
MANLESS='?e(END)'
export MANLESS
fi
fi
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if tty > /dev/null 2>&1; then
# Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
unset mode
;;
esac
# Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
if [ X"$TERM" = Xxterm ]; then
TERM=xterm-256color
export TERM
fi
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
d3c2223609b1fa04e297eeec0b78c318decb73ce
|
shrc: Define MANLESS depending on man version
|
diff --git a/shrc b/shrc
index c416de6..1412b1e 100644
--- a/shrc
+++ b/shrc
@@ -1,115 +1,125 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in iceweasel firefox chromium chromium-browser google-chrome; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-ix8z-3FQRSX}"
MANPAGER='less -s'
export LESS MANPAGER
+ unset MANLESS
+ if man --help 2>&1 | grep -- "--prompt=" > /dev/null 2>&1; then
+ if man --version 2>&1 | grep -E " 2\.([45]|6\.[0123])" > /dev/null 2>&1; then
+ MANLESS=$LESS
+ export MANLESS
+ else
+ MANLESS='?e(END)'
+ export MANLESS
+ fi
+ fi
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if tty > /dev/null 2>&1; then
# Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
unset mode
;;
esac
# Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
if [ X"$TERM" = Xxterm ]; then
TERM=xterm-256color
export TERM
fi
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
73f45faacf14af670e34026f622370a28d57db6d
|
shrc: Add more default less options
|
diff --git a/shrc b/shrc
index 32f1b7b..c416de6 100644
--- a/shrc
+++ b/shrc
@@ -1,115 +1,115 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in iceweasel firefox chromium chromium-browser google-chrome; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
- LESS="${LESS:-iFRSX}"
+ LESS="${LESS:-ix8z-3FQRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if tty > /dev/null 2>&1; then
# Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
unset mode
;;
esac
# Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
if [ X"$TERM" = Xxterm ]; then
TERM=xterm-256color
export TERM
fi
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
fdaf49bcedd6bb8302161509c764046aae699f79
|
Set all font preferences to generic Monospace
|
diff --git a/Xresources b/Xresources
index b212e96..68852bd 100644
--- a/Xresources
+++ b/Xresources
@@ -1,68 +1,68 @@
-emacs.font: Inconsolata-11
+emacs.font: Monospace-10
Rxvt.background: #000000
Rxvt.foreground: #d3d7cf
Rxvt.color0: #000000
Rxvt.color1: #cc0000
Rxvt.color2: #4e9a06
Rxvt.color3: #c4a000
Rxvt.color4: #3465a4
Rxvt.color5: #75507b
Rxvt.color6: #06989a
Rxvt.color7: #d3d7cf
Rxvt.color8: #555753
Rxvt.color9: #ef2929
Rxvt.color10: #8ae234
Rxvt.color11: #fce94f
Rxvt.color12: #729fcf
Rxvt.color13: #ad7fa8
Rxvt.color14: #34e2e2
Rxvt.color15: #eeeeec
Rxvt.font: 7x14
-URxvt.font: xft:Inconsolata:pixelsize=14
+URxvt.font: xft:Monospace:size=10
URxvt.letterSpace: -1
UXTerm.background: #000000
UXterm.foreground: #d3d7cf
UXTerm.vt100.background: #000000
UXTerm.vt100.foreground: #d3d7cf
UXTerm.vt100.color0: #000000
UXTerm.vt100.color1: #cc0000
UXTerm.vt100.color2: #4e9a06
UXTerm.vt100.color3: #c4a000
UXTerm.vt100.color4: #3465a4
UXTerm.vt100.color5: #75507b
UXTerm.vt100.color6: #06989a
UXTerm.vt100.color7: #d3d7cf
UXTerm.vt100.color8: #555753
UXTerm.vt100.color9: #ef2929
UXTerm.vt100.color10: #8ae234
UXTerm.vt100.color11: #fce94f
UXTerm.vt100.color12: #729fcf
UXTerm.vt100.color13: #ad7fa8
UXTerm.vt100.color14: #34e2e2
UXTerm.vt100.color15: #eeeeec
UXTerm.vt100.font: 7x14
-UXTerm.vt100.faceName: Inconsolata
-UXTerm.vt100.faceSize: 11
+UXTerm.vt100.faceName: Monospace
+UXTerm.vt100.faceSize: 10
XTerm.background: #000000
XTerm.foreground: #d3d7cf
XTerm.vt100.background: #000000
XTerm.vt100.foreground: #d3d7cf
XTerm.vt100.color0: #000000
XTerm.vt100.color1: #cc0000
XTerm.vt100.color2: #4e9a06
XTerm.vt100.color3: #c4a000
XTerm.vt100.color4: #3465a4
XTerm.vt100.color5: #75507b
XTerm.vt100.color6: #06989a
XTerm.vt100.color7: #d3d7cf
XTerm.vt100.color8: #555753
XTerm.vt100.color9: #ef2929
XTerm.vt100.color10: #8ae234
XTerm.vt100.color11: #fce94f
XTerm.vt100.color12: #729fcf
XTerm.vt100.color13: #ad7fa8
XTerm.vt100.color14: #34e2e2
XTerm.vt100.color15: #eeeeec
XTerm.vt100.font: 7x14
-XTerm.vt100.faceName: Inconsolata
-XTerm.vt100.faceSize: 11
+XTerm.vt100.faceName: Monospace
+XTerm.vt100.faceSize: 10
diff --git a/emacs b/emacs
index a3f83d6..644a380 100644
--- a/emacs
+++ b/emacs
@@ -1,16 +1,16 @@
;; ~/.emacs
(when (fboundp 'blink-cursor-mode)
(blink-cursor-mode 0))
(dolist (fn '(global-font-lock-mode show-paren-mode transient-mark-mode))
(when (fboundp fn)
(funcall fn t)))
(custom-set-variables
'(diff-switches "-u")
'(frame-title-format (concat "%b - " (invocation-name) "@" (system-name)))
'(require-final-newline 'query)
'(ring-bell-function 'ignore)
'(scroll-bar-mode 'right))
-(add-to-list 'default-frame-alist '(font . "Inconsolata-11"))
+(add-to-list 'default-frame-alist '(font . "Monospace-10"))
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 380b2e0..563e522 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,184 +1,184 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Configure Vim NERDTree with a useful default ignore list.
let g:NERDTreeIgnore = ['\.[ao]$', '\.l[ao]$', '\.py[co]$', '\.so$', '\~$']
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
endif
if &term =~ "^screen"
set background=dark
if strlen($TMUX)
set t_Co=256
endif
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
" Configure Vim cscope interface.
if has("cscope") && executable("cscope")
set csprg=cscope
set csto=0
set cst
set nocsverb
if filereadable("cscope.out")
cs add cscope.out
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
- set guifont=Inconsolata\ 11,Liberation\ Mono\ 10,Monospace\ 10
+ set guifont=Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
03dfd0b764fb7c9d34a09d71c6ac14bca0c91699
|
fontconfig: Prefer Droid Sans Mono
|
diff --git a/config/fontconfig/conf.d/60-monospace-prefs.conf b/config/fontconfig/conf.d/60-monospace-prefs.conf
new file mode 100644
index 0000000..12968bf
--- /dev/null
+++ b/config/fontconfig/conf.d/60-monospace-prefs.conf
@@ -0,0 +1,10 @@
+<?xml version="1.0"?>
+<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
+<fontconfig>
+ <alias>
+ <family>monospace</family>
+ <prefer>
+ <family>Droid Sans Mono</family>
+ </prefer>
+ </alias>
+</fontconfig>
|
mtmiller/dotfiles
|
676e0a68f6fe54f1460a76a02f16b5666737229f
|
hgrc: Fix alias describe, add alias ls â manifest
|
diff --git a/hgrc b/hgrc
index d2cb661..ed473a5 100644
--- a/hgrc
+++ b/hgrc
@@ -1,35 +1,36 @@
[alias]
-describe = log --rev . --template '{latesttag}-{latesttagdistance}-{node|short}\n'
+describe = log --limit 1 --template '{latesttag}+{latesttagdistance}-{node|short}\n'
gc = strip --hidden --rev 'extinct()'
grepdir = !$HG manifest | tr '\n' '\0' | xargs -0 grep --color=auto -E -- $@
+ls = manifest
[defaults]
log = -v
[diff]
git = True
showfunc = True
[extensions]
churn =
color =
convert =
graphlog =
hgk =
hgview =
histedit =
largefiles =
mq =
pager =
progress =
purge =
rebase =
record =
shelve =
[pager]
attend = annotate, cat, diff, export, glog, help, incoming, log, outgoing, \
qdiff, status, tags
[ui]
ignore = ~/.hgignore
|
mtmiller/dotfiles
|
e148ef432da4caf336d45ec8482c220843ab9b15
|
gemrc: New dotfile
|
diff --git a/gemrc b/gemrc
new file mode 100644
index 0000000..55ac69d
--- /dev/null
+++ b/gemrc
@@ -0,0 +1 @@
+install: --bindir ~/bin --user-install
|
mtmiller/dotfiles
|
a3d61ed4c100c0739962f2f3622b7e0b399d908d
|
shrc: Delete Python and Ruby library path config
|
diff --git a/shrc b/shrc
index 233fc95..32f1b7b 100644
--- a/shrc
+++ b/shrc
@@ -1,150 +1,115 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
-# Configure user Python library paths.
-# Assume Python packages are installed as python setup.py install --prefix=~
-cmd="from distutils import sysconfig"
-cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
-for dir in `python -c "$cmd" 2> /dev/null`; do
- if [ -n "$dir" ]; then
- __list_prepend_uniq PYTHONPATH "$dir"
- export PYTHONPATH
- fi
-done
-
-# Configure personal RubyGems environment and add bin directory to PATH.
-cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
-ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
-if [ -n "$ver" ]; then
- GEM_HOME="$HOME/.gem/ruby/$ver"
- GEM_PATH="$GEM_HOME"
- export GEM_HOME GEM_PATH
-fi
-cmd='puts Gem.default_dir'
-dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
-if [ -n "$dir" ] && [ -d "$dir" ]; then
- __list_append_uniq GEM_PATH "$dir"
- export GEM_PATH
-fi
-cmd='puts Gem.bindir'
-dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
-if [ -n "$dir" ] && [ -d "$dir" ]; then
- if ! __list_contains PATH "$dir"; then
- # Put this directory at the front of PATH, but after ~/bin if present.
- PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
- fi
-fi
-unset cmd dir ver
-
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in iceweasel firefox chromium chromium-browser google-chrome; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if tty > /dev/null 2>&1; then
# Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
unset mode
;;
esac
# Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
if [ X"$TERM" = Xxterm ]; then
TERM=xterm-256color
export TERM
fi
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
9dc26598e7e87d6483aa17574d6c9b234034310f
|
Promote iceweasel/firefox to default browser
|
diff --git a/gitconfig b/gitconfig
index f1bf0f2..06e487a 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,6 +1,6 @@
[color]
ui = auto
[core]
excludesfile = ~/.config/git/ignore
[web]
- browser = chromium
+ browser = firefox
diff --git a/shrc b/shrc
index 0daa95f..233fc95 100644
--- a/shrc
+++ b/shrc
@@ -1,150 +1,150 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
- for util in chromium chromium-browser google-chrome firefox; do
+ for util in iceweasel firefox chromium chromium-browser google-chrome; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if tty > /dev/null 2>&1; then
# Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
unset mode
;;
esac
# Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
if [ X"$TERM" = Xxterm ]; then
TERM=xterm-256color
export TERM
fi
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
4c4aeb5cc25ea59712adae424ba48504aa841823
|
Fix grep match color on 256-color terms
|
diff --git a/bashrc b/bashrc
index 352ae67..3fd26db 100644
--- a/bashrc
+++ b/bashrc
@@ -1,174 +1,174 @@
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# Load common shell initializations
if [ -r ~/.shrc ]; then
. ~/.shrc
fi
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# Clear any aliases inherited from the system (no thank you, Red Hat)
unalias -a
# don't put duplicate lines in the history. See bash(1) for more options
# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
HISTCONTROL=$HISTCONTROL${HISTCONTROL+:}ignoredups
# ... or force ignoredups and ignorespace
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# set history length, save history to a file, and remember times for each
# history entry
HISTSIZE=1000
HISTFILE=~/.bash_history
HISTFILESIZE=1000
HISTTIMEFORMAT='%x %X '
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
screen*)
PS1="\[\e_${debian_chroot:+($debian_chroot)}\u@\h: \w\e\\\\\]$PS1"
;;
*)
;;
esac
# Enable color support in ls if the shell is on a valid terminal.
case "$TERM" in
""|dumb)
;;
*)
# GNU ls and dircolors are both part of coreutils, prefer this option.
# Fall back to colorls for *BSD.
if [ -x /usr/bin/dircolors ]; then
case "$TERM" in
*256col*) fn=~/.dircolors-256color ;;
*) fn=~/.dircolors ;;
esac
if [ "$TMUX" ]; then
fn=~/.dircolors-256color
fi
if [ ! -r $fn ]; then
fn=~/.dircolors
fi
if [ -r $fn ]; then
# be backwards-compatible: attempt to detect newer keywords not
# understood by the available version of dircolors and filter
# them out
errs=$(dircolors -b $fn 2>&1 > /dev/null)
bad=$(echo "$errs" | sed -n 's/^.*: unrecognized keyword \(.*\)$/\1/p')
if [ "$bad" ]; then
fix='grep -F -v "$bad"'
# special cases:
# - if dircolors doesn't know RESET, use NORMAL and FILE
# - if dircolors doesn't know OTHER_WRITABLE, remove SET[GU]ID
for word in $bad; do
case "$word" in
RESET) fix="sed 's/^RESET.*$/NORMAL 00\nFILE 00/' | $fix" ;;
*OTHER*) fix="grep -v 'SET[GU]ID' | $fix" ;;
esac
done
eval "$(cat $fn | eval $fix | dircolors -b -)"
else
eval "$(dircolors -b $fn)"
fi
unset bad errs fix word
else
eval "$(dircolors -b)"
fi
unset fn
alias ls='ls --color=auto'
case "$TERM" in
*256col*)
- GREP_COLOR="38;5;160"
- GREP_COLORS="ms=01;38;5;160:mc=01;38;5;160:sl=:cx=:fn=38;5;139"
+ GREP_COLOR="01;38;5;196"
+ GREP_COLORS="ms=01;38;5;196:mc=01;38;5;196:sl=:cx=:fn=38;5;139"
GREP_COLORS="$GREP_COLORS:ln=38;5;117:bn=38;5;117:se=38;5;37"
;;
*)
GREP_COLOR="01;31"
GREP_COLORS="ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=34:bn=34:se=36"
;;
esac
if [ "$TMUX" ]; then
- GREP_COLOR="38;5;160"
- GREP_COLORS="ms=01;38;5;160:mc=01;38;5;160:sl=:cx=:fn=38;5;139"
+ GREP_COLOR="01;38;5;196"
+ GREP_COLORS="ms=01;38;5;196:mc=01;38;5;196:sl=:cx=:fn=38;5;139"
GREP_COLORS="$GREP_COLORS:ln=38;5;117:bn=38;5;117:se=38;5;37"
fi
export GREP_COLOR GREP_COLORS
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
elif type colorls > /dev/null 2>&1; then
alias ls='colorls -G'
fi
;;
esac
# Define command aliases to invoke the preferred editor and pager utilities.
# Use the sensible-utils commands if on Debian; otherwise, use the values of
# standard variables.
if type sensible-editor > /dev/null 2>&1; then
alias editor=sensible-editor
alias e=sensible-editor
alias v=sensible-editor
elif [ -n "${VISUAL:-$EDITOR}" ]; then
alias editor="${VISUAL:-$EDITOR}"
alias e="${VISUAL:-$EDITOR}"
alias v="${VISUAL:-$EDITOR}"
fi
if type sensible-pager > /dev/null 2>&1; then
alias pager=sensible-pager
elif [ -n "$PAGER" ]; then
alias pager="$PAGER"
fi
# Compensate for Red Hat installing the most featureful Vim under a
# different name.
if type vimx > /dev/null 2>&1; then
alias vim=vimx
fi
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
# enable programmable completion from ~/.bash_completion (needed for some
# systems where system-wide bash-completion is not installed).
if [ -f ~/.bash_completion ] && ! shopt -oq posix; then
. ~/.bash_completion
fi
|
mtmiller/dotfiles
|
4d03f908134a4e98147448d3e4b8140dc328392b
|
Configure grep --color for 256-color terminals
|
diff --git a/bashrc b/bashrc
index 0664eba..352ae67 100644
--- a/bashrc
+++ b/bashrc
@@ -1,157 +1,174 @@
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# Load common shell initializations
if [ -r ~/.shrc ]; then
. ~/.shrc
fi
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# Clear any aliases inherited from the system (no thank you, Red Hat)
unalias -a
# don't put duplicate lines in the history. See bash(1) for more options
# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
HISTCONTROL=$HISTCONTROL${HISTCONTROL+:}ignoredups
# ... or force ignoredups and ignorespace
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# set history length, save history to a file, and remember times for each
# history entry
HISTSIZE=1000
HISTFILE=~/.bash_history
HISTFILESIZE=1000
HISTTIMEFORMAT='%x %X '
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
screen*)
PS1="\[\e_${debian_chroot:+($debian_chroot)}\u@\h: \w\e\\\\\]$PS1"
;;
*)
;;
esac
# Enable color support in ls if the shell is on a valid terminal.
case "$TERM" in
""|dumb)
;;
*)
# GNU ls and dircolors are both part of coreutils, prefer this option.
# Fall back to colorls for *BSD.
if [ -x /usr/bin/dircolors ]; then
case "$TERM" in
*256col*) fn=~/.dircolors-256color ;;
*) fn=~/.dircolors ;;
esac
if [ "$TMUX" ]; then
fn=~/.dircolors-256color
fi
if [ ! -r $fn ]; then
fn=~/.dircolors
fi
if [ -r $fn ]; then
# be backwards-compatible: attempt to detect newer keywords not
# understood by the available version of dircolors and filter
# them out
errs=$(dircolors -b $fn 2>&1 > /dev/null)
bad=$(echo "$errs" | sed -n 's/^.*: unrecognized keyword \(.*\)$/\1/p')
if [ "$bad" ]; then
fix='grep -F -v "$bad"'
# special cases:
# - if dircolors doesn't know RESET, use NORMAL and FILE
# - if dircolors doesn't know OTHER_WRITABLE, remove SET[GU]ID
for word in $bad; do
case "$word" in
RESET) fix="sed 's/^RESET.*$/NORMAL 00\nFILE 00/' | $fix" ;;
*OTHER*) fix="grep -v 'SET[GU]ID' | $fix" ;;
esac
done
eval "$(cat $fn | eval $fix | dircolors -b -)"
else
eval "$(dircolors -b $fn)"
fi
unset bad errs fix word
else
eval "$(dircolors -b)"
fi
unset fn
alias ls='ls --color=auto'
+ case "$TERM" in
+ *256col*)
+ GREP_COLOR="38;5;160"
+ GREP_COLORS="ms=01;38;5;160:mc=01;38;5;160:sl=:cx=:fn=38;5;139"
+ GREP_COLORS="$GREP_COLORS:ln=38;5;117:bn=38;5;117:se=38;5;37"
+ ;;
+ *)
+ GREP_COLOR="01;31"
+ GREP_COLORS="ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=34:bn=34:se=36"
+ ;;
+ esac
+ if [ "$TMUX" ]; then
+ GREP_COLOR="38;5;160"
+ GREP_COLORS="ms=01;38;5;160:mc=01;38;5;160:sl=:cx=:fn=38;5;139"
+ GREP_COLORS="$GREP_COLORS:ln=38;5;117:bn=38;5;117:se=38;5;37"
+ fi
+ export GREP_COLOR GREP_COLORS
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
elif type colorls > /dev/null 2>&1; then
alias ls='colorls -G'
fi
;;
esac
# Define command aliases to invoke the preferred editor and pager utilities.
# Use the sensible-utils commands if on Debian; otherwise, use the values of
# standard variables.
if type sensible-editor > /dev/null 2>&1; then
alias editor=sensible-editor
alias e=sensible-editor
alias v=sensible-editor
elif [ -n "${VISUAL:-$EDITOR}" ]; then
alias editor="${VISUAL:-$EDITOR}"
alias e="${VISUAL:-$EDITOR}"
alias v="${VISUAL:-$EDITOR}"
fi
if type sensible-pager > /dev/null 2>&1; then
alias pager=sensible-pager
elif [ -n "$PAGER" ]; then
alias pager="$PAGER"
fi
# Compensate for Red Hat installing the most featureful Vim under a
# different name.
if type vimx > /dev/null 2>&1; then
alias vim=vimx
fi
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
# enable programmable completion from ~/.bash_completion (needed for some
# systems where system-wide bash-completion is not installed).
if [ -f ~/.bash_completion ] && ! shopt -oq posix; then
. ~/.bash_completion
fi
|
mtmiller/dotfiles
|
b7ae2e83bbb5c82e7be37eb0f3cec2657158e0e3
|
Configure ls --color for 256-color terminals
|
diff --git a/Makefile.am b/Makefile.am
index 958ddc7..8f700a1 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,108 +1,109 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/bazaar.conf \
bazaar/ignore \
byobu/.tmux.conf \
caff/gnupghome/gpg.conf \
colordiffrc \
config/git/ignore \
cshrc \
cvsignore \
cvsrc \
devscripts \
dircolors \
+ dircolors-256color \
emacs \
gbp.conf \
gdbinit \
gitconfig \
hgignore \
hgrc \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/bashrc b/bashrc
index d6fa41e..0664eba 100644
--- a/bashrc
+++ b/bashrc
@@ -1,146 +1,157 @@
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# Load common shell initializations
if [ -r ~/.shrc ]; then
. ~/.shrc
fi
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# Clear any aliases inherited from the system (no thank you, Red Hat)
unalias -a
# don't put duplicate lines in the history. See bash(1) for more options
# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
HISTCONTROL=$HISTCONTROL${HISTCONTROL+:}ignoredups
# ... or force ignoredups and ignorespace
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# set history length, save history to a file, and remember times for each
# history entry
HISTSIZE=1000
HISTFILE=~/.bash_history
HISTFILESIZE=1000
HISTTIMEFORMAT='%x %X '
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
screen*)
PS1="\[\e_${debian_chroot:+($debian_chroot)}\u@\h: \w\e\\\\\]$PS1"
;;
*)
;;
esac
# Enable color support in ls if the shell is on a valid terminal.
case "$TERM" in
""|dumb)
;;
*)
# GNU ls and dircolors are both part of coreutils, prefer this option.
# Fall back to colorls for *BSD.
if [ -x /usr/bin/dircolors ]; then
- if [ -r ~/.dircolors ]; then
+ case "$TERM" in
+ *256col*) fn=~/.dircolors-256color ;;
+ *) fn=~/.dircolors ;;
+ esac
+ if [ "$TMUX" ]; then
+ fn=~/.dircolors-256color
+ fi
+ if [ ! -r $fn ]; then
+ fn=~/.dircolors
+ fi
+ if [ -r $fn ]; then
# be backwards-compatible: attempt to detect newer keywords not
# understood by the available version of dircolors and filter
# them out
- errs=$(dircolors -b ~/.dircolors 2>&1 > /dev/null)
+ errs=$(dircolors -b $fn 2>&1 > /dev/null)
bad=$(echo "$errs" | sed -n 's/^.*: unrecognized keyword \(.*\)$/\1/p')
if [ "$bad" ]; then
fix='grep -F -v "$bad"'
# special cases:
# - if dircolors doesn't know RESET, use NORMAL and FILE
# - if dircolors doesn't know OTHER_WRITABLE, remove SET[GU]ID
for word in $bad; do
case "$word" in
RESET) fix="sed 's/^RESET.*$/NORMAL 00\nFILE 00/' | $fix" ;;
*OTHER*) fix="grep -v 'SET[GU]ID' | $fix" ;;
esac
done
- eval "$(cat ~/.dircolors | eval $fix | dircolors -b -)"
+ eval "$(cat $fn | eval $fix | dircolors -b -)"
else
- eval "$(dircolors -b ~/.dircolors)"
+ eval "$(dircolors -b $fn)"
fi
unset bad errs fix word
else
eval "$(dircolors -b)"
fi
+ unset fn
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
elif type colorls > /dev/null 2>&1; then
alias ls='colorls -G'
fi
;;
esac
# Define command aliases to invoke the preferred editor and pager utilities.
# Use the sensible-utils commands if on Debian; otherwise, use the values of
# standard variables.
if type sensible-editor > /dev/null 2>&1; then
alias editor=sensible-editor
alias e=sensible-editor
alias v=sensible-editor
elif [ -n "${VISUAL:-$EDITOR}" ]; then
alias editor="${VISUAL:-$EDITOR}"
alias e="${VISUAL:-$EDITOR}"
alias v="${VISUAL:-$EDITOR}"
fi
if type sensible-pager > /dev/null 2>&1; then
alias pager=sensible-pager
elif [ -n "$PAGER" ]; then
alias pager="$PAGER"
fi
# Compensate for Red Hat installing the most featureful Vim under a
# different name.
if type vimx > /dev/null 2>&1; then
alias vim=vimx
fi
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
# enable programmable completion from ~/.bash_completion (needed for some
# systems where system-wide bash-completion is not installed).
if [ -f ~/.bash_completion ] && ! shopt -oq posix; then
. ~/.bash_completion
fi
diff --git a/dircolors-256color b/dircolors-256color
new file mode 100644
index 0000000..9b7da0f
--- /dev/null
+++ b/dircolors-256color
@@ -0,0 +1,179 @@
+# Configuration file for dircolors, a utility to help you set the
+# LS_COLORS environment variable used by GNU ls with the --color option.
+
+# Copyright (C) 1996-2015 Free Software Foundation, Inc.
+# Copying and distribution of this file, with or without modification,
+# are permitted provided the copyright notice and this notice are preserved.
+
+# Modified for 256-color terminals.
+
+# Below, there should be one TERM entry for each termtype that is colorizable
+TERM gnome-256color
+TERM putty-256color
+TERM rxvt-256color
+TERM rxvt-unicode-256color
+TERM rxvt-unicode256
+TERM screen-256color
+TERM screen-256color-bce
+TERM st-256color
+TERM xterm-256color
+
+# Below are the color init strings for the basic file types. A color init
+# string consists of one or more of the following numeric codes:
+# Attribute codes:
+# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
+# Text color codes:
+# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
+# Background color codes:
+# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
+#NORMAL 00 # no color code at all
+#FILE 00 # regular file: use no color at all
+RESET 0 # reset to "normal" color
+DIR 38;5;111 # directory
+LINK 38;5;87 # symbolic link. (If you set this to 'target' instead of a
+ # numerical value, the color is as for the file pointed to.)
+MULTIHARDLINK 00 # regular file with more than one link
+FIFO 38;5;214 # pipe
+SOCK 38;5;139 # socket
+DOOR 38;5;139 # door
+BLK 38;5;227 # block device driver
+CHR 38;5;227 # character device driver
+ORPHAN 38;5;160 # symlink to nonexistent file, or non-stat'able file
+SETUID 38;5;232;48;5;160 # file that is setuid (u+s)
+SETGID 38;5;232;48;5;178 # file that is setgid (g+s)
+CAPABILITY 38;5;232;48;5;160 # file with capability
+STICKY_OTHER_WRITABLE 38;5;232;48;5;64 # dir that is sticky and other-writable (+t,o+w)
+OTHER_WRITABLE 38;5;55;48;5;64 # dir that is other-writable (o+w) and not sticky
+STICKY 38;5;251;48;5;25 # dir with the sticky bit set (+t) and not other-writable
+
+# This is for files with execute permission:
+EXEC 38;5;119
+
+# List any file extensions like '.gz' or '.tar' that you would like ls
+# to colorize below. Put the extension, a space, and the color init string.
+# (and any comments you want to add after a '#')
+
+# If you use DOS-style suffixes, you may want to uncomment the following:
+#.cmd 38;5;119 # executables (bright green)
+#.exe 38;5;119
+#.com 38;5;119
+#.btm 38;5;119
+#.bat 38;5;119
+# Or if you want to colorize scripts even if they do not have the
+# executable bit actually set.
+#.sh 38;5;119
+#.csh 38;5;119
+
+ # archives or compressed (bright red)
+.tar 38;5;160
+.tgz 38;5;160
+.arc 38;5;160
+.arj 38;5;160
+.taz 38;5;160
+.lha 38;5;160
+.lz4 38;5;160
+.lzh 38;5;160
+.lzma 38;5;160
+.tlz 38;5;160
+.txz 38;5;160
+.tzo 38;5;160
+.t7z 38;5;160
+.zip 38;5;160
+.z 38;5;160
+.Z 38;5;160
+.dz 38;5;160
+.gz 38;5;160
+.lrz 38;5;160
+.lz 38;5;160
+.lzo 38;5;160
+.xz 38;5;160
+.bz2 38;5;160
+.bz 38;5;160
+.tbz 38;5;160
+.tbz2 38;5;160
+.tz 38;5;160
+.deb 38;5;160
+.rpm 38;5;160
+.jar 38;5;160
+.war 38;5;160
+.ear 38;5;160
+.sar 38;5;160
+.rar 38;5;160
+.alz 38;5;160
+.ace 38;5;160
+.zoo 38;5;160
+.cpio 38;5;160
+.7z 38;5;160
+.rz 38;5;160
+.cab 38;5;160
+
+# image formats
+.jpg 38;5;139
+.jpeg 38;5;139
+.gif 38;5;139
+.bmp 38;5;139
+.pbm 38;5;139
+.pgm 38;5;139
+.ppm 38;5;139
+.tga 38;5;139
+.xbm 38;5;139
+.xpm 38;5;139
+.tif 38;5;139
+.tiff 38;5;139
+.png 38;5;139
+.svg 38;5;139
+.svgz 38;5;139
+.mng 38;5;139
+.pcx 38;5;139
+.mov 38;5;139
+.mpg 38;5;139
+.mpeg 38;5;139
+.m2v 38;5;139
+.mkv 38;5;139
+.webm 38;5;139
+.ogm 38;5;139
+.mp4 38;5;139
+.m4v 38;5;139
+.mp4v 38;5;139
+.vob 38;5;139
+.qt 38;5;139
+.nuv 38;5;139
+.wmv 38;5;139
+.asf 38;5;139
+.rm 38;5;139
+.rmvb 38;5;139
+.flc 38;5;139
+.avi 38;5;139
+.fli 38;5;139
+.flv 38;5;139
+.gl 38;5;139
+.dl 38;5;139
+.xcf 38;5;139
+.xwd 38;5;139
+.yuv 38;5;139
+.cgm 38;5;139
+.emf 38;5;139
+
+# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
+.ogv 38;5;139
+.ogx 38;5;139
+
+# audio formats
+.aac 38;5;37
+.au 38;5;37
+.flac 38;5;37
+.m4a 38;5;37
+.mid 38;5;37
+.midi 38;5;37
+.mka 38;5;37
+.mp3 38;5;37
+.mpc 38;5;37
+.ogg 38;5;37
+.ra 38;5;37
+.wav 38;5;37
+
+# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
+.oga 38;5;37
+.opus 38;5;37
+.spx 38;5;37
+.xspf 38;5;37
|
mtmiller/dotfiles
|
2e9a61a116a7f053c2ec6b414edb3571a916192f
|
Set correct background and colors for vim in tmux
|
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 94cf00c..380b2e0 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,179 +1,184 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Configure Vim NERDTree with a useful default ignore list.
let g:NERDTreeIgnore = ['\.[ao]$', '\.l[ao]$', '\.py[co]$', '\.so$', '\~$']
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
- set t_Co=16
+endif
+if &term =~ "^screen"
+ set background=dark
+ if strlen($TMUX)
+ set t_Co=256
+ endif
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
" Configure Vim cscope interface.
if has("cscope") && executable("cscope")
set csprg=cscope
set csto=0
set cst
set nocsverb
if filereadable("cscope.out")
cs add cscope.out
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
set guifont=Inconsolata\ 11,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
28d1a88f3a88d7c882bdecdb6fe01337e1f69eea
|
dircolors: Update from GNU coreutils
|
diff --git a/dircolors b/dircolors
index 0770b1a..742b6cf 100644
--- a/dircolors
+++ b/dircolors
@@ -1,209 +1,227 @@
# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option.
-# Copyright (C) 1996, 1999-2010 Free Software Foundation, Inc.
+# Copyright (C) 1996-2015 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted provided the copyright notice and this notice are preserved.
# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
# slackware version of dircolors) are recognized but ignored.
# Below, there should be one TERM entry for each termtype that is colorizable
TERM Eterm
TERM ansi
TERM color-xterm
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28
TERM con80x30
TERM con80x43
TERM con80x50
TERM con80x60
TERM cons25
TERM console
TERM cygwin
TERM dtterm
TERM eterm-color
TERM gnome
TERM gnome-256color
+TERM hurd
TERM jfbterm
TERM konsole
TERM kterm
TERM linux
TERM linux-c
TERM mach-color
+TERM mach-gnu-color
TERM mlterm
TERM putty
+TERM putty-256color
TERM rxvt
TERM rxvt-256color
TERM rxvt-cygwin
TERM rxvt-cygwin-native
TERM rxvt-unicode
TERM rxvt-unicode-256color
TERM rxvt-unicode256
TERM screen
TERM screen-256color
TERM screen-256color-bce
TERM screen-bce
TERM screen-w
+TERM screen.Eterm
TERM screen.rxvt
TERM screen.linux
+TERM st
+TERM st-256color
TERM terminator
TERM vt100
TERM xterm
TERM xterm-16color
TERM xterm-256color
TERM xterm-88color
TERM xterm-color
TERM xterm-debian
# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#NORMAL 00 # no color code at all
#FILE 00 # regular file: use no color at all
RESET 0 # reset to "normal" color
DIR 01;34 # directory
LINK 01;36 # symbolic link. (If you set this to 'target' instead of a
# numerical value, the color is as for the file pointed to.)
MULTIHARDLINK 00 # regular file with more than one link
FIFO 40;33 # pipe
SOCK 01;35 # socket
DOOR 01;35 # door
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file
SETUID 37;41 # file that is setuid (u+s)
SETGID 30;43 # file that is setgid (g+s)
CAPABILITY 30;41 # file with capability
STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
# This is for files with execute permission:
EXEC 01;32
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
# If you use DOS-style suffixes, you may want to uncomment the following:
#.cmd 01;32 # executables (bright green)
#.exe 01;32
#.com 01;32
#.btm 01;32
#.bat 01;32
# Or if you want to colorize scripts even if they do not have the
# executable bit actually set.
#.sh 01;32
#.csh 01;32
# archives or compressed (bright red)
.tar 01;31
.tgz 01;31
+.arc 01;31
.arj 01;31
.taz 01;31
+.lha 01;31
+.lz4 01;31
.lzh 01;31
.lzma 01;31
.tlz 01;31
.txz 01;31
+.tzo 01;31
+.t7z 01;31
.zip 01;31
.z 01;31
.Z 01;31
.dz 01;31
.gz 01;31
+.lrz 01;31
.lz 01;31
+.lzo 01;31
.xz 01;31
.bz2 01;31
.bz 01;31
.tbz 01;31
.tbz2 01;31
.tz 01;31
.deb 01;31
.rpm 01;31
.jar 01;31
+.war 01;31
+.ear 01;31
+.sar 01;31
.rar 01;31
+.alz 01;31
.ace 01;31
.zoo 01;31
.cpio 01;31
.7z 01;31
.rz 01;31
+.cab 01;31
# image formats
.jpg 01;35
.jpeg 01;35
.gif 01;35
.bmp 01;35
.pbm 01;35
.pgm 01;35
.ppm 01;35
.tga 01;35
.xbm 01;35
.xpm 01;35
.tif 01;35
.tiff 01;35
.png 01;35
.svg 01;35
.svgz 01;35
.mng 01;35
.pcx 01;35
.mov 01;35
.mpg 01;35
.mpeg 01;35
.m2v 01;35
.mkv 01;35
+.webm 01;35
.ogm 01;35
.mp4 01;35
.m4v 01;35
.mp4v 01;35
.vob 01;35
.qt 01;35
.nuv 01;35
.wmv 01;35
.asf 01;35
.rm 01;35
.rmvb 01;35
.flc 01;35
.avi 01;35
.fli 01;35
.flv 01;35
.gl 01;35
.dl 01;35
.xcf 01;35
.xwd 01;35
.yuv 01;35
.cgm 01;35
.emf 01;35
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
-.axv 01;35
-.anx 01;35
.ogv 01;35
.ogx 01;35
# audio formats
.aac 00;36
.au 00;36
.flac 00;36
+.m4a 00;36
.mid 00;36
.midi 00;36
.mka 00;36
.mp3 00;36
.mpc 00;36
.ogg 00;36
.ra 00;36
.wav 00;36
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
-.axa 00;36
.oga 00;36
+.opus 00;36
.spx 00;36
.xspf 00;36
|
mtmiller/dotfiles
|
5f5424fd08cfa4880af89385f58f26acaa3ca259
|
shrc: Upgrade terminals with TERM=xterm -> xterm-256color
|
diff --git a/shrc b/shrc
index 98ef9f0..0daa95f 100644
--- a/shrc
+++ b/shrc
@@ -1,141 +1,150 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in chromium chromium-browser google-chrome firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
-# Apply my preferred terminal control modes on known terminal types.
if tty > /dev/null 2>&1; then
+
+ # Apply my preferred terminal control modes on known terminal types.
case "$TERM" in
linux|rxvt*|screen*|xterm*)
for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
stty $mode > /dev/null 2>&1
done
+ unset mode
;;
esac
+
+ # Upgrade xterm -> xterm-256color, all modern terminals support 256 colors.
+ if [ X"$TERM" = Xxterm ]; then
+ TERM=xterm-256color
+ export TERM
+ fi
+
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
d8e34018a6e2deff959ebb7d49abd422b6ca4e3f
|
byobu: Adapt tmux configuration for byobu
|
diff --git a/Makefile.am b/Makefile.am
index 2b93813..958ddc7 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,107 +1,108 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/bazaar.conf \
bazaar/ignore \
+ byobu/.tmux.conf \
caff/gnupghome/gpg.conf \
colordiffrc \
config/git/ignore \
cshrc \
cvsignore \
cvsrc \
devscripts \
dircolors \
emacs \
gbp.conf \
gdbinit \
gitconfig \
hgignore \
hgrc \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/byobu/.tmux.conf b/byobu/.tmux.conf
new file mode 100644
index 0000000..7c47e5b
--- /dev/null
+++ b/byobu/.tmux.conf
@@ -0,0 +1,16 @@
+set-window-option -g aggressive-resize on
+set-window-option -g mode-mouse on
+set-window-option -g monitor-activity on
+set-window-option -g xterm-keys on
+
+set-option -g history-limit 10000
+
+set-option -g mouse-resize-pane on
+set-option -g mouse-select-pane on
+set-option -g mouse-select-window on
+
+set-option -g status-interval 1
+set-option -g status-left "#(byobu-status tmux_left)"
+set-option -g status-right "#(byobu-status tmux_right)%Y-%m-%d %H:%M:%S"
+
+set-option -g terminal-overrides "*256col*:colors=256,xterm*:XT:Ms=\\E]52;%p1%s;%p2%s\\007:Cs=\\E]12;%p1%s\\007:Cr=\\E]112\\007:Ss=\\E[%p1%d q:Se=\\E[2 q,screen*:XT"
|
mtmiller/dotfiles
|
f0b1497e9d6b1e914b6c35f964e879a88c82ecca
|
tmux: Add terminal overrides, go back to 24-hour clock
|
diff --git a/tmux.conf b/tmux.conf
index 2e25c9e..8d37eee 100644
--- a/tmux.conf
+++ b/tmux.conf
@@ -1,14 +1,16 @@
set-window-option -g aggressive-resize on
set-window-option -g mode-mouse on
set-window-option -g monitor-activity on
set-window-option -g xterm-keys on
set-option -g history-limit 10000
set-option -g mouse-resize-pane on
set-option -g mouse-select-pane on
set-option -g mouse-select-window on
set-option -g status-interval 1
set-option -g status-left "[#S]"
-set-option -g status-right "%Y-%m-%d %r"
+set-option -g status-right "%Y-%m-%d %H:%M:%S"
+
+set-option -g terminal-overrides "*256col*:colors=256,xterm*:XT:Ms=\\E]52;%p1%s;%p2%s\\007:Cs=\\E]12;%p1%s\\007:Cr=\\E]112\\007:Ss=\\E[%p1%d q:Se=\\E[2 q,screen*:XT"
|
mtmiller/dotfiles
|
d9bf5151cd992c0a5deb2eb611a0c00369b2ada4
|
shrc: Apply terminal control mode preferences
|
diff --git a/shrc b/shrc
index cb47cb2..98ef9f0 100644
--- a/shrc
+++ b/shrc
@@ -1,130 +1,141 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in chromium chromium-browser google-chrome firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
+# Apply my preferred terminal control modes on known terminal types.
+if tty > /dev/null 2>&1; then
+ case "$TERM" in
+ linux|rxvt*|screen*|xterm*)
+ for mode in sane -brkint -imaxbel iutf8 -ixany -ixoff -ixon; do
+ stty $mode > /dev/null 2>&1
+ done
+ ;;
+ esac
+fi
+
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
74174143e5b05ef065de3cb2a0da508f15dcdc78
|
hgrc: add more aliases, extensions, and default options
|
diff --git a/hgrc b/hgrc
index d331bef..d2cb661 100644
--- a/hgrc
+++ b/hgrc
@@ -1,23 +1,35 @@
[alias]
-describe = log -r . --template '{latesttag}-{latesttagdistance}-{node|short}\n'
+describe = log --rev . --template '{latesttag}-{latesttagdistance}-{node|short}\n'
+gc = strip --hidden --rev 'extinct()'
+grepdir = !$HG manifest | tr '\n' '\0' | xargs -0 grep --color=auto -E -- $@
+
+[defaults]
+log = -v
[diff]
git = True
showfunc = True
[extensions]
+churn =
color =
convert =
graphlog =
hgk =
hgview =
histedit =
+largefiles =
mq =
pager =
progress =
purge =
rebase =
record =
+shelve =
+
+[pager]
+attend = annotate, cat, diff, export, glog, help, incoming, log, outgoing, \
+ qdiff, status, tags
[ui]
ignore = ~/.hgignore
|
mtmiller/dotfiles
|
e9bef10e9e4dfc57f3b4cf023535f2a7c1a03eee
|
Add bzr, git, and hg configurations
|
diff --git a/Makefile.am b/Makefile.am
index e867223..2b93813 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,104 +1,107 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
+ bazaar/bazaar.conf \
bazaar/ignore \
caff/gnupghome/gpg.conf \
colordiffrc \
+ config/git/ignore \
cshrc \
cvsignore \
cvsrc \
devscripts \
dircolors \
emacs \
gbp.conf \
gdbinit \
- gitignore \
+ gitconfig \
hgignore \
+ hgrc \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/bazaar/bazaar.conf b/bazaar/bazaar.conf
new file mode 100644
index 0000000..db4574b
--- /dev/null
+++ b/bazaar/bazaar.conf
@@ -0,0 +1 @@
+[DEFAULT]
diff --git a/gitignore b/config/git/ignore
similarity index 100%
rename from gitignore
rename to config/git/ignore
diff --git a/gitconfig b/gitconfig
new file mode 100644
index 0000000..f1bf0f2
--- /dev/null
+++ b/gitconfig
@@ -0,0 +1,6 @@
+[color]
+ ui = auto
+[core]
+ excludesfile = ~/.config/git/ignore
+[web]
+ browser = chromium
diff --git a/hgrc b/hgrc
new file mode 100644
index 0000000..d331bef
--- /dev/null
+++ b/hgrc
@@ -0,0 +1,23 @@
+[alias]
+describe = log -r . --template '{latesttag}-{latesttagdistance}-{node|short}\n'
+
+[diff]
+git = True
+showfunc = True
+
+[extensions]
+color =
+convert =
+graphlog =
+hgk =
+hgview =
+histedit =
+mq =
+pager =
+progress =
+purge =
+rebase =
+record =
+
+[ui]
+ignore = ~/.hgignore
|
mtmiller/dotfiles
|
03c1f0ae89a13610ca1415e44f74f3e3b6153274
|
Add gdb configuration
|
diff --git a/Makefile.am b/Makefile.am
index a56f783..e867223 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,103 +1,104 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
caff/gnupghome/gpg.conf \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
devscripts \
dircolors \
emacs \
gbp.conf \
+ gdbinit \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/gdbinit b/gdbinit
new file mode 100644
index 0000000..e8e47b6
--- /dev/null
+++ b/gdbinit
@@ -0,0 +1,2 @@
+set history file ~/.gdb_history
+set history save on
|
mtmiller/dotfiles
|
cf16b684a97dc55449204ac3fd7bd17125ea1d7d
|
Add Debian devscripts configuration
|
diff --git a/Makefile.am b/Makefile.am
index 68719da..a56f783 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,102 +1,103 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
caff/gnupghome/gpg.conf \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
+ devscripts \
dircolors \
emacs \
gbp.conf \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/devscripts b/devscripts
new file mode 100644
index 0000000..3f6cf01
--- /dev/null
+++ b/devscripts
@@ -0,0 +1,11 @@
+# Default settings for bts(1)
+BTS_CACHE_MODE=mbox
+
+# Default settings for debchange(1)
+DEBCHANGE_RELEASE_HEURISTIC=changelog
+DEBCHANGE_MULTIMAINT=yes
+DEBCHANGE_MULTIMAINT_MERGE=yes
+
+# Default settings for debuild(1)
+DEBUILD_LINTIAN=yes
+DEBUILD_LINTIAN_OPTS="-IE --pedantic --color=auto"
|
mtmiller/dotfiles
|
b909a5af743387f8202d9b134165a5644389782a
|
Add sensible GnuPG configuration for caff
|
diff --git a/Makefile.am b/Makefile.am
index 7f0fb88..68719da 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,101 +1,102 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
+ caff/gnupghome/gpg.conf \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gbp.conf \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/caff/gnupghome/gpg.conf b/caff/gnupghome/gpg.conf
new file mode 100644
index 0000000..ca26c22
--- /dev/null
+++ b/caff/gnupghome/gpg.conf
@@ -0,0 +1,5 @@
+ask-cert-level
+photo-viewer "eog %i"
+personal-digest-preferences SHA256
+cert-digest-algo SHA256
+default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed
|
mtmiller/dotfiles
|
5cb277d360f413b930c2377b905b07e5cc180fa0
|
Add git-buildpackage configuration
|
diff --git a/Makefile.am b/Makefile.am
index f12ee92..7f0fb88 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,100 +1,101 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
+ gbp.conf \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/gbp.conf b/gbp.conf
new file mode 100644
index 0000000..cec628c
--- /dev/null
+++ b/gbp.conf
@@ -0,0 +1,2 @@
+[DEFAULT]
+pristine-tar = True
|
mtmiller/dotfiles
|
59175b71860e4752953005faa995834ff8a8ab63
|
Add mk-sbuild configuration
|
diff --git a/Makefile.am b/Makefile.am
index 8c06b0d..f12ee92 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,99 +1,100 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
+ mk-sbuild.rc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/mk-sbuild.rc b/mk-sbuild.rc
new file mode 100644
index 0000000..1c35ae8
--- /dev/null
+++ b/mk-sbuild.rc
@@ -0,0 +1,35 @@
+# ~/.mk-sbuild.rc
+
+# Override the sbuild chroot naming convention
+CHROOT_NAME="${name}-${CHROOT_ARCH}-sbuild"
+
+# Override the sbuild synonym naming convention as well
+if [ -z "$synonym" ]; then
+ CHROOT_SYNONYM=""
+else
+ CHROOT_SYNONYM="${synonym}-${CHROOT_ARCH}-sbuild"
+fi
+
+# Set the URL to install from
+case "$DISTRO" in
+ubuntu)
+ case "$CHROOT_ARCH" in
+ amd64 | i386)
+ DEBOOTSTRAP_MIRROR="http://archive.ubuntu.com/ubuntu"
+ ;;
+ armhf | armel | hppa | ia64 | lpia | sparc)
+ DEBOOTSTRAP_MIRROR="http://ports.ubuntu.com/ubuntu-ports"
+ ;;
+ powerpc)
+ if [ "$RELEASE" != "dapper" ]; then
+ DEBOOTSTRAP_MIRROR="http://ports.ubuntu.com/ubuntu-ports"
+ else
+ DEBOOTSTRAP_MIRROR="http://archive.ubuntu.com/ubuntu"
+ fi
+ ;;
+ esac
+ ;;
+debian)
+ DEBOOTSTRAP_MIRROR="http://ftp.us.debian.org/debian"
+ ;;
+esac
|
mtmiller/dotfiles
|
7576c1c4499696c1e1754f8b473fe169914126b5
|
Add sbuild configuration
|
diff --git a/Makefile.am b/Makefile.am
index 7aeb9e9..8c06b0d 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,98 +1,99 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
+ sbuildrc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/sbuildrc b/sbuildrc
new file mode 100644
index 0000000..52ad832
--- /dev/null
+++ b/sbuildrc
@@ -0,0 +1,10 @@
+# ~/.sbuildrc
+
+# Run lintian after successful builds.
+$run_lintian = 1;
+
+# Options to pass to lintian. Each option is a separate arrayref element.
+$lintian_opts = ['-I', '-E', '--pedantic', '--color=auto'];
+
+# don't remove this, Perl needs it:
+1;
|
mtmiller/dotfiles
|
94c9ed76838e5718db792f8e0c3a27436f1898d7
|
Add initial tmux configuration
|
diff --git a/Makefile.am b/Makefile.am
index 4fc27a6..7aeb9e9 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,97 +1,98 @@
NULL =
homedir = $(prefix)
dotfiles = \
Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
+ tmux.conf \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/tmux.conf b/tmux.conf
new file mode 100644
index 0000000..2e25c9e
--- /dev/null
+++ b/tmux.conf
@@ -0,0 +1,14 @@
+set-window-option -g aggressive-resize on
+set-window-option -g mode-mouse on
+set-window-option -g monitor-activity on
+set-window-option -g xterm-keys on
+
+set-option -g history-limit 10000
+
+set-option -g mouse-resize-pane on
+set-option -g mouse-select-pane on
+set-option -g mouse-select-window on
+
+set-option -g status-interval 1
+set-option -g status-left "[#S]"
+set-option -g status-right "%Y-%m-%d %r"
|
mtmiller/dotfiles
|
de6fde5e3c4562d24467d073b197bdb898eaa1d3
|
Add colors and fonts for X clients
|
diff --git a/Makefile.am b/Makefile.am
index af57b13..4fc27a6 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,96 +1,97 @@
NULL =
homedir = $(prefix)
dotfiles = \
+ Xresources \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
@$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
diff --git a/Xresources b/Xresources
new file mode 100644
index 0000000..b212e96
--- /dev/null
+++ b/Xresources
@@ -0,0 +1,68 @@
+emacs.font: Inconsolata-11
+Rxvt.background: #000000
+Rxvt.foreground: #d3d7cf
+Rxvt.color0: #000000
+Rxvt.color1: #cc0000
+Rxvt.color2: #4e9a06
+Rxvt.color3: #c4a000
+Rxvt.color4: #3465a4
+Rxvt.color5: #75507b
+Rxvt.color6: #06989a
+Rxvt.color7: #d3d7cf
+Rxvt.color8: #555753
+Rxvt.color9: #ef2929
+Rxvt.color10: #8ae234
+Rxvt.color11: #fce94f
+Rxvt.color12: #729fcf
+Rxvt.color13: #ad7fa8
+Rxvt.color14: #34e2e2
+Rxvt.color15: #eeeeec
+Rxvt.font: 7x14
+URxvt.font: xft:Inconsolata:pixelsize=14
+URxvt.letterSpace: -1
+UXTerm.background: #000000
+UXterm.foreground: #d3d7cf
+UXTerm.vt100.background: #000000
+UXTerm.vt100.foreground: #d3d7cf
+UXTerm.vt100.color0: #000000
+UXTerm.vt100.color1: #cc0000
+UXTerm.vt100.color2: #4e9a06
+UXTerm.vt100.color3: #c4a000
+UXTerm.vt100.color4: #3465a4
+UXTerm.vt100.color5: #75507b
+UXTerm.vt100.color6: #06989a
+UXTerm.vt100.color7: #d3d7cf
+UXTerm.vt100.color8: #555753
+UXTerm.vt100.color9: #ef2929
+UXTerm.vt100.color10: #8ae234
+UXTerm.vt100.color11: #fce94f
+UXTerm.vt100.color12: #729fcf
+UXTerm.vt100.color13: #ad7fa8
+UXTerm.vt100.color14: #34e2e2
+UXTerm.vt100.color15: #eeeeec
+UXTerm.vt100.font: 7x14
+UXTerm.vt100.faceName: Inconsolata
+UXTerm.vt100.faceSize: 11
+XTerm.background: #000000
+XTerm.foreground: #d3d7cf
+XTerm.vt100.background: #000000
+XTerm.vt100.foreground: #d3d7cf
+XTerm.vt100.color0: #000000
+XTerm.vt100.color1: #cc0000
+XTerm.vt100.color2: #4e9a06
+XTerm.vt100.color3: #c4a000
+XTerm.vt100.color4: #3465a4
+XTerm.vt100.color5: #75507b
+XTerm.vt100.color6: #06989a
+XTerm.vt100.color7: #d3d7cf
+XTerm.vt100.color8: #555753
+XTerm.vt100.color9: #ef2929
+XTerm.vt100.color10: #8ae234
+XTerm.vt100.color11: #fce94f
+XTerm.vt100.color12: #729fcf
+XTerm.vt100.color13: #ad7fa8
+XTerm.vt100.color14: #34e2e2
+XTerm.vt100.color15: #eeeeec
+XTerm.vt100.font: 7x14
+XTerm.vt100.faceName: Inconsolata
+XTerm.vt100.faceSize: 11
|
mtmiller/dotfiles
|
1ff3885fce6689376ed828a78d666957fdf3d91f
|
octave: make backwards compatible with Octave 3.2
|
diff --git a/octaverc b/octaverc
index 4ff781f..0bc78cb 100644
--- a/octaverc
+++ b/octaverc
@@ -1,61 +1,65 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("octave:\\#> ");
elseif (regexp (getenv ("TERM"), "^(rxvt|xterm)"))
PS1 (["\\[\\033]0;" term_title "\\007\\033[32m\\]octave:\\#>\\[\\033[00m\\] "]);
else
PS1 ("octave:\\#> ");
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
-history_control ("ignoreboth");
+if (exist ("history_control") == 5)
+ history_control ("ignoreboth");
+endif
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
if (exist (history_file ()))
history ("-r", history_file ());
endif
# Set up plotting preferences, but only if we're graphical.
if (getenv ("DISPLAY"))
# Use Qt or FLTK for plotting by default if available.
- if (any (cell2mat (strfind (available_graphics_toolkits (), "qt"))))
- graphics_toolkit ("qt");
- elseif (any (cell2mat (strfind (available_graphics_toolkits (), "fltk"))))
- graphics_toolkit ("fltk");
- elseif (any (cell2mat (strfind (available_graphics_toolkits (), "gnuplot"))))
- graphics_toolkit ("gnuplot");
+ if (exist ("available_graphics_toolkits") == 5)
+ if (any (cell2mat (strfind (available_graphics_toolkits (), "qt"))))
+ graphics_toolkit ("qt");
+ elseif (any (cell2mat (strfind (available_graphics_toolkits (), "fltk"))))
+ graphics_toolkit ("fltk");
+ elseif (any (cell2mat (strfind (available_graphics_toolkits (), "gnuplot"))))
+ graphics_toolkit ("gnuplot");
+ endif
endif
# Choose Gnuplot terminal based on available.
- [~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
+ [status, s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
- clear s
+ clear s status
endif
|
mtmiller/dotfiles
|
f29917490a9ba3137d2785cc27d6e9a85fcfb90c
|
octave: select the best available plotting toolkit
|
diff --git a/octaverc b/octaverc
index bea1738..4ff781f 100644
--- a/octaverc
+++ b/octaverc
@@ -1,55 +1,61 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("octave:\\#> ");
elseif (regexp (getenv ("TERM"), "^(rxvt|xterm)"))
PS1 (["\\[\\033]0;" term_title "\\007\\033[32m\\]octave:\\#>\\[\\033[00m\\] "]);
else
PS1 ("octave:\\#> ");
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
if (exist (history_file ()))
history ("-r", history_file ());
endif
# Set up plotting preferences, but only if we're graphical.
if (getenv ("DISPLAY"))
- # Use FLTK for plotting by default.
- graphics_toolkit ("fltk");
+ # Use Qt or FLTK for plotting by default if available.
+ if (any (cell2mat (strfind (available_graphics_toolkits (), "qt"))))
+ graphics_toolkit ("qt");
+ elseif (any (cell2mat (strfind (available_graphics_toolkits (), "fltk"))))
+ graphics_toolkit ("fltk");
+ elseif (any (cell2mat (strfind (available_graphics_toolkits (), "gnuplot"))))
+ graphics_toolkit ("gnuplot");
+ endif
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
endif
|
mtmiller/dotfiles
|
2fcb5b8fbd3d835b12ba0a45edb407c931bfcf30
|
Set default editor font to Inconsolata 11
|
diff --git a/emacs b/emacs
index 44b78ea..a3f83d6 100644
--- a/emacs
+++ b/emacs
@@ -1,14 +1,16 @@
;; ~/.emacs
(when (fboundp 'blink-cursor-mode)
(blink-cursor-mode 0))
(dolist (fn '(global-font-lock-mode show-paren-mode transient-mark-mode))
(when (fboundp fn)
(funcall fn t)))
(custom-set-variables
'(diff-switches "-u")
'(frame-title-format (concat "%b - " (invocation-name) "@" (system-name)))
'(require-final-newline 'query)
'(ring-bell-function 'ignore)
'(scroll-bar-mode 'right))
+
+(add-to-list 'default-frame-alist '(font . "Inconsolata-11"))
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 5c62c63..94cf00c 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,179 +1,179 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Configure Vim NERDTree with a useful default ignore list.
let g:NERDTreeIgnore = ['\.[ao]$', '\.l[ao]$', '\.py[co]$', '\.so$', '\~$']
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
set t_Co=16
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
" Configure Vim cscope interface.
if has("cscope") && executable("cscope")
set csprg=cscope
set csto=0
set cst
set nocsverb
if filereadable("cscope.out")
cs add cscope.out
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
- set guifont=Inconsolata\ 12,Liberation\ Mono\ 10,Monospace\ 10
+ set guifont=Inconsolata\ 11,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
8bcdb3887a2ea0b580832445f8f976f8b42d230c
|
ipython: don't pollute the default namespace with pylab
|
diff --git a/ipython/profile_default/ipython_config.py b/ipython/profile_default/ipython_config.py
index 081f41d..4a34f94 100644
--- a/ipython/profile_default/ipython_config.py
+++ b/ipython/profile_default/ipython_config.py
@@ -1,45 +1,46 @@
# Configuration file for ipython version >= 0.11.
import IPython
import os
import sys
def terminal_set_title(title):
"""Set the terminal title to the given string."""
term = os.getenv('TERM')
if term and term[0:5] == 'xterm':
sys.stdout.write('\033]0;' + title + '\007')
def ipython_name_version():
"""Get the name and version of IPython."""
s = "IPython"
if hasattr(IPython, '__version__'):
s += ' ' + IPython.__version__
return s
c = get_config()
c.TerminalIPythonApp.ignore_old_config = True
c.InteractiveShell.autoindent = True
c.InteractiveShell.colors = 'Linux'
c.InteractiveShell.confirm_exit = False
c.InteractiveShellApp.exec_lines = []
+c.InteractiveShellApp.pylab_import_all = False
c.AliasManager.default_aliases = []
c.AliasManager.user_aliases = []
if os.name == 'posix':
c.AliasManager.user_aliases.append(('ps', 'ps'))
if 'bsd' in sys.platform:
c.AliasManager.user_aliases.append(('ls', 'colorls -G'))
else:
c.AliasManager.user_aliases.append(('ls', 'ls --color=auto'))
terminal_set_title(ipython_name_version())
# Make ipython with python 2.x behave more like 3.x
if int(sys.version[0]) < 3:
for feature in ('division', 'print_function', 'unicode_literals'):
c.InteractiveShellApp.exec_lines.append('from __future__ import ' + feature)
|
mtmiller/dotfiles
|
1ec362439435db747f2f2f95c271416ce80586b5
|
octave: set PS1 for rxvt like xterm, and set default value
|
diff --git a/octaverc b/octaverc
index 50c76cf..bea1738 100644
--- a/octaverc
+++ b/octaverc
@@ -1,53 +1,55 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("octave:\\#> ");
-elseif (regexp (getenv ("TERM"), "^xterm"))
+elseif (regexp (getenv ("TERM"), "^(rxvt|xterm)"))
PS1 (["\\[\\033]0;" term_title "\\007\\033[32m\\]octave:\\#>\\[\\033[00m\\] "]);
+else
+ PS1 ("octave:\\#> ");
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
if (exist (history_file ()))
history ("-r", history_file ());
endif
# Set up plotting preferences, but only if we're graphical.
if (getenv ("DISPLAY"))
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
endif
|
mtmiller/dotfiles
|
ce4bf9063bb3f31b54df55dfcf8a26fbae451b69
|
octave: use "octave" in PS1, add color
|
diff --git a/octaverc b/octaverc
index d5c454b..50c76cf 100644
--- a/octaverc
+++ b/octaverc
@@ -1,53 +1,53 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
- PS1 ("\\s:\\#> ");
+ PS1 ("octave:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
- PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
+ PS1 (["\\[\\033]0;" term_title "\\007\\033[32m\\]octave:\\#>\\[\\033[00m\\] "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
if (exist (history_file ()))
history ("-r", history_file ());
endif
# Set up plotting preferences, but only if we're graphical.
if (getenv ("DISPLAY"))
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
endif
|
mtmiller/dotfiles
|
c3bb01d00cf2a42c8ce7ff12e999b4325f0cce39
|
inputrc: add rxvt-compatible key bindings
|
diff --git a/inputrc b/inputrc
index 2773afa..9ed85d7 100644
--- a/inputrc
+++ b/inputrc
@@ -1,65 +1,73 @@
# ~/.inputrc - user configuration for readline
# No terminal bell on completion
set bell-style none
# Be 8 bit clean
set input-meta on
set output-meta on
set convert-meta off
set byte-oriented off
# Trailing slash on directories and symlinks to directories
set mark-directories on
set mark-symlinked-directories on
# Default editing and key binding mode
set editing-mode emacs
set keymap emacs
# Default key bindings are for PC keyboard on a Linux console, Xterm, or
# GNOME VTE.
# Repeat some readline defaults explicitly to prevent being overridden.
"\C-l": clear-screen
"\C-v": quoted-insert
# VT100 ANSI cursor movement
"\e[A": previous-history
"\e[B": next-history
"\e[C": forward-char
"\e[D": backward-char
# VT100 keypad application mode cursor movement
"\eOA": previous-history
"\eOB": next-history
"\eOC": forward-char
"\eOD": backward-char
# Xterm Home/End "cursor" keys in normal mode
"\e[H": beginning-of-line
"\e[F": end-of-line
# Xterm Home/End "cursor" keys in cursor application mode
"\eOH": beginning-of-line
"\eOF": end-of-line
# VT220 Find/Select -> Linux console Home/End and GNOME VTE keypad Home/End
"\e[1~": beginning-of-line
"\e[4~": end-of-line
# VT220 Insert/Delete -> PC Insert/Delete
"\e[2~": quoted-insert
"\e[3~": delete-char
# VT220 Prev/Next -> PC PageUp/PageDown
"\e[5~": beginning-of-history
"\e[6~": end-of-history
# Xterm control-modified cursor keys
"\e[1;5C": forward-word
"\e[1;5D": backward-word
# GNOME VTE control-modified cursor keys versions older than 0.15.0
"\e[5C": forward-word
"\e[5D": backward-word
+
+# rxvt control-modified cursor keys
+"\eOc": forward-word
+"\eOd": backward-word
+
+# rxvt Home/End "cursor" keys
+"\e[7~": beginning-of-line
+"\e[8~": end-of-line
|
mtmiller/dotfiles
|
a8dbcd4484767987fc722659bcbbf3e079abbbd0
|
inputrc: add some readline default bindings
|
diff --git a/inputrc b/inputrc
index 83f6c29..2773afa 100644
--- a/inputrc
+++ b/inputrc
@@ -1,61 +1,65 @@
# ~/.inputrc - user configuration for readline
# No terminal bell on completion
set bell-style none
# Be 8 bit clean
set input-meta on
set output-meta on
set convert-meta off
set byte-oriented off
# Trailing slash on directories and symlinks to directories
set mark-directories on
set mark-symlinked-directories on
# Default editing and key binding mode
set editing-mode emacs
set keymap emacs
# Default key bindings are for PC keyboard on a Linux console, Xterm, or
# GNOME VTE.
+# Repeat some readline defaults explicitly to prevent being overridden.
+"\C-l": clear-screen
+"\C-v": quoted-insert
+
# VT100 ANSI cursor movement
"\e[A": previous-history
"\e[B": next-history
"\e[C": forward-char
"\e[D": backward-char
# VT100 keypad application mode cursor movement
"\eOA": previous-history
"\eOB": next-history
"\eOC": forward-char
"\eOD": backward-char
# Xterm Home/End "cursor" keys in normal mode
"\e[H": beginning-of-line
"\e[F": end-of-line
# Xterm Home/End "cursor" keys in cursor application mode
"\eOH": beginning-of-line
"\eOF": end-of-line
# VT220 Find/Select -> Linux console Home/End and GNOME VTE keypad Home/End
"\e[1~": beginning-of-line
"\e[4~": end-of-line
# VT220 Insert/Delete -> PC Insert/Delete
"\e[2~": quoted-insert
"\e[3~": delete-char
# VT220 Prev/Next -> PC PageUp/PageDown
"\e[5~": beginning-of-history
"\e[6~": end-of-history
# Xterm control-modified cursor keys
"\e[1;5C": forward-word
"\e[1;5D": backward-word
# GNOME VTE control-modified cursor keys versions older than 0.15.0
"\e[5C": forward-word
"\e[5D": backward-word
|
mtmiller/dotfiles
|
855bf144e3e7558b7145e4f03a1d861eb9b5473d
|
octave: check for existence of history file
|
diff --git a/octaverc b/octaverc
index d23b05f..d5c454b 100644
--- a/octaverc
+++ b/octaverc
@@ -1,51 +1,53 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
-history ("-r", history_file ());
+if (exist (history_file ()))
+ history ("-r", history_file ());
+endif
# Set up plotting preferences, but only if we're graphical.
if (getenv ("DISPLAY"))
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
endif
|
mtmiller/dotfiles
|
bd688e205df4e2abded3d3995e7f73ce6a330bdd
|
octave: set plotting preferences only if $DISPLAY is set
|
diff --git a/octaverc b/octaverc
index 08b7f70..d23b05f 100644
--- a/octaverc
+++ b/octaverc
@@ -1,46 +1,51 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
if (exist ("readline_read_init_file") == 5)
readline_read_init_file ("~/.inputrc");
else
read_readline_init_file ("~/.inputrc");
endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
if (exist ("history_save") == 5)
history_save (true);
endif
history_size (1000);
history ("-r", history_file ());
-# Choose Gnuplot terminal based on available.
-[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
-if isempty (s)
- putenv ("GNUTERM", "x11");
-else
- putenv ("GNUTERM", "qt");
-endif
-clear s
+# Set up plotting preferences, but only if we're graphical.
+if (getenv ("DISPLAY"))
+
+ # Use FLTK for plotting by default.
+ graphics_toolkit ("fltk");
-# Use FLTK for plotting by default.
-graphics_toolkit ("fltk");
+ # Choose Gnuplot terminal based on available.
+ [~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
+ if isempty (s)
+ putenv ("GNUTERM", "x11");
+ else
+ putenv ("GNUTERM", "qt");
+ endif
+ clear s
+
+endif
|
mtmiller/dotfiles
|
d4780927c19229e0bd373b5976647bc8bb93fe92
|
octave: be backwards compatible with older versions
|
diff --git a/octaverc b/octaverc
index bd3a8d4..08b7f70 100644
--- a/octaverc
+++ b/octaverc
@@ -1,40 +1,46 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
-readline_read_init_file ("~/.inputrc");
+if (exist ("readline_read_init_file") == 5)
+ readline_read_init_file ("~/.inputrc");
+else
+ read_readline_init_file ("~/.inputrc");
+endif
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
-history_save (true);
+if (exist ("history_save") == 5)
+ history_save (true);
+endif
history_size (1000);
history ("-r", history_file ());
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
|
mtmiller/dotfiles
|
656ce63f2269f886a0806e34381e6065bd4aaee0
|
ipython: clean up quotes to be consistent
|
diff --git a/ipython/ipy_user_conf.py b/ipython/ipy_user_conf.py
index 3cd92a1..6a54c0f 100644
--- a/ipython/ipy_user_conf.py
+++ b/ipython/ipy_user_conf.py
@@ -1,65 +1,65 @@
# Configuration file for ipython version < 0.11.
import IPython
import IPython.ipapi
import ipy_defaults
import os
import sys
def unalias(shell, *args):
"""Remove aliases from the given IPython shell object."""
for cmd in args:
if cmd in shell.alias_table:
del shell.alias_table[cmd]
def terminal_set_title(title):
"""Set the terminal title to the given string."""
term = os.getenv('TERM')
if term and term[0:5] == 'xterm':
sys.stdout.write('\033]0;' + title + '\007')
def ipython_name_version():
"""Get the name and version of IPython."""
s = 'IPython'
if hasattr(IPython, '__version__'):
s += ' ' + IPython.__version__
return s
def import_future_feature(opts, *args):
"""Import future features into the IPython shell at startup."""
import __future__
for feature in args:
if hasattr(__future__, feature):
- opts.autoexec.append("from __future__ import " + feature)
+ opts.autoexec.append('from __future__ import ' + feature)
def main():
"""Configure IPython shell for versions < 0.11."""
ip = IPython.ipapi.get()
ip.options.autoindent = 1
ip.options.confirm_exit = 0
ip.options.pprint = 1
ip.options.separate_out = ''
unalias(ip.IP, 'lc', 'lf', 'lk', 'll', 'lx', 'ddir', 'ldir')
if os.name == 'posix':
ip.defalias('ps', 'ps')
if 'bsd' in sys.platform:
ip.defalias('ls', 'colorls -G')
else:
ip.defalias('ls', 'ls --color=auto')
terminal_set_title(ipython_name_version())
# Make ipython with python 2.x behave more like 3.x
if int(sys.version[0]) < 3:
- import_future_feature(ip.options, "division",
- "print_function",
- "unicode_literals")
+ import_future_feature(ip.options, 'division',
+ 'print_function',
+ 'unicode_literals')
main()
|
mtmiller/dotfiles
|
ba708170d8399514cd7d0b4c4ed59bd061238fd8
|
ipython: set terminal title
|
diff --git a/ipython/ipy_user_conf.py b/ipython/ipy_user_conf.py
index 7fcaaa8..3cd92a1 100644
--- a/ipython/ipy_user_conf.py
+++ b/ipython/ipy_user_conf.py
@@ -1,47 +1,65 @@
# Configuration file for ipython version < 0.11.
+import IPython
import IPython.ipapi
import ipy_defaults
import os
import sys
def unalias(shell, *args):
"""Remove aliases from the given IPython shell object."""
for cmd in args:
if cmd in shell.alias_table:
del shell.alias_table[cmd]
+def terminal_set_title(title):
+ """Set the terminal title to the given string."""
+ term = os.getenv('TERM')
+ if term and term[0:5] == 'xterm':
+ sys.stdout.write('\033]0;' + title + '\007')
+
+
+def ipython_name_version():
+ """Get the name and version of IPython."""
+ s = 'IPython'
+ if hasattr(IPython, '__version__'):
+ s += ' ' + IPython.__version__
+ return s
+
+
def import_future_feature(opts, *args):
"""Import future features into the IPython shell at startup."""
import __future__
for feature in args:
if hasattr(__future__, feature):
opts.autoexec.append("from __future__ import " + feature)
def main():
"""Configure IPython shell for versions < 0.11."""
ip = IPython.ipapi.get()
ip.options.autoindent = 1
ip.options.confirm_exit = 0
ip.options.pprint = 1
ip.options.separate_out = ''
unalias(ip.IP, 'lc', 'lf', 'lk', 'll', 'lx', 'ddir', 'ldir')
if os.name == 'posix':
ip.defalias('ps', 'ps')
if 'bsd' in sys.platform:
ip.defalias('ls', 'colorls -G')
else:
ip.defalias('ls', 'ls --color=auto')
+ terminal_set_title(ipython_name_version())
+
# Make ipython with python 2.x behave more like 3.x
if int(sys.version[0]) < 3:
import_future_feature(ip.options, "division",
"print_function",
"unicode_literals")
main()
diff --git a/ipython/profile_default/ipython_config.py b/ipython/profile_default/ipython_config.py
index f242564..081f41d 100644
--- a/ipython/profile_default/ipython_config.py
+++ b/ipython/profile_default/ipython_config.py
@@ -1,26 +1,45 @@
# Configuration file for ipython version >= 0.11.
+import IPython
import os
import sys
+
+def terminal_set_title(title):
+ """Set the terminal title to the given string."""
+ term = os.getenv('TERM')
+ if term and term[0:5] == 'xterm':
+ sys.stdout.write('\033]0;' + title + '\007')
+
+
+def ipython_name_version():
+ """Get the name and version of IPython."""
+ s = "IPython"
+ if hasattr(IPython, '__version__'):
+ s += ' ' + IPython.__version__
+ return s
+
+
c = get_config()
c.TerminalIPythonApp.ignore_old_config = True
c.InteractiveShell.autoindent = True
c.InteractiveShell.colors = 'Linux'
c.InteractiveShell.confirm_exit = False
c.InteractiveShellApp.exec_lines = []
c.AliasManager.default_aliases = []
c.AliasManager.user_aliases = []
if os.name == 'posix':
c.AliasManager.user_aliases.append(('ps', 'ps'))
if 'bsd' in sys.platform:
c.AliasManager.user_aliases.append(('ls', 'colorls -G'))
else:
c.AliasManager.user_aliases.append(('ls', 'ls --color=auto'))
+terminal_set_title(ipython_name_version())
+
# Make ipython with python 2.x behave more like 3.x
if int(sys.version[0]) < 3:
for feature in ('division', 'print_function', 'unicode_literals'):
c.InteractiveShellApp.exec_lines.append('from __future__ import ' + feature)
|
mtmiller/dotfiles
|
1dce671ac3d829780426ebf12baa22cac01bfa25
|
ipython: make ipython with python 2.x behave more like 3.x
|
diff --git a/ipython/ipy_user_conf.py b/ipython/ipy_user_conf.py
index df823fe..7fcaaa8 100644
--- a/ipython/ipy_user_conf.py
+++ b/ipython/ipy_user_conf.py
@@ -1,33 +1,47 @@
# Configuration file for ipython version < 0.11.
import IPython.ipapi
import ipy_defaults
import os
import sys
def unalias(shell, *args):
"""Remove aliases from the given IPython shell object."""
for cmd in args:
if cmd in shell.alias_table:
del shell.alias_table[cmd]
+def import_future_feature(opts, *args):
+ """Import future features into the IPython shell at startup."""
+ import __future__
+ for feature in args:
+ if hasattr(__future__, feature):
+ opts.autoexec.append("from __future__ import " + feature)
+
+
def main():
"""Configure IPython shell for versions < 0.11."""
ip = IPython.ipapi.get()
ip.options.autoindent = 1
ip.options.confirm_exit = 0
ip.options.pprint = 1
ip.options.separate_out = ''
unalias(ip.IP, 'lc', 'lf', 'lk', 'll', 'lx', 'ddir', 'ldir')
if os.name == 'posix':
ip.defalias('ps', 'ps')
if 'bsd' in sys.platform:
ip.defalias('ls', 'colorls -G')
else:
ip.defalias('ls', 'ls --color=auto')
+ # Make ipython with python 2.x behave more like 3.x
+ if int(sys.version[0]) < 3:
+ import_future_feature(ip.options, "division",
+ "print_function",
+ "unicode_literals")
+
main()
diff --git a/ipython/profile_default/ipython_config.py b/ipython/profile_default/ipython_config.py
index da6144f..f242564 100644
--- a/ipython/profile_default/ipython_config.py
+++ b/ipython/profile_default/ipython_config.py
@@ -1,20 +1,26 @@
# Configuration file for ipython version >= 0.11.
import os
import sys
c = get_config()
c.TerminalIPythonApp.ignore_old_config = True
c.InteractiveShell.autoindent = True
c.InteractiveShell.colors = 'Linux'
c.InteractiveShell.confirm_exit = False
+c.InteractiveShellApp.exec_lines = []
c.AliasManager.default_aliases = []
c.AliasManager.user_aliases = []
if os.name == 'posix':
c.AliasManager.user_aliases.append(('ps', 'ps'))
if 'bsd' in sys.platform:
c.AliasManager.user_aliases.append(('ls', 'colorls -G'))
else:
c.AliasManager.user_aliases.append(('ls', 'ls --color=auto'))
+
+# Make ipython with python 2.x behave more like 3.x
+if int(sys.version[0]) < 3:
+ for feature in ('division', 'print_function', 'unicode_literals'):
+ c.InteractiveShellApp.exec_lines.append('from __future__ import ' + feature)
|
mtmiller/dotfiles
|
dba8e3232b74e8c96f2f9eb190462260a1d6affc
|
ipython: add docstrings and pep8 cleanup
|
diff --git a/ipython/ipy_user_conf.py b/ipython/ipy_user_conf.py
index 7b982f1..df823fe 100644
--- a/ipython/ipy_user_conf.py
+++ b/ipython/ipy_user_conf.py
@@ -1,28 +1,33 @@
# Configuration file for ipython version < 0.11.
import IPython.ipapi
import ipy_defaults
import os
import sys
+
def unalias(shell, *args):
+ """Remove aliases from the given IPython shell object."""
for cmd in args:
if cmd in shell.alias_table:
del shell.alias_table[cmd]
+
def main():
+ """Configure IPython shell for versions < 0.11."""
ip = IPython.ipapi.get()
ip.options.autoindent = 1
ip.options.confirm_exit = 0
ip.options.pprint = 1
ip.options.separate_out = ''
unalias(ip.IP, 'lc', 'lf', 'lk', 'll', 'lx', 'ddir', 'ldir')
if os.name == 'posix':
ip.defalias('ps', 'ps')
if 'bsd' in sys.platform:
ip.defalias('ls', 'colorls -G')
else:
ip.defalias('ls', 'ls --color=auto')
+
main()
|
mtmiller/dotfiles
|
6e8c57b7448e5111c1216986325a21bedf5a5b1f
|
octave: load history after setting file name
|
diff --git a/octaverc b/octaverc
index 17e4a88..bd3a8d4 100644
--- a/octaverc
+++ b/octaverc
@@ -1,39 +1,40 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Load my ~/.inputrc to override any conflicting keybindings from Octave.
readline_read_init_file ("~/.inputrc");
# Save interpreter history with the same settings as for bash.
history_control ("ignoreboth");
history_file ("~/.octave_history");
history_save (true);
history_size (1000);
+history ("-r", history_file ());
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
|
mtmiller/dotfiles
|
efa434839c01fb05b173b6332bea8f0784b198fe
|
octave: set readline key bindings and history preferences
|
diff --git a/octaverc b/octaverc
index d0289a2..17e4a88 100644
--- a/octaverc
+++ b/octaverc
@@ -1,30 +1,39 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
+# Load my ~/.inputrc to override any conflicting keybindings from Octave.
+readline_read_init_file ("~/.inputrc");
+
+# Save interpreter history with the same settings as for bash.
+history_control ("ignoreboth");
+history_file ("~/.octave_history");
+history_save (true);
+history_size (1000);
+
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
# Use FLTK for plotting by default.
graphics_toolkit ("fltk");
|
mtmiller/dotfiles
|
2651560e836fa7c5969426014a0a35c627e8f4c8
|
octave: use FLTK by default
|
diff --git a/octaverc b/octaverc
index f5aea4b..d0289a2 100644
--- a/octaverc
+++ b/octaverc
@@ -1,27 +1,30 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
+
+# Use FLTK for plotting by default.
+graphics_toolkit ("fltk");
|
mtmiller/dotfiles
|
f395f218753ee6cc2ef92dcf4085117bb2ffba06
|
octave: don't add ~/octave to the runtime path
|
diff --git a/octaverc b/octaverc
index 646caca..f5aea4b 100644
--- a/octaverc
+++ b/octaverc
@@ -1,30 +1,27 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if (exist ("isguirunning") && isguirunning ())
PS1 ("\\s:\\#> ");
elseif (regexp (getenv ("TERM"), "^xterm"))
PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
-# Add ~/octave (and all subdirectories) to the Octave load path.
-addpath (genpath ("~/octave"));
-
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
|
mtmiller/dotfiles
|
d3fcb9aba6a6adc4dea48cc5fe1d570d64384e6a
|
vcs: add quilt metafiles to ignore lists
|
diff --git a/bazaar/ignore b/bazaar/ignore
index 03c6a5c..895cac0 100644
--- a/bazaar/ignore
+++ b/bazaar/ignore
@@ -1,8 +1,10 @@
*.[ao]
*.l[ao]
*.py[co]
*.so
*.sw[nop]
*~
.#*
+.pc
+.timestamp
[#]*#
diff --git a/cvsignore b/cvsignore
index 03c6a5c..895cac0 100644
--- a/cvsignore
+++ b/cvsignore
@@ -1,8 +1,10 @@
*.[ao]
*.l[ao]
*.py[co]
*.so
*.sw[nop]
*~
.#*
+.pc
+.timestamp
[#]*#
diff --git a/gitignore b/gitignore
index 03c6a5c..895cac0 100644
--- a/gitignore
+++ b/gitignore
@@ -1,8 +1,10 @@
*.[ao]
*.l[ao]
*.py[co]
*.so
*.sw[nop]
*~
.#*
+.pc
+.timestamp
[#]*#
diff --git a/hgignore b/hgignore
index 7fc9638..5353297 100644
--- a/hgignore
+++ b/hgignore
@@ -1,10 +1,12 @@
syntax: glob
*.[ao]
*.l[ao]
*.py[co]
*.so
*.sw[nop]
*~
.#*
+.pc
+.timestamp
[#]*#
|
mtmiller/dotfiles
|
68428528abb68e1e2ecaef5235137ca72d95ae73
|
shrc: make chromium default browser
|
diff --git a/shrc b/shrc
index d5643bf..cb47cb2 100644
--- a/shrc
+++ b/shrc
@@ -1,130 +1,130 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
- for util in google-chrome chromium-browser firefox; do
+ for util in chromium chromium-browser google-chrome firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
0d67198f9eac76b4a7f911ffb31f81018cbdec9a
|
octaverc: set PS1 for gui and terminal mode
|
diff --git a/octaverc b/octaverc
index 4ef04f3..646caca 100644
--- a/octaverc
+++ b/octaverc
@@ -1,28 +1,30 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
-if regexp (getenv ("TERM"), "^xterm")
- PS1 (["\\[\\033]0;" term_title "\\007\\]" PS1]);
+if (exist ("isguirunning") && isguirunning ())
+ PS1 ("\\s:\\#> ");
+elseif (regexp (getenv ("TERM"), "^xterm"))
+ PS1 (["\\[\\033]0;" term_title "\\007\\]\\s:\\#> "]);
end
clear term_title
# Add ~/octave (and all subdirectories) to the Octave load path.
addpath (genpath ("~/octave"));
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
clear s
|
mtmiller/dotfiles
|
24a37750e7e9845826cca32275ca38c3e74189a1
|
octaverc: clear temporary variable
|
diff --git a/octaverc b/octaverc
index 97acfda..4ef04f3 100644
--- a/octaverc
+++ b/octaverc
@@ -1,27 +1,28 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if regexp (getenv ("TERM"), "^xterm")
PS1 (["\\[\\033]0;" term_title "\\007\\]" PS1]);
end
clear term_title
# Add ~/octave (and all subdirectories) to the Octave load path.
addpath (genpath ("~/octave"));
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
# Choose Gnuplot terminal based on available.
[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
if isempty (s)
putenv ("GNUTERM", "x11");
else
putenv ("GNUTERM", "qt");
endif
+clear s
|
mtmiller/dotfiles
|
31bc33a2ef66f8e8010769e08096dc76cbf58aa6
|
Configure gnuplot terminal for Octave
|
diff --git a/octaverc b/octaverc
index 374cbf5..97acfda 100644
--- a/octaverc
+++ b/octaverc
@@ -1,19 +1,27 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
if regexp (getenv ("TERM"), "^xterm")
PS1 (["\\[\\033]0;" term_title "\\007\\]" PS1]);
end
clear term_title
# Add ~/octave (and all subdirectories) to the Octave load path.
addpath (genpath ("~/octave"));
# Set up Octave editor.
if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
+
+# Choose Gnuplot terminal based on available.
+[~,s] = system ([gnuplot_binary " -e 'set term' 2>&1 | grep '\\<qt\\> '"]);
+if isempty (s)
+ putenv ("GNUTERM", "x11");
+else
+ putenv ("GNUTERM", "qt");
+endif
|
mtmiller/dotfiles
|
a2d6064e6542bb277d5e47b55d22afd9a733db31
|
Revert "Configure Perl locale in environment"
|
diff --git a/shrc b/shrc
index 62df360..d5643bf 100644
--- a/shrc
+++ b/shrc
@@ -1,135 +1,130 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# Add standard admin binary directories to the end of PATH in order.
# Some distributions put very useful utilities into an sbin directory.
for dir in /usr/local/sbin /usr/sbin /sbin; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
-# Configure Perl locale, see perlrun(1).
-case `locale charmap 2> /dev/null` in
-UTF-8) PERL_UNICODE=SDAL; export PERL_UNICODE ;;
-esac
-
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in google-chrome chromium-browser firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
3a66b6bd88cc97ba74ffeea7e63e89bbb239984c
|
Add standard admin directories to PATH
|
diff --git a/shrc b/shrc
index 3e5f80a..62df360 100644
--- a/shrc
+++ b/shrc
@@ -1,129 +1,135 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
+# Add standard admin binary directories to the end of PATH in order.
+# Some distributions put very useful utilities into an sbin directory.
+for dir in /usr/local/sbin /usr/sbin /sbin; do
+ __list_append_uniq PATH "$dir"
+done
+
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Configure Perl locale, see perlrun(1).
case `locale charmap 2> /dev/null` in
UTF-8) PERL_UNICODE=SDAL; export PERL_UNICODE ;;
esac
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in google-chrome chromium-browser firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
5c8eda1562d5e785a66f07dd4a8982ffeb1d21f7
|
Don't overwrite less options if already set
|
diff --git a/shrc b/shrc
index f3d747d..3e5f80a 100644
--- a/shrc
+++ b/shrc
@@ -1,129 +1,129 @@
# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
# Shell environment configuration for POSIX-compliant command interpreters.
# This file is intended to be executed from within ~/.profile or another
# shell initialization file (such as ~/.bashrc).
# Set my default semi-paranoid umask before anything else
umask 027
__list_contains() {
eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}
__list_append() {
eval "$1=\${$1:+\$$1:}$2"
}
__list_prepend() {
eval "$1=$2\${$1:+:\$$1}"
}
__list_append_uniq() {
__list_contains "$@" || __list_append "$@" || :
}
__list_prepend_uniq() {
__list_contains "$@" || __list_prepend "$@" || :
}
# Add any missing standard directories to the end of PATH in order.
for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
__list_append_uniq PATH "$dir"
done
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
__list_prepend_uniq PATH "$HOME/bin"
fi
# Configure user Perl library paths.
# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
# perl Build.PL --install_base ~
cmd="use Config; use File::Spec::Functions"
cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
for dir in `perl -e "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PERL5LIB "$dir"
export PERL5LIB
fi
done
# Configure user Python library paths.
# Assume Python packages are installed as python setup.py install --prefix=~
cmd="from distutils import sysconfig"
cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
for dir in `python -c "$cmd" 2> /dev/null`; do
if [ -n "$dir" ]; then
__list_prepend_uniq PYTHONPATH "$dir"
export PYTHONPATH
fi
done
# Configure personal RubyGems environment and add bin directory to PATH.
cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
if [ -n "$ver" ]; then
GEM_HOME="$HOME/.gem/ruby/$ver"
GEM_PATH="$GEM_HOME"
export GEM_HOME GEM_PATH
fi
cmd='puts Gem.default_dir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
__list_append_uniq GEM_PATH "$dir"
export GEM_PATH
fi
cmd='puts Gem.bindir'
dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
if [ -n "$dir" ] && [ -d "$dir" ]; then
if ! __list_contains PATH "$dir"; then
# Put this directory at the front of PATH, but after ~/bin if present.
PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
fi
fi
unset cmd dir ver
# Configure Perl locale, see perlrun(1).
case `locale charmap 2> /dev/null` in
UTF-8) PERL_UNICODE=SDAL; export PERL_UNICODE ;;
esac
# Set default text editor, pager, and web browser.
for util in vimx vim vi ex ed; do
type $util > /dev/null 2>&1 && EDITOR=$util && break
done
for util in vimx vim vi; do
type $util > /dev/null 2>&1 && VISUAL=$util && break
done
for util in less more; do
type $util > /dev/null 2>&1 && PAGER=$util && break
done
if [ -n "$DISPLAY" ]; then
for util in google-chrome chromium-browser firefox; do
type $util > /dev/null 2>&1 && BROWSER=$util && break
done
fi
for util in w3m; do
type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
done
[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
[ -n "$PAGER" ] && export PAGER || unset PAGER
[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
unset util
if [ "$PAGER" = less ]; then
- LESS=iFRSX
+ LESS="${LESS:-iFRSX}"
MANPAGER='less -s'
export LESS MANPAGER
fi
if [ -n "$EDITOR" ]; then
FCEDIT="$EDITOR"
export FCEDIT
fi
if [ -r "$HOME/.shrc.local" ]; then
. "$HOME/.shrc.local"
fi
unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
|
mtmiller/dotfiles
|
a68622490d507b0a6702d812bf26e20fd4042f9a
|
Configure Vim NERDTree with a useful default ignore list
|
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index e710fdf..5c62c63 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,176 +1,179 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
+" Configure Vim NERDTree with a useful default ignore list.
+let g:NERDTreeIgnore = ['\.[ao]$', '\.l[ao]$', '\.py[co]$', '\.so$', '\~$']
+
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
set t_Co=16
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
" Configure Vim cscope interface.
if has("cscope") && executable("cscope")
set csprg=cscope
set csto=0
set cst
set nocsverb
if filereadable("cscope.out")
cs add cscope.out
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
set guifont=Inconsolata\ 12,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
bbcb60cd4ef1b2aaaf4d148f7ff30e920dd03618
|
Configure Vim to use cscope automatically
|
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 92a4fc3..e710fdf 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,162 +1,176 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
set t_Co=16
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
+" Configure Vim cscope interface.
+if has("cscope") && executable("cscope")
+ set csprg=cscope
+ set csto=0
+ set cst
+ set nocsverb
+ if filereadable("cscope.out")
+ cs add cscope.out
+ elseif $CSCOPE_DB != ""
+ cs add $CSCOPE_DB
+ endif
+ set csverb
+endif
+
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
set guifont=Inconsolata\ 12,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
9a6b49ab8a791f4995914ec85794e6540c2a643a
|
Disable 'joinspaces' in Vim by default
|
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 06b605a..92a4fc3 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,161 +1,162 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
+set nojoinspaces " do not insert two spaces after full stop
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
set t_Co=16
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
let g:filetype_m = "octave"
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
set guifont=Inconsolata\ 12,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
a5daf679fb7dfe2d876641c8695f149cb29f20b3
|
Use Vim help for keyword lookup for vim syntax
|
diff --git a/vim/after/ftplugin/vim.vim b/vim/after/ftplugin/vim.vim
index 15f64c7..06bf1f9 100644
--- a/vim/after/ftplugin/vim.vim
+++ b/vim/after/ftplugin/vim.vim
@@ -1,4 +1,8 @@
" Vim filetype plugin
" Language: Vim
call SetBufferIndentationPreferences(2, "spaces")
+
+" Use Vim internal help for keyword lookup
+setlocal keywordprg=:help
+let b:undo_ftplugin = b:undo_ftplugin . " | setl kp<"
|
mtmiller/dotfiles
|
b9f77890623286da7e17e1a03900aad7e00e605b
|
Clean up "make compare" to only show diff output
|
diff --git a/Makefile.am b/Makefile.am
index 2534949..af57b13 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,95 +1,96 @@
NULL =
homedir = $(prefix)
dotfiles = \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
.PHONY: compare
TMPINST = $(CURDIR)/tmp
compare:
- $(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install
+ @$(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install > /dev/null
@for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
+ f=`echo $$f | sed 's/^\.\///'`; \
diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
if test -n "$$diff"; then \
echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
echo "$$diff"; \
fi \
done
@rm -rf '$(TMPINST)'
|
mtmiller/dotfiles
|
a44a36008feb88775c85ef7801f65ec9921e2064
|
Add make target to display dotfiles differences
|
diff --git a/Makefile.am b/Makefile.am
index 1e17d07..2534949 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,82 +1,95 @@
NULL =
homedir = $(prefix)
dotfiles = \
bash_completion \
bash_logout \
bash_profile \
bashrc \
bazaar/ignore \
colordiffrc \
cshrc \
cvsignore \
cvsrc \
dircolors \
emacs \
gitignore \
hgignore \
inputrc \
ipython/ipy_user_conf.py \
ipython/ipythonrc \
ipython/profile_default/ipython_config.py \
irbrc \
lintianrc \
octaverc \
profile \
quiltrc \
quiltrc-dpkg \
re.pl/repl.rc \
shrc \
ssh/config \
tcsh_editing \
teclarc \
vim/after/ftplugin/c.vim \
vim/after/ftplugin/fortran.vim \
vim/after/ftplugin/perl.vim \
vim/after/ftplugin/python.vim \
vim/after/ftplugin/ruby.vim \
vim/after/ftplugin/sh.vim \
vim/after/ftplugin/vim.vim \
vim/after/syntax/m4.vim \
vim/bundle/nerdtree/doc/NERD_tree.txt \
vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
vim/bundle/nerdtree/plugin/NERD_tree.vim \
vim/bundle/vim-fugitive/doc/fugitive.txt \
vim/bundle/vim-fugitive/plugin/fugitive.vim \
vim/bundle/vim-pathogen/autoload/pathogen.vim \
vim/colors/zenburn.vim \
vim/plugin/indentprefs.vim \
vim/vimrc_normal.vim \
vimrc \
$(NULL)
# Custom install targets because automake does not support renaming on install
install-data-local: $(dotfiles)
@$(NORMAL_INSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$$dir'"; \
$(MKDIR_P) "$$dir" || exit 1; \
fi; \
for f in $$list; do \
p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
if test -n "$$p"; then \
echo " $(MKDIR_P) '$$dir/$$p'"; \
$(MKDIR_P) "$$dir/$$p" || exit 1; \
else \
p=".$$f"; \
fi; \
echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
$(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
done
uninstall-local:
@$(NORMAL_UNINSTALL)
@list='$(dotfiles)'; test -n "$(homedir)" || list=; \
dir='$(DESTDIR)$(homedir)'; \
for f in $$list; do \
echo " rm -f '$$dir/.$$f'"; \
p=".$$f"; \
rm -f "$$dir/$$p"; \
done
+
+.PHONY: compare
+TMPINST = $(CURDIR)/tmp
+compare:
+ $(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(TMPINST)' install
+ @for f in `cd $(TMPINST)$(homedir) && find . -type f -print`; do \
+ diff=`diff -u "$(TMPINST)$(homedir)/$$f" "$(homedir)/$$f" 2>/dev/null`; \
+ if test -n "$$diff"; then \
+ echo "diff -Naur $(TMPINST)$(homedir)/$$f $(homedir)/$$f"; \
+ echo "$$diff"; \
+ fi \
+ done
+ @rm -rf '$(TMPINST)'
|
mtmiller/dotfiles
|
8a4d2a6bdbde02faf96dc306e68f367dd6347082
|
Set default .m filetype in vim to be octave
|
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
index 910052c..06b605a 100644
--- a/vim/vimrc_normal.vim
+++ b/vim/vimrc_normal.vim
@@ -1,160 +1,161 @@
" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
"
" Maintainer: Mike Miller
" Original Author: Bram Moolenaar <[email protected]>
" Last Change: 2012-03-12
"
" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
" This file is sourced only for Vim normal, big, or huge.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim" || v:progname =~? "eview"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set shortmess+=I " don't display the Vim intro at startup
set laststatus=2 " always show the status line
set visualbell t_vb= " no beeping or visual bell whatsoever
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Extend the runtimepath using the pathogen plugin.
" http://github.com/tpope/vim-pathogen
let s:pluginpath = 'pathogen#'
if v:version >= 700
call {s:pluginpath}infect()
call {s:pluginpath}helptags()
endif
" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
" done initializing.
augroup vimInitCommands
au!
autocmd VimEnter *
\ if exists(":NERDTreeToggle") |
\ map <Leader>d :NERDTreeToggle<CR> |
\ endif
augroup END
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcNormal
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Prefer a dark background on terminal emulators.
if &term =~ "^xterm"
set background=dark
set t_Co=16
endif
" User customizations for syntax highlighting.
if has("syntax")
let g:is_posix = 1
if v:version < 700
let g:is_kornshell = 1
endif
let g:fortran_fixed_source = 1
let g:fortran_have_tabs = 1
+ let g:filetype_m = "octave"
endif
" Settings specific to using the GUI.
if has("gui")
" Fonts to use in gvim. Always have fallbacks, and handle each platform in
" its own special way, see :help setting-guifont.
if has("gui_gtk2")
set guifont=Inconsolata\ 12,Liberation\ Mono\ 10,Monospace\ 10
elseif has("x11")
set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
elseif has("gui_win32")
set guifont=Consolas:h10,Lucida_Console:h9,Courier_New:h9,Terminal:h9
endif
" GUI customizations. No blinking cursor, no tearoffs, no toolbar.
set guicursor=a:blinkon0
set guioptions-=tT
" The following settings must be done when the GUI starts.
augroup guiInitCommands
au!
" Load my favorite color scheme by default.
autocmd GUIEnter * colorscheme zenburn
" Override default less options for a chance of working in the GUI
" (e.g. :shell command or man page lookup)
autocmd GUIEnter * let $LESS = $LESS . 'dr'
" Turn off visual bell feedback, needs to be done after the GUI starts.
autocmd GUIEnter * set t_vb=
augroup END
endif
|
mtmiller/dotfiles
|
22cd715479d18e6036ead2d906c040f6f4ef75c8
|
Add autotools support for installing dotfiles
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..fcb6a17
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+Makefile
+Makefile.in
+aclocal.m4
+autom4te.cache
+config.*
+configure
+install-sh
+missing
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..1e17d07
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,82 @@
+NULL =
+homedir = $(prefix)
+dotfiles = \
+ bash_completion \
+ bash_logout \
+ bash_profile \
+ bashrc \
+ bazaar/ignore \
+ colordiffrc \
+ cshrc \
+ cvsignore \
+ cvsrc \
+ dircolors \
+ emacs \
+ gitignore \
+ hgignore \
+ inputrc \
+ ipython/ipy_user_conf.py \
+ ipython/ipythonrc \
+ ipython/profile_default/ipython_config.py \
+ irbrc \
+ lintianrc \
+ octaverc \
+ profile \
+ quiltrc \
+ quiltrc-dpkg \
+ re.pl/repl.rc \
+ shrc \
+ ssh/config \
+ tcsh_editing \
+ teclarc \
+ vim/after/ftplugin/c.vim \
+ vim/after/ftplugin/fortran.vim \
+ vim/after/ftplugin/perl.vim \
+ vim/after/ftplugin/python.vim \
+ vim/after/ftplugin/ruby.vim \
+ vim/after/ftplugin/sh.vim \
+ vim/after/ftplugin/vim.vim \
+ vim/after/syntax/m4.vim \
+ vim/bundle/nerdtree/doc/NERD_tree.txt \
+ vim/bundle/nerdtree/nerdtree_plugin/exec_menuitem.vim \
+ vim/bundle/nerdtree/nerdtree_plugin/fs_menu.vim \
+ vim/bundle/nerdtree/plugin/NERD_tree.vim \
+ vim/bundle/vim-fugitive/doc/fugitive.txt \
+ vim/bundle/vim-fugitive/plugin/fugitive.vim \
+ vim/bundle/vim-pathogen/autoload/pathogen.vim \
+ vim/colors/zenburn.vim \
+ vim/plugin/indentprefs.vim \
+ vim/vimrc_normal.vim \
+ vimrc \
+ $(NULL)
+
+# Custom install targets because automake does not support renaming on install
+install-data-local: $(dotfiles)
+ @$(NORMAL_INSTALL)
+ @list='$(dotfiles)'; test -n "$(homedir)" || list=; \
+ dir='$(DESTDIR)$(homedir)'; \
+ if test -n "$$list"; then \
+ echo " $(MKDIR_P) '$$dir'"; \
+ $(MKDIR_P) "$$dir" || exit 1; \
+ fi; \
+ for f in $$list; do \
+ p=`echo ".$$f" | sed 's|/*[^/]*$$||'`; \
+ if test -n "$$p"; then \
+ echo " $(MKDIR_P) '$$dir/$$p'"; \
+ $(MKDIR_P) "$$dir/$$p" || exit 1; \
+ else \
+ p=".$$f"; \
+ fi; \
+ echo " $(INSTALL_DATA) '$$f' '$$dir/$$p'"; \
+ $(INSTALL_DATA) "$$f" "$$dir/$$p" || exit 1; \
+ done
+
+uninstall-local:
+ @$(NORMAL_UNINSTALL)
+ @list='$(dotfiles)'; test -n "$(homedir)" || list=; \
+ dir='$(DESTDIR)$(homedir)'; \
+ for f in $$list; do \
+ echo " rm -f '$$dir/.$$f'"; \
+ p=".$$f"; \
+ rm -f "$$dir/$$p"; \
+ done
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..20a7a80
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,5 @@
+AC_INIT(dotfiles, 0)
+AM_INIT_AUTOMAKE(foreign)
+AC_PREFIX_DEFAULT($HOME)
+AC_CONFIG_FILES(Makefile)
+AC_OUTPUT
|
mtmiller/dotfiles
|
d2c9193f84fbe94782403525a33268b63674524c
|
Clean up octaverc style, detect gvim in PATH
|
diff --git a/octaverc b/octaverc
index d40969f..374cbf5 100644
--- a/octaverc
+++ b/octaverc
@@ -1,19 +1,19 @@
# ~/.octaverc: Octave per-user initialization file.
# If Octave is running in a known terminal emulator set the title.
term_title = ["GNU Octave " version];
-if regexp(getenv("TERM"), "^xterm")
- PS1(["\\[\\033]0;" term_title "\\007\\]" PS1]);
+if regexp (getenv ("TERM"), "^xterm")
+ PS1 (["\\[\\033]0;" term_title "\\007\\]" PS1]);
end
clear term_title
# Add ~/octave (and all subdirectories) to the Octave load path.
-addpath(genpath("~/octave"));
+addpath (genpath ("~/octave"));
# Set up Octave editor.
-if getenv("DISPLAY")
+if getenv ("DISPLAY") && file_in_path (getenv ("PATH"), "gvim")
edit editor "gvim %s"
edit mode async
else
edit mode sync
endif
|
mtmiller/dotfiles
|
0a2a817d2671ff6797a08fef2dc70cab76f5f612
|
Add strict default lintian configuration
|
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..a6069d6
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,9 @@
+[submodule "vim/bundle/nerdtree"]
+ path = vim/bundle/nerdtree
+ url = ../../scrooloose/nerdtree.git
+[submodule "vim/bundle/vim-fugitive"]
+ path = vim/bundle/vim-fugitive
+ url = ../../tpope/vim-fugitive.git
+[submodule "vim/bundle/vim-pathogen"]
+ path = vim/bundle/vim-pathogen
+ url = ../../tpope/vim-pathogen.git
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/COPYING.VIM b/COPYING.VIM
new file mode 100644
index 0000000..dd68529
--- /dev/null
+++ b/COPYING.VIM
@@ -0,0 +1,78 @@
+VIM LICENSE
+
+I) There are no restrictions on distributing unmodified copies of Vim except
+ that they must include this license text. You can also distribute
+ unmodified parts of Vim, likewise unrestricted except that they must
+ include this license text. You are also allowed to include executables
+ that you made from the unmodified Vim sources, plus your own usage
+ examples and Vim scripts.
+
+II) It is allowed to distribute a modified (or extended) version of Vim,
+ including executables and/or source code, when the following four
+ conditions are met:
+ 1) This license text must be included unmodified.
+ 2) The modified Vim must be distributed in one of the following five ways:
+ a) If you make changes to Vim yourself, you must clearly describe in
+ the distribution how to contact you. When the maintainer asks you
+ (in any way) for a copy of the modified Vim you distributed, you
+ must make your changes, including source code, available to the
+ maintainer without fee. The maintainer reserves the right to
+ include your changes in the official version of Vim. What the
+ maintainer will do with your changes and under what license they
+ will be distributed is negotiable. If there has been no negotiation
+ then this license, or a later version, also applies to your changes.
+ The current maintainer is Bram Moolenaar <[email protected]>. If this
+ changes it will be announced in appropriate places (most likely
+ vim.sf.net, www.vim.org and/or comp.editors). When it is completely
+ impossible to contact the maintainer, the obligation to send him
+ your changes ceases. Once the maintainer has confirmed that he has
+ received your changes they will not have to be sent again.
+ b) If you have received a modified Vim that was distributed as
+ mentioned under a) you are allowed to further distribute it
+ unmodified, as mentioned at I). If you make additional changes the
+ text under a) applies to those changes.
+ c) Provide all the changes, including source code, with every copy of
+ the modified Vim you distribute. This may be done in the form of a
+ context diff. You can choose what license to use for new code you
+ add. The changes and their license must not restrict others from
+ making their own changes to the official version of Vim.
+ d) When you have a modified Vim which includes changes as mentioned
+ under c), you can distribute it without the source code for the
+ changes if the following three conditions are met:
+ - The license that applies to the changes permits you to distribute
+ the changes to the Vim maintainer without fee or restriction, and
+ permits the Vim maintainer to include the changes in the official
+ version of Vim without fee or restriction.
+ - You keep the changes for at least three years after last
+ distributing the corresponding modified Vim. When the maintainer
+ or someone who you distributed the modified Vim to asks you (in
+ any way) for the changes within this period, you must make them
+ available to him.
+ - You clearly describe in the distribution how to contact you. This
+ contact information must remain valid for at least three years
+ after last distributing the corresponding modified Vim, or as long
+ as possible.
+ e) When the GNU General Public License (GPL) applies to the changes,
+ you can distribute the modified Vim under the GNU GPL version 2 or
+ any later version.
+ 3) A message must be added, at least in the output of the ":version"
+ command and in the intro screen, such that the user of the modified Vim
+ is able to see that it was modified. When distributing as mentioned
+ under 2)e) adding the message is only required for as far as this does
+ not conflict with the license used for the changes.
+ 4) The contact information as required under 2)a) and 2)d) must not be
+ removed or changed, except that the person himself can make
+ corrections.
+
+III) If you distribute a modified version of Vim, you are encouraged to use
+ the Vim license for your changes and make them available to the
+ maintainer, including the source code. The preferred way to do this is
+ by e-mail or by uploading the files to a server and e-mailing the URL.
+ If the number of changes is small (e.g., a modified Makefile) e-mailing a
+ context diff will do. The e-mail address to be used is
+ <[email protected]>
+
+IV) It is not allowed to remove this license from the distribution of the Vim
+ sources, parts of it or from a modified version. You may use this
+ license for previous Vim releases instead of the license that they came
+ with, at your option.
diff --git a/CREDITS b/CREDITS
new file mode 100644
index 0000000..627331f
--- /dev/null
+++ b/CREDITS
@@ -0,0 +1,88 @@
+Except as otherwise noted below, all files in this package:
+
+ Copyright (C) 2010 Mike Miller <[email protected]>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+Files derived from other sources
+--------------------------------
+
+bash_logout, bashrc, profile:
+
+ Copyright (C) 2010 Mike Miller <[email protected]>
+ Copyright (c) 2000-2010 Matthias Klose <[email protected]>
+ Copyright (C) 1989-2006 Free Software Foundation, Inc.
+
+ Bash is free software; you can redistribute it and/or modify it under
+ the terms of the GNU General Public License as published by the Free
+ Software Foundation; either version 2, or (at your option) any later
+ version.
+
+ Bash is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ for more details.
+
+ http://ftp.debian.org/debian/pool/main/b/bash/bash_4.1.orig.tar.gz
+ http://ftp.debian.org/debian/pool/main/b/bash/bash_4.1-3.diff.gz
+
+colordiffrc:
+
+ Copyright (C) 2010 Mike Miller <[email protected]>
+ Copyright (C) 2002-2009 Dave Ewart <[email protected]>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ http://colordiff.sourceforge.net/colordiff-1.0.9.tar.gz
+
+dircolors:
+
+ Copyright (C) 1996, 1999-2010 Free Software Foundation, Inc.
+ Copying and distribution of this file, with or without modification,
+ are permitted provided the copyright notice and this notice are preserved.
+
+ git clone git://git.sv.gnu.org/coreutils
+
+vimrc:
+
+ Copyright (C) 2010 Mike Miller <[email protected]>
+
+ Derived from vimrc_example.vim by Bram Moolenaar <[email protected]>, part of
+ Vim, which is distributed under the Vim license. See COPYING.VIM for the
+ full text of the license.
+
+ hg clone https://vim.googlecode.com/hg/ vim-hg
+
+vim/colors/zenburn.vim:
+
+ Maintainer: Jani Nurminen <[email protected]>
+ Last Change: $Id: zenburn.vim,v 2.13 2009/10/24 10:16:01 slinky Exp $
+ URL: http://slinky.imukuppi.org/zenburnpage/
+ License: GPL
+
+ http://slinky.imukuppi.org/zenburn/zenburn.vim
+
+vim/bundle/vim-fugitive:
+
+ Author: Tim Pope <[email protected]>
+ License: Same terms as Vim itself
+
+ See COPYING.VIM for the full text of the Vim license.
+
+ http://github.com/tpope/vim-fugitive
diff --git a/README b/README
new file mode 100644
index 0000000..fa15414
--- /dev/null
+++ b/README
@@ -0,0 +1,20 @@
+This is a collection of configuration files for the shell, editor, and other
+commands and utilities used frequently by the author.
+
+This dotfiles collection is free software, distributed under the terms of the
+GNU General Public License as published by the Free Software Foundation,
+either version 3 of the License, or any later version.
+
+This package is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+details.
+
+You should have received a copy of the GNU General Public License along with
+this package; see the file COPYING. If not, see
+<http://www.gnu.org/licenses/>.
+
+This package is an aggregation of user configuration files for shells and
+other programs, some of which are based on examples distributed with the
+programs themselves. See the file CREDITS for details on files derived from
+other sources.
diff --git a/bash_completion b/bash_completion
new file mode 100644
index 0000000..bd524fd
--- /dev/null
+++ b/bash_completion
@@ -0,0 +1,33 @@
+# ~/.bash_completion: user programmable completion for bash.
+# This file is typically included by the system-wide bash completion package
+# for user completion configuration.
+
+# If this file has already been loaded do not load it again.
+[ -n "$BASH_COMPLETION_USER_FILE" ] && return
+
+# Check for minimum safe version of bash for certain features.
+bash=${BASH_VERSION%.*}; bmajor=${bash%.*}; bminor=${bash#*.}
+if [ $bmajor -lt 3 ] || [ $bmajor -eq 3 -a $bminor -lt 2 ]; then
+ unset bash bmajor bminor
+ return
+fi
+unset bash bmajor bminor
+
+# Set unique constants for this file and the directory it loads.
+BASH_COMPLETION_USER_FILE=~/.bash_completion
+BASH_COMPLETION_USER_DIR=~/.bash_completion.d
+readonly BASH_COMPLETION_USER_FILE BASH_COMPLETION_USER_DIR
+
+# Turn on extended globbing and programmable completion.
+shopt -s extglob progcomp
+
+# Load completion definitions from the directory specified above.
+if [ -d "$BASH_COMPLETION_USER_DIR" ]; then
+ for i in "$BASH_COMPLETION_USER_DIR"/*; do
+ case "${i##*/}" in
+ *~|*.bak|*.swp) ;;
+ *) [ -f "$i" ] && [ -r "$i" ] && . "$i" ;;
+ esac
+ done
+fi
+unset i
diff --git a/bash_logout b/bash_logout
new file mode 100644
index 0000000..6b13548
--- /dev/null
+++ b/bash_logout
@@ -0,0 +1,16 @@
+# ~/.bash_logout: executed by bash(1) when login shell exits.
+
+# when leaving the console clear the screen to increase privacy
+
+if [ "$SHLVL" = 1 ]; then
+ if [ -x /usr/bin/clear_console ]; then
+ /usr/bin/clear_console -q
+ else
+ # don't bother clearing a pseudo-terminal
+ case `tty` in
+ /dev/pts/*) ;;
+ /dev/tty[p-zP-Za-eA-E][0-9A-Za-z]) ;;
+ *) [ -x /usr/bin/clear ] && /usr/bin/clear ;;
+ esac
+ fi
+fi
diff --git a/bash_profile b/bash_profile
new file mode 100644
index 0000000..37bb6ed
--- /dev/null
+++ b/bash_profile
@@ -0,0 +1,6 @@
+# ~/.bash_profile -*- mode: sh -*- vi:set ft=sh:
+# Executed by bash(1) for login shells, replaces ~/.profile
+
+if [ -r "$HOME/.bashrc" ]; then
+ . "$HOME/.bashrc"
+fi
diff --git a/bashrc b/bashrc
new file mode 100644
index 0000000..d6fa41e
--- /dev/null
+++ b/bashrc
@@ -0,0 +1,146 @@
+# ~/.bashrc: executed by bash(1) for non-login shells.
+# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
+# for examples
+
+# Load common shell initializations
+if [ -r ~/.shrc ]; then
+ . ~/.shrc
+fi
+
+# If not running interactively, don't do anything
+[ -z "$PS1" ] && return
+
+# Clear any aliases inherited from the system (no thank you, Red Hat)
+unalias -a
+
+# don't put duplicate lines in the history. See bash(1) for more options
+# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
+HISTCONTROL=$HISTCONTROL${HISTCONTROL+:}ignoredups
+# ... or force ignoredups and ignorespace
+HISTCONTROL=ignoreboth
+
+# append to the history file, don't overwrite it
+shopt -s histappend
+
+# set history length, save history to a file, and remember times for each
+# history entry
+HISTSIZE=1000
+HISTFILE=~/.bash_history
+HISTFILESIZE=1000
+HISTTIMEFORMAT='%x %X '
+
+# check the window size after each command and, if necessary,
+# update the values of LINES and COLUMNS.
+shopt -s checkwinsize
+
+# make less more friendly for non-text input files, see lesspipe(1)
+[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
+
+# set variable identifying the chroot you work in (used in the prompt below)
+if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
+ debian_chroot=$(cat /etc/debian_chroot)
+fi
+
+PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
+
+# If this is an xterm set the title to user@host:dir
+case "$TERM" in
+xterm*|rxvt*)
+ PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
+ ;;
+screen*)
+ PS1="\[\e_${debian_chroot:+($debian_chroot)}\u@\h: \w\e\\\\\]$PS1"
+ ;;
+*)
+ ;;
+esac
+
+# Enable color support in ls if the shell is on a valid terminal.
+case "$TERM" in
+""|dumb)
+ ;;
+*)
+ # GNU ls and dircolors are both part of coreutils, prefer this option.
+ # Fall back to colorls for *BSD.
+ if [ -x /usr/bin/dircolors ]; then
+ if [ -r ~/.dircolors ]; then
+ # be backwards-compatible: attempt to detect newer keywords not
+ # understood by the available version of dircolors and filter
+ # them out
+ errs=$(dircolors -b ~/.dircolors 2>&1 > /dev/null)
+ bad=$(echo "$errs" | sed -n 's/^.*: unrecognized keyword \(.*\)$/\1/p')
+ if [ "$bad" ]; then
+ fix='grep -F -v "$bad"'
+ # special cases:
+ # - if dircolors doesn't know RESET, use NORMAL and FILE
+ # - if dircolors doesn't know OTHER_WRITABLE, remove SET[GU]ID
+ for word in $bad; do
+ case "$word" in
+ RESET) fix="sed 's/^RESET.*$/NORMAL 00\nFILE 00/' | $fix" ;;
+ *OTHER*) fix="grep -v 'SET[GU]ID' | $fix" ;;
+ esac
+ done
+ eval "$(cat ~/.dircolors | eval $fix | dircolors -b -)"
+ else
+ eval "$(dircolors -b ~/.dircolors)"
+ fi
+ unset bad errs fix word
+ else
+ eval "$(dircolors -b)"
+ fi
+ alias ls='ls --color=auto'
+
+ alias grep='grep --color=auto'
+ alias fgrep='fgrep --color=auto'
+ alias egrep='egrep --color=auto'
+ elif type colorls > /dev/null 2>&1; then
+ alias ls='colorls -G'
+ fi
+ ;;
+esac
+
+# Define command aliases to invoke the preferred editor and pager utilities.
+# Use the sensible-utils commands if on Debian; otherwise, use the values of
+# standard variables.
+if type sensible-editor > /dev/null 2>&1; then
+ alias editor=sensible-editor
+ alias e=sensible-editor
+ alias v=sensible-editor
+elif [ -n "${VISUAL:-$EDITOR}" ]; then
+ alias editor="${VISUAL:-$EDITOR}"
+ alias e="${VISUAL:-$EDITOR}"
+ alias v="${VISUAL:-$EDITOR}"
+fi
+if type sensible-pager > /dev/null 2>&1; then
+ alias pager=sensible-pager
+elif [ -n "$PAGER" ]; then
+ alias pager="$PAGER"
+fi
+
+# Compensate for Red Hat installing the most featureful Vim under a
+# different name.
+if type vimx > /dev/null 2>&1; then
+ alias vim=vimx
+fi
+
+# Alias definitions.
+# You may want to put all your additions into a separate file like
+# ~/.bash_aliases, instead of adding them here directly.
+# See /usr/share/doc/bash-doc/examples in the bash-doc package.
+
+if [ -f ~/.bash_aliases ]; then
+ . ~/.bash_aliases
+fi
+
+# enable programmable completion features (you don't need to enable
+# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
+# sources /etc/bash.bashrc).
+if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
+ . /etc/bash_completion
+fi
+
+# enable programmable completion from ~/.bash_completion (needed for some
+# systems where system-wide bash-completion is not installed).
+if [ -f ~/.bash_completion ] && ! shopt -oq posix; then
+ . ~/.bash_completion
+fi
diff --git a/bazaar/ignore b/bazaar/ignore
new file mode 100644
index 0000000..03c6a5c
--- /dev/null
+++ b/bazaar/ignore
@@ -0,0 +1,8 @@
+*.[ao]
+*.l[ao]
+*.py[co]
+*.so
+*.sw[nop]
+*~
+.#*
+[#]*#
diff --git a/colordiffrc b/colordiffrc
new file mode 100644
index 0000000..2390aed
--- /dev/null
+++ b/colordiffrc
@@ -0,0 +1,26 @@
+# Example colordiffrc file for dark backgrounds
+#
+# Set banner=no to suppress authorship info at top of
+# colordiff output
+banner=no
+# By default, when colordiff output is being redirected
+# to a file, it detects this and does not colour-highlight
+# To make the patch file *include* colours, change the option
+# below to 'yes'
+color_patches=no
+#
+# available colours are: white, yellow, green, blue,
+# cyan, red, magenta, black,
+# darkwhite, darkyellow, darkgreen,
+# darkblue, darkcyan, darkred,
+# darkmagenta, darkblack
+#
+# Can also specify 'none', 'normal' or 'off' which are all
+# aliases for the same thing, namely "don't colour highlight
+# this, use the default output colour"
+#
+plain=off
+newtext=darkgreen
+oldtext=darkred
+diffstuff=darkcyan
+cvsstuff=white
diff --git a/cshrc b/cshrc
new file mode 100644
index 0000000..c69ccad
--- /dev/null
+++ b/cshrc
@@ -0,0 +1,43 @@
+# ~/.cshrc: executed by csh(1) and tcsh(1) for login and non-login shells.
+
+# force the umask in case it was changed by the system configuration
+umask 027
+
+# Clear any aliases inherited from the system (no thank you, Red Hat)
+unalias *
+
+if ($?tcsh && $?prompt) then
+
+ if ( -r ~/.tcsh_editing ) then
+ source ~/.tcsh_editing
+ endif
+
+ # make tcsh behavior a little closer to that of bash
+ set symlinks = ignore
+ set nonomatch
+
+ set histdup = prev
+ set history = (1000 "%h\t%W/%D/%Y %p\t%R\n")
+ set savehist = (1000 merge)
+
+ set prompt = "%n@%m:%~%# "
+ set promptchars = '$#'
+
+ if ($?TERM) then
+ switch ($TERM)
+ case xterm*:
+ set prompt = "%{\033]0;%n@%m: %~\007%}$prompt"
+ breaksw
+ case screen*:
+ set prompt = "%{\033_%n@%m: %~\033\\%}$prompt"
+ breaksw
+ endsw
+ endif
+
+ setenv COLUMNS
+ setenv LINES
+endif
+
+if ( -r ~/.cshrc.local ) then
+ source ~/.cshrc.local
+endif
diff --git a/cvsignore b/cvsignore
new file mode 100644
index 0000000..03c6a5c
--- /dev/null
+++ b/cvsignore
@@ -0,0 +1,8 @@
+*.[ao]
+*.l[ao]
+*.py[co]
+*.so
+*.sw[nop]
+*~
+.#*
+[#]*#
diff --git a/cvsrc b/cvsrc
new file mode 100644
index 0000000..b7e806a
--- /dev/null
+++ b/cvsrc
@@ -0,0 +1,5 @@
+cvs -q
+checkout -P
+diff -up
+rdiff -u
+update -Pd
diff --git a/dircolors b/dircolors
new file mode 100644
index 0000000..0770b1a
--- /dev/null
+++ b/dircolors
@@ -0,0 +1,209 @@
+# Configuration file for dircolors, a utility to help you set the
+# LS_COLORS environment variable used by GNU ls with the --color option.
+
+# Copyright (C) 1996, 1999-2010 Free Software Foundation, Inc.
+# Copying and distribution of this file, with or without modification,
+# are permitted provided the copyright notice and this notice are preserved.
+
+# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
+# slackware version of dircolors) are recognized but ignored.
+
+# Below, there should be one TERM entry for each termtype that is colorizable
+TERM Eterm
+TERM ansi
+TERM color-xterm
+TERM con132x25
+TERM con132x30
+TERM con132x43
+TERM con132x60
+TERM con80x25
+TERM con80x28
+TERM con80x30
+TERM con80x43
+TERM con80x50
+TERM con80x60
+TERM cons25
+TERM console
+TERM cygwin
+TERM dtterm
+TERM eterm-color
+TERM gnome
+TERM gnome-256color
+TERM jfbterm
+TERM konsole
+TERM kterm
+TERM linux
+TERM linux-c
+TERM mach-color
+TERM mlterm
+TERM putty
+TERM rxvt
+TERM rxvt-256color
+TERM rxvt-cygwin
+TERM rxvt-cygwin-native
+TERM rxvt-unicode
+TERM rxvt-unicode-256color
+TERM rxvt-unicode256
+TERM screen
+TERM screen-256color
+TERM screen-256color-bce
+TERM screen-bce
+TERM screen-w
+TERM screen.rxvt
+TERM screen.linux
+TERM terminator
+TERM vt100
+TERM xterm
+TERM xterm-16color
+TERM xterm-256color
+TERM xterm-88color
+TERM xterm-color
+TERM xterm-debian
+
+# Below are the color init strings for the basic file types. A color init
+# string consists of one or more of the following numeric codes:
+# Attribute codes:
+# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
+# Text color codes:
+# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
+# Background color codes:
+# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
+#NORMAL 00 # no color code at all
+#FILE 00 # regular file: use no color at all
+RESET 0 # reset to "normal" color
+DIR 01;34 # directory
+LINK 01;36 # symbolic link. (If you set this to 'target' instead of a
+ # numerical value, the color is as for the file pointed to.)
+MULTIHARDLINK 00 # regular file with more than one link
+FIFO 40;33 # pipe
+SOCK 01;35 # socket
+DOOR 01;35 # door
+BLK 40;33;01 # block device driver
+CHR 40;33;01 # character device driver
+ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file
+SETUID 37;41 # file that is setuid (u+s)
+SETGID 30;43 # file that is setgid (g+s)
+CAPABILITY 30;41 # file with capability
+STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
+OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
+STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
+
+# This is for files with execute permission:
+EXEC 01;32
+
+# List any file extensions like '.gz' or '.tar' that you would like ls
+# to colorize below. Put the extension, a space, and the color init string.
+# (and any comments you want to add after a '#')
+
+# If you use DOS-style suffixes, you may want to uncomment the following:
+#.cmd 01;32 # executables (bright green)
+#.exe 01;32
+#.com 01;32
+#.btm 01;32
+#.bat 01;32
+# Or if you want to colorize scripts even if they do not have the
+# executable bit actually set.
+#.sh 01;32
+#.csh 01;32
+
+ # archives or compressed (bright red)
+.tar 01;31
+.tgz 01;31
+.arj 01;31
+.taz 01;31
+.lzh 01;31
+.lzma 01;31
+.tlz 01;31
+.txz 01;31
+.zip 01;31
+.z 01;31
+.Z 01;31
+.dz 01;31
+.gz 01;31
+.lz 01;31
+.xz 01;31
+.bz2 01;31
+.bz 01;31
+.tbz 01;31
+.tbz2 01;31
+.tz 01;31
+.deb 01;31
+.rpm 01;31
+.jar 01;31
+.rar 01;31
+.ace 01;31
+.zoo 01;31
+.cpio 01;31
+.7z 01;31
+.rz 01;31
+
+# image formats
+.jpg 01;35
+.jpeg 01;35
+.gif 01;35
+.bmp 01;35
+.pbm 01;35
+.pgm 01;35
+.ppm 01;35
+.tga 01;35
+.xbm 01;35
+.xpm 01;35
+.tif 01;35
+.tiff 01;35
+.png 01;35
+.svg 01;35
+.svgz 01;35
+.mng 01;35
+.pcx 01;35
+.mov 01;35
+.mpg 01;35
+.mpeg 01;35
+.m2v 01;35
+.mkv 01;35
+.ogm 01;35
+.mp4 01;35
+.m4v 01;35
+.mp4v 01;35
+.vob 01;35
+.qt 01;35
+.nuv 01;35
+.wmv 01;35
+.asf 01;35
+.rm 01;35
+.rmvb 01;35
+.flc 01;35
+.avi 01;35
+.fli 01;35
+.flv 01;35
+.gl 01;35
+.dl 01;35
+.xcf 01;35
+.xwd 01;35
+.yuv 01;35
+.cgm 01;35
+.emf 01;35
+
+# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
+.axv 01;35
+.anx 01;35
+.ogv 01;35
+.ogx 01;35
+
+# audio formats
+.aac 00;36
+.au 00;36
+.flac 00;36
+.mid 00;36
+.midi 00;36
+.mka 00;36
+.mp3 00;36
+.mpc 00;36
+.ogg 00;36
+.ra 00;36
+.wav 00;36
+
+# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
+.axa 00;36
+.oga 00;36
+.spx 00;36
+.xspf 00;36
diff --git a/emacs b/emacs
new file mode 100644
index 0000000..44b78ea
--- /dev/null
+++ b/emacs
@@ -0,0 +1,14 @@
+;; ~/.emacs
+
+(when (fboundp 'blink-cursor-mode)
+ (blink-cursor-mode 0))
+(dolist (fn '(global-font-lock-mode show-paren-mode transient-mark-mode))
+ (when (fboundp fn)
+ (funcall fn t)))
+
+(custom-set-variables
+ '(diff-switches "-u")
+ '(frame-title-format (concat "%b - " (invocation-name) "@" (system-name)))
+ '(require-final-newline 'query)
+ '(ring-bell-function 'ignore)
+ '(scroll-bar-mode 'right))
diff --git a/gitignore b/gitignore
new file mode 100644
index 0000000..03c6a5c
--- /dev/null
+++ b/gitignore
@@ -0,0 +1,8 @@
+*.[ao]
+*.l[ao]
+*.py[co]
+*.so
+*.sw[nop]
+*~
+.#*
+[#]*#
diff --git a/hgignore b/hgignore
new file mode 100644
index 0000000..7fc9638
--- /dev/null
+++ b/hgignore
@@ -0,0 +1,10 @@
+syntax: glob
+
+*.[ao]
+*.l[ao]
+*.py[co]
+*.so
+*.sw[nop]
+*~
+.#*
+[#]*#
diff --git a/inputrc b/inputrc
new file mode 100644
index 0000000..83f6c29
--- /dev/null
+++ b/inputrc
@@ -0,0 +1,61 @@
+# ~/.inputrc - user configuration for readline
+
+# No terminal bell on completion
+set bell-style none
+
+# Be 8 bit clean
+set input-meta on
+set output-meta on
+set convert-meta off
+set byte-oriented off
+
+# Trailing slash on directories and symlinks to directories
+set mark-directories on
+set mark-symlinked-directories on
+
+# Default editing and key binding mode
+set editing-mode emacs
+set keymap emacs
+
+# Default key bindings are for PC keyboard on a Linux console, Xterm, or
+# GNOME VTE.
+
+# VT100 ANSI cursor movement
+"\e[A": previous-history
+"\e[B": next-history
+"\e[C": forward-char
+"\e[D": backward-char
+
+# VT100 keypad application mode cursor movement
+"\eOA": previous-history
+"\eOB": next-history
+"\eOC": forward-char
+"\eOD": backward-char
+
+# Xterm Home/End "cursor" keys in normal mode
+"\e[H": beginning-of-line
+"\e[F": end-of-line
+
+# Xterm Home/End "cursor" keys in cursor application mode
+"\eOH": beginning-of-line
+"\eOF": end-of-line
+
+# VT220 Find/Select -> Linux console Home/End and GNOME VTE keypad Home/End
+"\e[1~": beginning-of-line
+"\e[4~": end-of-line
+
+# VT220 Insert/Delete -> PC Insert/Delete
+"\e[2~": quoted-insert
+"\e[3~": delete-char
+
+# VT220 Prev/Next -> PC PageUp/PageDown
+"\e[5~": beginning-of-history
+"\e[6~": end-of-history
+
+# Xterm control-modified cursor keys
+"\e[1;5C": forward-word
+"\e[1;5D": backward-word
+
+# GNOME VTE control-modified cursor keys versions older than 0.15.0
+"\e[5C": forward-word
+"\e[5D": backward-word
diff --git a/ipython/ipy_user_conf.py b/ipython/ipy_user_conf.py
new file mode 100644
index 0000000..7b982f1
--- /dev/null
+++ b/ipython/ipy_user_conf.py
@@ -0,0 +1,28 @@
+# Configuration file for ipython version < 0.11.
+
+import IPython.ipapi
+import ipy_defaults
+import os
+import sys
+
+def unalias(shell, *args):
+ for cmd in args:
+ if cmd in shell.alias_table:
+ del shell.alias_table[cmd]
+
+def main():
+ ip = IPython.ipapi.get()
+ ip.options.autoindent = 1
+ ip.options.confirm_exit = 0
+ ip.options.pprint = 1
+ ip.options.separate_out = ''
+
+ unalias(ip.IP, 'lc', 'lf', 'lk', 'll', 'lx', 'ddir', 'ldir')
+ if os.name == 'posix':
+ ip.defalias('ps', 'ps')
+ if 'bsd' in sys.platform:
+ ip.defalias('ls', 'colorls -G')
+ else:
+ ip.defalias('ls', 'ls --color=auto')
+
+main()
diff --git a/ipython/ipythonrc b/ipython/ipythonrc
new file mode 100644
index 0000000..2fb9ac0
--- /dev/null
+++ b/ipython/ipythonrc
@@ -0,0 +1 @@
+# Legacy configuration file for ipython, exists to avoid warning messages
diff --git a/ipython/profile_default/ipython_config.py b/ipython/profile_default/ipython_config.py
new file mode 100644
index 0000000..da6144f
--- /dev/null
+++ b/ipython/profile_default/ipython_config.py
@@ -0,0 +1,20 @@
+# Configuration file for ipython version >= 0.11.
+
+import os
+import sys
+
+c = get_config()
+
+c.TerminalIPythonApp.ignore_old_config = True
+c.InteractiveShell.autoindent = True
+c.InteractiveShell.colors = 'Linux'
+c.InteractiveShell.confirm_exit = False
+
+c.AliasManager.default_aliases = []
+c.AliasManager.user_aliases = []
+if os.name == 'posix':
+ c.AliasManager.user_aliases.append(('ps', 'ps'))
+ if 'bsd' in sys.platform:
+ c.AliasManager.user_aliases.append(('ls', 'colorls -G'))
+ else:
+ c.AliasManager.user_aliases.append(('ls', 'ls --color=auto'))
diff --git a/irbrc b/irbrc
new file mode 100644
index 0000000..9c914c0
--- /dev/null
+++ b/irbrc
@@ -0,0 +1,13 @@
+# -*- mode: ruby -*- vi:set ft=ruby:
+
+%w(rubygems).each do |lib|
+ begin
+ require lib
+ rescue LoadError
+ end
+end
+
+IRB.conf[:LOAD_MODULES] |= %w(irb/completion)
+IRB.conf[:AUTO_INDENT] = true
+IRB.conf[:HISTORY_FILE] = File.expand_path('~/.irb_history')
+IRB.conf[:SAVE_HISTORY] = 1000
diff --git a/lintianrc b/lintianrc
new file mode 100644
index 0000000..b0d3707
--- /dev/null
+++ b/lintianrc
@@ -0,0 +1,19 @@
+# ~/.lintianrc
+#
+# Set the default profile (--profile)
+LINTIAN_PROFILE = debian
+
+# Enable info tags by default (--display info)
+display-info = yes
+
+# Enable pedantic tags by default (--pedantic)
+pedantic = yes
+
+# Enable experimental tags by default (--display-experimental)
+display-experimental = yes
+
+# Enable colored output for terminal output (--color)
+color = auto
+
+# Show overridden tags (--show-overrides)
+show-overrides = yes
diff --git a/octaverc b/octaverc
new file mode 100644
index 0000000..d40969f
--- /dev/null
+++ b/octaverc
@@ -0,0 +1,19 @@
+# ~/.octaverc: Octave per-user initialization file.
+
+# If Octave is running in a known terminal emulator set the title.
+term_title = ["GNU Octave " version];
+if regexp(getenv("TERM"), "^xterm")
+ PS1(["\\[\\033]0;" term_title "\\007\\]" PS1]);
+end
+clear term_title
+
+# Add ~/octave (and all subdirectories) to the Octave load path.
+addpath(genpath("~/octave"));
+
+# Set up Octave editor.
+if getenv("DISPLAY")
+ edit editor "gvim %s"
+ edit mode async
+else
+ edit mode sync
+endif
diff --git a/profile b/profile
new file mode 100644
index 0000000..7e47da7
--- /dev/null
+++ b/profile
@@ -0,0 +1,8 @@
+# ~/.profile -*- mode: sh -*- vi:set ft=sh:
+# Executed by the command interpreter for login shells
+
+if [ -n "$BASH_VERSION" ] && [ -r "$HOME/.bashrc" ]; then
+ . "$HOME/.bashrc"
+elif [ -r "$HOME/.shrc" ]; then
+ . "$HOME/.shrc"
+fi
diff --git a/quiltrc b/quiltrc
new file mode 100644
index 0000000..5534b01
--- /dev/null
+++ b/quiltrc
@@ -0,0 +1,24 @@
+# ~/.quiltrc -*- mode: sh -*- vi:set ft=sh:
+# User configuration file for quilt
+
+# Options passed to quilt commands
+QUILT_DIFF_ARGS="-p ab --no-index --no-timestamps --color=auto"
+QUILT_NEW_ARGS="-p ab"
+QUILT_PATCHES_ARGS="--color=auto"
+QUILT_PUSH_ARGS="--color=auto"
+QUILT_REFRESH_ARGS="-p ab --no-index --no-timestamps --backup"
+QUILT_SERIES_ARGS="--color=auto"
+
+# Options passed to external commands (diff, patch)
+QUILT_DIFF_OPTS="-p"
+QUILT_PATCH_OPTS="-u"
+
+# Quilt patch directory and series file defaults
+: ${QUILT_PATCHES="patches"}
+: ${QUILT_SERIES="series"}
+
+# Show the patch directory path when listing patch names
+QUILT_PATCHES_PREFIX=yes
+
+# Quilt color overrides
+QUILT_COLORS="diff_hdr=1;37:diff_add=32:diff_rem=31:diff_hunk=35"
diff --git a/quiltrc-dpkg b/quiltrc-dpkg
new file mode 100644
index 0000000..335126a
--- /dev/null
+++ b/quiltrc-dpkg
@@ -0,0 +1,13 @@
+# ~/.quiltrc-dpkg -*- mode: sh -*- vi:set ft=sh:
+# Debian-packaging-specific quilt configuration
+# Adapted from the Debian New Maintainers' Guide
+
+d=. ; while [ ! -d $d/debian -a `readlink -e $d` != / ]; do d=$d/..; done
+if [ -d $d/debian ] && [ -z "$QUILT_PATCHES" ]; then
+ QUILT_PATCHES="debian/patches"
+ if ! [ -d "$d/$QUILT_PATCHES" ]; then mkdir "$d/$QUILT_PATCHES"; fi
+fi
+
+if [ -e "$HOME/.quiltrc" ]; then
+ . "$HOME/.quiltrc"
+fi
diff --git a/re.pl/repl.rc b/re.pl/repl.rc
new file mode 100644
index 0000000..c9ee25c
--- /dev/null
+++ b/re.pl/repl.rc
@@ -0,0 +1,26 @@
+# -*- mode: perl -*- vi:set ft=perl:
+
+use strict;
+use warnings;
+
+load_plugin qw(
+ FancyPrompt
+ History
+ LexEnv
+ MultiLine::PPI
+ Packages
+);
+
+$_REPL->term->ornaments(0);
+
+$_REPL->fancy_continuation_prompt(sub {
+ my $self = shift;
+ my $indent = ' ' x 4 x $self->line_depth;
+ sprintf 're.pl(%s):%03d:%d> %s',
+ $self->current_package,
+ $self->lines_read,
+ $self->line_depth,
+ $indent;
+});
+
+package main;
diff --git a/shrc b/shrc
new file mode 100644
index 0000000..f3d747d
--- /dev/null
+++ b/shrc
@@ -0,0 +1,129 @@
+# ~/.shrc -*- mode: sh -*- vi:set ft=sh:
+# Shell environment configuration for POSIX-compliant command interpreters.
+# This file is intended to be executed from within ~/.profile or another
+# shell initialization file (such as ~/.bashrc).
+
+# Set my default semi-paranoid umask before anything else
+umask 027
+
+__list_contains() {
+ eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
+}
+
+__list_append() {
+ eval "$1=\${$1:+\$$1:}$2"
+}
+
+__list_prepend() {
+ eval "$1=$2\${$1:+:\$$1}"
+}
+
+__list_append_uniq() {
+ __list_contains "$@" || __list_append "$@" || :
+}
+
+__list_prepend_uniq() {
+ __list_contains "$@" || __list_prepend "$@" || :
+}
+
+# Add any missing standard directories to the end of PATH in order.
+for dir in /usr/local/bin /usr/bin /bin /usr/local/games /usr/games; do
+ __list_append_uniq PATH "$dir"
+done
+
+# set PATH so it includes user's private bin if it exists
+if [ -d "$HOME/bin" ] ; then
+ __list_prepend_uniq PATH "$HOME/bin"
+fi
+
+# Configure user Perl library paths.
+# Assume Perl modules are installed as perl Makefile.PL INSTALL_BASE=~ or
+# perl Build.PL --install_base ~
+cmd="use Config; use File::Spec::Functions"
+cmd="$cmd; print catdir('$HOME', qw(lib perl5)), ' '"
+cmd="$cmd; print catdir('$HOME', qw(lib perl5), \$Config{archname}), ' '"
+for dir in `perl -e "$cmd" 2> /dev/null`; do
+ if [ -n "$dir" ]; then
+ __list_prepend_uniq PERL5LIB "$dir"
+ export PERL5LIB
+ fi
+done
+
+# Configure user Python library paths.
+# Assume Python packages are installed as python setup.py install --prefix=~
+cmd="from distutils import sysconfig"
+cmd="$cmd; print sysconfig.get_python_lib(0,0,prefix='$HOME')"
+for dir in `python -c "$cmd" 2> /dev/null`; do
+ if [ -n "$dir" ]; then
+ __list_prepend_uniq PYTHONPATH "$dir"
+ export PYTHONPATH
+ fi
+done
+
+# Configure personal RubyGems environment and add bin directory to PATH.
+cmd='puts (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"]'
+ver=$(ruby -rrbconfig -e "$cmd" 2> /dev/null)
+if [ -n "$ver" ]; then
+ GEM_HOME="$HOME/.gem/ruby/$ver"
+ GEM_PATH="$GEM_HOME"
+ export GEM_HOME GEM_PATH
+fi
+cmd='puts Gem.default_dir'
+dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
+if [ -n "$dir" ] && [ -d "$dir" ]; then
+ __list_append_uniq GEM_PATH "$dir"
+ export GEM_PATH
+fi
+cmd='puts Gem.bindir'
+dir=$(ruby -rrubygems -e "$cmd" 2> /dev/null)
+if [ -n "$dir" ] && [ -d "$dir" ]; then
+ if ! __list_contains PATH "$dir"; then
+ # Put this directory at the front of PATH, but after ~/bin if present.
+ PATH=$(echo "$PATH" | sed -e 's,^\(.*'"$HOME/bin"':\)\?,\1'"$dir:,")
+ fi
+fi
+unset cmd dir ver
+
+# Configure Perl locale, see perlrun(1).
+case `locale charmap 2> /dev/null` in
+UTF-8) PERL_UNICODE=SDAL; export PERL_UNICODE ;;
+esac
+
+# Set default text editor, pager, and web browser.
+for util in vimx vim vi ex ed; do
+ type $util > /dev/null 2>&1 && EDITOR=$util && break
+done
+for util in vimx vim vi; do
+ type $util > /dev/null 2>&1 && VISUAL=$util && break
+done
+for util in less more; do
+ type $util > /dev/null 2>&1 && PAGER=$util && break
+done
+if [ -n "$DISPLAY" ]; then
+ for util in google-chrome chromium-browser firefox; do
+ type $util > /dev/null 2>&1 && BROWSER=$util && break
+ done
+fi
+for util in w3m; do
+ type $util > /dev/null 2>&1 && __list_append_uniq BROWSER "$util" && break
+done
+[ -n "$EDITOR" ] && export EDITOR || unset EDITOR
+[ -n "$VISUAL" ] && export VISUAL || unset VISUAL
+[ -n "$PAGER" ] && export PAGER || unset PAGER
+[ -n "$BROWSER" ] && export BROWSER || unset BROWSER
+unset util
+if [ "$PAGER" = less ]; then
+ LESS=iFRSX
+ MANPAGER='less -s'
+ export LESS MANPAGER
+fi
+if [ -n "$EDITOR" ]; then
+ FCEDIT="$EDITOR"
+ export FCEDIT
+fi
+
+if [ -r "$HOME/.shrc.local" ]; then
+ . "$HOME/.shrc.local"
+fi
+
+unset __list_contains __list_append __list_append_uniq __list_prepend __list_prepend_uniq
diff --git a/ssh/config b/ssh/config
new file mode 100644
index 0000000..2fd558a
--- /dev/null
+++ b/ssh/config
@@ -0,0 +1,13 @@
+# ~/.ssh/config: ssh client per-user configuration file.
+
+# Default configuration for all hosts.
+Host *
+ ForwardAgent no
+ ForwardX11 no
+ ForwardX11Trusted no
+ StrictHostKeyChecking ask
+ Protocol 2
+ SendEnv LANG LC_*
+ HashKnownHosts yes
+ GSSAPIAuthentication yes
+ GSSAPIDelegateCredentials no
diff --git a/tcsh_editing b/tcsh_editing
new file mode 100644
index 0000000..5c5dfcf
--- /dev/null
+++ b/tcsh_editing
@@ -0,0 +1,63 @@
+# ~/.tcsh_editing -*- mode: sh -*- vi:set ft=tcsh:
+# Configure the tcsh command-line editor, similar to ~/.inputrc.
+
+# No terminal bell on completion
+set nobeep
+
+# Only list completions when no new characters are added
+set autolist = ambiguous
+
+# Use the readline concept of a word, i.e. no non-alphanumeric characters
+set wordchars = ""
+
+# Set default editing mode to emacs
+bindkey -e
+
+# Common sense bindings
+bindkey "^R" i-search-back
+bindkey "^U" backward-kill-line
+bindkey "^W" backward-delete-word
+bindkey "\e." insert-last-word
+
+# Default key bindings are for PC keyboard on a Linux console, Xterm, or
+# GNOME VTE.
+
+# VT100 ANSI cursor movement
+bindkey "\e[A" up-history
+bindkey "\e[B" down-history
+bindkey "\e[C" forward-char
+bindkey "\e[D" backward-char
+
+# VT100 keypad application mode cursor movement
+bindkey "\eOA" up-history
+bindkey "\eOB" down-history
+bindkey "\eOC" forward-char
+bindkey "\eOD" backward-char
+
+# Xterm Home/End "cursor" keys in normal mode
+bindkey "\e[H" beginning-of-line
+bindkey "\e[F" end-of-line
+
+# Xterm Home/End "cursor" keys in cursor application mode
+bindkey "\eOH" beginning-of-line
+bindkey "\eOF" end-of-line
+
+# VT220 Find/Select -> Linux console Home/End and GNOME VTE keypad Home/End
+bindkey "\e[1~" beginning-of-line
+bindkey "\e[4~" end-of-line
+
+# VT220 Insert/Delete -> PC Insert/Delete
+bindkey "\e[2~" quoted-insert
+bindkey "\e[3~" delete-char
+
+# VT220 Prev/Next -> PC PageUp/PageDown
+bindkey "\e[5~" up-history
+bindkey "\e[6~" down-history
+
+# Xterm control-modified cursor keys
+bindkey "\e[1;5C" forward-word
+bindkey "\e[1;5D" backward-word
+
+# GNOME VTE control-modified cursor keys versions older than 0.15.0
+bindkey "\e[5C" forward-word
+bindkey "\e[5D" backward-word
diff --git a/teclarc b/teclarc
new file mode 100644
index 0000000..70d894d
--- /dev/null
+++ b/teclarc
@@ -0,0 +1,54 @@
+# ~/.teclarc - user configuration for tecla
+
+# No terminal bell on completion
+nobeep
+
+# Default editing and key binding mode
+edit-mode emacs
+
+# Common-sense bindings that have different defaults under tecla.
+bind ^U backward-kill-line
+bind ^W backward-delete-word
+
+# Default key bindings are for PC keyboard on a Linux console, Xterm, or
+# GNOME VTE.
+
+# VT100 ANSI cursor movement
+bind \e[A up-history
+bind \e[B down-history
+bind \e[C cursor-right
+bind \e[D cursor-left
+
+# VT100 keypad application mode cursor movement
+bind \eOA up-history
+bind \eOB down-history
+bind \eOC cursor-right
+bind \eOD cursor-left
+
+# Xterm Home/End "cursor" keys in normal mode
+bind \e[H beginning-of-line
+bind \e[F end-of-line
+
+# Xterm Home/End "cursor" keys in cursor application mode
+bind \eOH beginning-of-line
+bind \eOF end-of-line
+
+# VT220 Find/Select -> Linux console Home/End and GNOME VTE keypad Home/End
+bind \e[1~ beginning-of-line
+bind \e[4~ end-of-line
+
+# VT220 Insert/Delete -> PC Insert/Delete
+bind \e[2~ literal-next
+bind \e[3~ forward-delete-char
+
+# VT220 Prev/Next -> PC PageUp/PageDown
+bind \e[5~ beginning-of-history
+bind \e[6~ end-of-history
+
+# Xterm control-modified cursor keys
+bind \e[1;5C forward-word
+bind \e[1;5D backward-word
+
+# GNOME VTE control-modified cursor keys versions older than 0.15.0
+bind \e[5C forward-word
+bind \e[5D backward-word
diff --git a/vim/after/ftplugin/c.vim b/vim/after/ftplugin/c.vim
new file mode 100644
index 0000000..60a59e5
--- /dev/null
+++ b/vim/after/ftplugin/c.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: C/C++
+
+call SetBufferIndentationPreferences(4, "spaces")
diff --git a/vim/after/ftplugin/fortran.vim b/vim/after/ftplugin/fortran.vim
new file mode 100644
index 0000000..458827d
--- /dev/null
+++ b/vim/after/ftplugin/fortran.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: Fortran
+
+call SetBufferIndentationPreferences(2, "mixed")
diff --git a/vim/after/ftplugin/perl.vim b/vim/after/ftplugin/perl.vim
new file mode 100644
index 0000000..237bdbc
--- /dev/null
+++ b/vim/after/ftplugin/perl.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: Perl
+
+call SetBufferIndentationPreferences(4, "spaces")
diff --git a/vim/after/ftplugin/python.vim b/vim/after/ftplugin/python.vim
new file mode 100644
index 0000000..54bb65f
--- /dev/null
+++ b/vim/after/ftplugin/python.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: Python
+
+call SetBufferIndentationPreferences(4, "spaces")
diff --git a/vim/after/ftplugin/ruby.vim b/vim/after/ftplugin/ruby.vim
new file mode 100644
index 0000000..d1d24af
--- /dev/null
+++ b/vim/after/ftplugin/ruby.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: Ruby
+
+call SetBufferIndentationPreferences(2, "spaces")
diff --git a/vim/after/ftplugin/sh.vim b/vim/after/ftplugin/sh.vim
new file mode 100644
index 0000000..2d65823
--- /dev/null
+++ b/vim/after/ftplugin/sh.vim
@@ -0,0 +1,8 @@
+" Vim filetype plugin
+" Language: Shell
+
+call SetBufferIndentationPreferences(4, "spaces")
+if v:version >= 700
+ let b:sh_indent_options = {"case-labels": 0}
+ let b:undo_ftplugin .= " | unlet! b:sh_indent_options"
+endif
diff --git a/vim/after/ftplugin/vim.vim b/vim/after/ftplugin/vim.vim
new file mode 100644
index 0000000..15f64c7
--- /dev/null
+++ b/vim/after/ftplugin/vim.vim
@@ -0,0 +1,4 @@
+" Vim filetype plugin
+" Language: Vim
+
+call SetBufferIndentationPreferences(2, "spaces")
diff --git a/vim/after/syntax/m4.vim b/vim/after/syntax/m4.vim
new file mode 100644
index 0000000..35fabde
--- /dev/null
+++ b/vim/after/syntax/m4.vim
@@ -0,0 +1,4 @@
+" Vim syntax file
+" Language: M4
+
+syn match m4Comment "#.*$" contains=SpellErrors
diff --git a/vim/bundle/nerdtree b/vim/bundle/nerdtree
new file mode 160000
index 0000000..1cd5048
--- /dev/null
+++ b/vim/bundle/nerdtree
@@ -0,0 +1 @@
+Subproject commit 1cd50482d2b0137a3faa3ee6ec4cb9d425bd3bb6
diff --git a/vim/bundle/vim-fugitive b/vim/bundle/vim-fugitive
new file mode 160000
index 0000000..c872a54
--- /dev/null
+++ b/vim/bundle/vim-fugitive
@@ -0,0 +1 @@
+Subproject commit c872a546751f1723766479528391cdada4aeb1ec
diff --git a/vim/bundle/vim-pathogen b/vim/bundle/vim-pathogen
new file mode 160000
index 0000000..c9fb89d
--- /dev/null
+++ b/vim/bundle/vim-pathogen
@@ -0,0 +1 @@
+Subproject commit c9fb89dd6efdeedb95c411ec78b3a9493602d33d
diff --git a/vim/colors/zenburn.vim b/vim/colors/zenburn.vim
new file mode 100644
index 0000000..663fdf9
--- /dev/null
+++ b/vim/colors/zenburn.vim
@@ -0,0 +1,353 @@
+" Vim color file
+" Maintainer: Jani Nurminen <[email protected]>
+" Last Change: $Id: zenburn.vim,v 2.13 2009/10/24 10:16:01 slinky Exp $
+" URL: http://slinky.imukuppi.org/zenburnpage/
+" License: GPL
+"
+" Nothing too fancy, just some alien fruit salad to keep you in the zone.
+" This syntax file was designed to be used with dark environments and
+" low light situations. Of course, if it works during a daybright office, go
+" ahead :)
+"
+" Owes heavily to other Vim color files! With special mentions
+" to "BlackDust", "Camo" and "Desert".
+"
+" To install, copy to ~/.vim/colors directory.
+"
+" Alternatively, you can use Vimball installation:
+" vim zenburn.vba
+" :so %
+" :q
+"
+" For details, see :help vimball
+"
+" After installation, use it with :colorscheme zenburn.
+" See also :help syntax
+"
+" Credits:
+" - Jani Nurminen - original Zenburn
+" - Steve Hall & Cream posse - higher-contrast Visual selection
+" - Kurt Maier - 256 color console coloring, low and high contrast toggle,
+" bug fixing
+" - Charlie - spotted too bright StatusLine in non-high contrast mode
+" - Pablo Castellazzi - CursorLine fix for 256 color mode
+" - Tim Smith - force dark background
+" - John Gabriele - spotted bad Ignore-group handling
+" - Zac Thompson - spotted invisible NonText in low contrast mode
+" - Christophe-Marie Duquesne - suggested making a Vimball
+"
+" CONFIGURABLE PARAMETERS:
+"
+" You can use the default (don't set any parameters), or you can
+" set some parameters to tweak the Zenburn colours.
+"
+" To use them, put them into your .vimrc file before loading the color scheme,
+" example:
+" let g:zenburn_high_Contrast=1
+" colors zenburn
+"
+" * You can now set a darker background for bright environments. To activate, use:
+" contrast Zenburn, use:
+"
+" let g:zenburn_high_Contrast = 1
+"
+" * For example, Vim help files uses the Ignore-group for the pipes in tags
+" like "|somelink.txt|". By default, the pipes are not visible, as they
+" map to Ignore group. If you wish to enable coloring of the Ignore group,
+" set the following parameter to 1. Warning, it might make some syntax files
+" look strange.
+"
+" let g:zenburn_color_also_Ignore = 1
+"
+" * To get more contrast to the Visual selection, use
+"
+" let g:zenburn_alternate_Visual = 1
+"
+" * To use alternate colouring for Error message, use
+"
+" let g:zenburn_alternate_Error = 1
+"
+" * The new default for Include is a duller orange. To use the original
+" colouring for Include, use
+"
+" let g:zenburn_alternate_Include = 1
+"
+" * Work-around to a Vim bug, it seems to misinterpret ctermfg and 234 and 237
+" as light values, and sets background to light for some people. If you have
+" this problem, use:
+"
+" let g:zenburn_force_dark_Background = 1
+"
+" NOTE:
+"
+" * To turn the parameter(s) back to defaults, use UNLET:
+"
+" unlet g:zenburn_alternate_Include
+"
+" Setting to 0 won't work!
+"
+" That's it, enjoy!
+"
+" TODO
+" - Visual alternate color is broken? Try GVim >= 7.0.66 if you have trouble
+" - IME colouring (CursorIM)
+
+set background=dark
+hi clear
+if exists("syntax_on")
+ syntax reset
+endif
+let g:colors_name="zenburn"
+
+hi Boolean guifg=#dca3a3
+hi Character guifg=#dca3a3 gui=bold
+hi Comment guifg=#7f9f7f gui=italic
+hi Conditional guifg=#f0dfaf gui=bold
+hi Constant guifg=#dca3a3 gui=bold
+hi Cursor guifg=#000d18 guibg=#8faf9f gui=bold
+hi Debug guifg=#bca3a3 gui=bold
+hi Define guifg=#ffcfaf gui=bold
+hi Delimiter guifg=#8f8f8f
+hi DiffAdd guifg=#709080 guibg=#313c36 gui=bold
+hi DiffChange guibg=#333333
+hi DiffDelete guifg=#333333 guibg=#464646
+hi DiffText guifg=#ecbcbc guibg=#41363c gui=bold
+hi Directory guifg=#dcdccc gui=bold
+hi ErrorMsg guifg=#80d4aa guibg=#2f2f2f gui=bold
+hi Exception guifg=#c3bf9f gui=bold
+hi Float guifg=#c0bed1
+hi FoldColumn guifg=#93b3a3 guibg=#3f4040
+hi Folded guifg=#93b3a3 guibg=#3f4040
+hi Function guifg=#efef8f
+hi Identifier guifg=#efdcbc
+hi IncSearch guibg=#f8f893 guifg=#385f38
+hi Keyword guifg=#f0dfaf gui=bold
+hi Label guifg=#dfcfaf gui=underline
+hi LineNr guifg=#9fafaf guibg=#262626
+hi Macro guifg=#ffcfaf gui=bold
+hi ModeMsg guifg=#ffcfaf gui=none
+hi MoreMsg guifg=#ffffff gui=bold
+hi Number guifg=#8cd0d3
+hi Operator guifg=#f0efd0
+hi PreCondit guifg=#dfaf8f gui=bold
+hi PreProc guifg=#ffcfaf gui=bold
+hi Question guifg=#ffffff gui=bold
+hi Repeat guifg=#ffd7a7 gui=bold
+hi Search guifg=#ffffe0 guibg=#284f28
+hi SpecialChar guifg=#dca3a3 gui=bold
+hi SpecialComment guifg=#82a282 gui=bold
+hi Special guifg=#cfbfaf
+hi SpecialKey guifg=#9ece9e
+hi Statement guifg=#e3ceab gui=none
+hi StatusLine guifg=#313633 guibg=#ccdc90
+hi StatusLineNC guifg=#2e3330 guibg=#88b090
+hi StorageClass guifg=#c3bf9f gui=bold
+hi String guifg=#cc9393
+hi Structure guifg=#efefaf gui=bold
+hi Tag guifg=#e89393 gui=bold
+hi Title guifg=#efefef gui=bold
+hi Todo guifg=#dfdfdf guibg=bg gui=bold
+hi Typedef guifg=#dfe4cf gui=bold
+hi Type guifg=#dfdfbf gui=bold
+hi Underlined guifg=#dcdccc gui=underline
+hi VertSplit guifg=#2e3330 guibg=#688060
+hi VisualNOS guifg=#333333 guibg=#f18c96 gui=bold,underline
+hi WarningMsg guifg=#ffffff guibg=#333333 gui=bold
+hi WildMenu guibg=#2c302d guifg=#cbecd0 gui=underline
+
+if v:version >= 700
+ hi SpellBad guisp=#bc6c4c guifg=#dc8c6c
+ hi SpellCap guisp=#6c6c9c guifg=#8c8cbc
+ hi SpellRare guisp=#bc6c9c guifg=#bc8cbc
+ hi SpellLocal guisp=#7cac7c guifg=#9ccc9c
+endif
+
+" Entering Kurt zone
+if &t_Co > 255
+ hi Boolean ctermfg=181
+ hi Character ctermfg=181 cterm=bold
+ hi Comment ctermfg=108
+ hi Conditional ctermfg=223 cterm=bold
+ hi Constant ctermfg=181 cterm=bold
+ hi Cursor ctermfg=233 ctermbg=109 cterm=bold
+ hi Debug ctermfg=181 cterm=bold
+ hi Define ctermfg=223 cterm=bold
+ hi Delimiter ctermfg=245
+ hi DiffAdd ctermfg=66 ctermbg=237 cterm=bold
+ hi DiffChange ctermbg=236
+ hi DiffDelete ctermfg=236 ctermbg=238
+ hi DiffText ctermfg=217 ctermbg=237 cterm=bold
+ hi Directory ctermfg=188 cterm=bold
+ hi ErrorMsg ctermfg=115 ctermbg=236 cterm=bold
+ hi Exception ctermfg=249 cterm=bold
+ hi Float ctermfg=251
+ hi FoldColumn ctermfg=109 ctermbg=238
+ hi Folded ctermfg=109 ctermbg=238
+ hi Function ctermfg=228
+ hi Identifier ctermfg=223
+ hi IncSearch ctermbg=228 ctermfg=238
+ hi Keyword ctermfg=223 cterm=bold
+ hi Label ctermfg=187 cterm=underline
+ hi LineNr ctermfg=248 ctermbg=235
+ hi Macro ctermfg=223 cterm=bold
+ hi ModeMsg ctermfg=223 cterm=none
+ hi MoreMsg ctermfg=15 cterm=bold
+ hi Number ctermfg=116
+ hi Operator ctermfg=230
+ hi PreCondit ctermfg=180 cterm=bold
+ hi PreProc ctermfg=223 cterm=bold
+ hi Question ctermfg=15 cterm=bold
+ hi Repeat ctermfg=223 cterm=bold
+ hi Search ctermfg=230 ctermbg=236
+ hi SpecialChar ctermfg=181 cterm=bold
+ hi SpecialComment ctermfg=108 cterm=bold
+ hi Special ctermfg=181
+ hi SpecialKey ctermfg=151
+ hi Statement ctermfg=187 ctermbg=234 cterm=none
+ hi StatusLine ctermfg=236 ctermbg=186
+ hi StatusLineNC ctermfg=235 ctermbg=108
+ hi StorageClass ctermfg=249 cterm=bold
+ hi String ctermfg=174
+ hi Structure ctermfg=229 cterm=bold
+ hi Tag ctermfg=181 cterm=bold
+ hi Title ctermfg=7 ctermbg=234 cterm=bold
+ hi Todo ctermfg=108 ctermbg=234 cterm=bold
+ hi Typedef ctermfg=253 cterm=bold
+ hi Type ctermfg=187 cterm=bold
+ hi Underlined ctermfg=188 ctermbg=234 cterm=bold
+ hi VertSplit ctermfg=236 ctermbg=65
+ hi VisualNOS ctermfg=236 ctermbg=210 cterm=bold
+ hi WarningMsg ctermfg=15 ctermbg=236 cterm=bold
+ hi WildMenu ctermbg=236 ctermfg=194 cterm=bold
+ hi CursorLine ctermbg=236 cterm=none
+
+ " spellchecking, always "bright" background
+ hi SpellLocal ctermfg=14 ctermbg=237
+ hi SpellBad ctermfg=9 ctermbg=237
+ hi SpellCap ctermfg=12 ctermbg=237
+ hi SpellRare ctermfg=13 ctermbg=237
+
+ " pmenu
+ hi PMenu ctermfg=248 ctermbg=0
+ hi PMenuSel ctermfg=223 ctermbg=235
+
+ if exists("g:zenburn_high_Contrast")
+ hi Normal ctermfg=188 ctermbg=234
+ hi NonText ctermfg=238
+
+ if exists("g:zenburn_color_also_Ignore")
+ hi Ignore ctermfg=238
+ endif
+ else
+ hi Normal ctermfg=188 ctermbg=237
+ hi Cursor ctermbg=109
+ hi diffadd ctermbg=237
+ hi diffdelete ctermbg=238
+ hi difftext ctermbg=237
+ hi errormsg ctermbg=237
+ hi foldcolumn ctermbg=238
+ hi folded ctermbg=238
+ hi incsearch ctermbg=228
+ hi linenr ctermbg=238
+ hi search ctermbg=238
+ hi statement ctermbg=237
+ hi statusline ctermbg=144
+ hi statuslinenc ctermbg=108
+ hi title ctermbg=237
+ hi todo ctermbg=237
+ hi underlined ctermbg=237
+ hi vertsplit ctermbg=65
+ hi visualnos ctermbg=210
+ hi warningmsg ctermbg=236
+ hi wildmenu ctermbg=236
+ hi NonText ctermfg=240
+
+ if exists("g:zenburn_color_also_Ignore")
+ hi Ignore ctermfg=240
+ endif
+ endif
+
+ if exists("g:zenburn_alternate_Error")
+ " use more jumpy Error
+ hi Error ctermfg=210 ctermbg=52 gui=bold
+ else
+ " default is something more zenburn-compatible
+ hi Error ctermfg=228 ctermbg=95 gui=bold
+ endif
+endif
+
+if exists("g:zenburn_force_dark_Background")
+ " Force dark background, because of a bug in VIM: VIM sets background
+ " automatically during "hi Normal ctermfg=X"; it misinterprets the high
+ " value (234 or 237 above) as a light color, and wrongly sets background to
+ " light. See ":help highlight" for details.
+ set background=dark
+endif
+
+if exists("g:zenburn_high_Contrast")
+ " use new darker background
+ hi Normal guifg=#dcdccc guibg=#1f1f1f
+ hi CursorLine guibg=#121212 gui=bold
+ hi Pmenu guibg=#242424 guifg=#ccccbc
+ hi PMenuSel guibg=#353a37 guifg=#ccdc90 gui=bold
+ hi PmenuSbar guibg=#2e3330 guifg=#000000
+ hi PMenuThumb guibg=#a0afa0 guifg=#040404
+ hi MatchParen guifg=#f0f0c0 guibg=#383838 gui=bold
+ hi SignColumn guifg=#9fafaf guibg=#181818 gui=bold
+ hi TabLineFill guifg=#cfcfaf guibg=#181818 gui=bold
+ hi TabLineSel guifg=#efefef guibg=#1c1c1b gui=bold
+ hi TabLine guifg=#b6bf98 guibg=#181818 gui=bold
+ hi CursorColumn guifg=#dcdccc guibg=#2b2b2b
+ hi NonText guifg=#404040 gui=bold
+else
+ " Original, lighter background
+ hi Normal guifg=#dcdccc guibg=#3f3f3f
+ hi CursorLine guibg=#434443
+ hi Pmenu guibg=#2c2e2e guifg=#9f9f9f
+ hi PMenuSel guibg=#242424 guifg=#d0d0a0 gui=bold
+ hi PmenuSbar guibg=#2e3330 guifg=#000000
+ hi PMenuThumb guibg=#a0afa0 guifg=#040404
+ hi MatchParen guifg=#b2b2a0 guibg=#2e2e2e gui=bold
+ hi SignColumn guifg=#9fafaf guibg=#343434 gui=bold
+ hi TabLineFill guifg=#cfcfaf guibg=#353535 gui=bold
+ hi TabLineSel guifg=#efefef guibg=#3a3a39 gui=bold
+ hi TabLine guifg=#b6bf98 guibg=#353535 gui=bold
+ hi CursorColumn guifg=#dcdccc guibg=#4f4f4f
+ hi NonText guifg=#5b605e gui=bold
+endif
+
+
+if exists("g:zenburn_alternate_Visual")
+ " Visual with more contrast, thanks to Steve Hall & Cream posse
+ " gui=none fixes weird highlight problem in at least GVim 7.0.66, thanks to Kurt Maier
+ hi Visual guifg=#000000 guibg=#71d3b4 gui=none
+ hi VisualNOS guifg=#000000 guibg=#71d3b4 gui=none
+else
+ " use default visual
+ hi Visual guifg=#233323 guibg=#71d3b4 gui=none
+ hi VisualNOS guifg=#233323 guibg=#71d3b4 gui=none
+endif
+
+if exists("g:zenburn_alternate_Error")
+ " use more jumpy Error
+ hi Error guifg=#e37170 guibg=#664040 gui=bold
+else
+ " default is something more zenburn-compatible
+ hi Error guifg=#e37170 guibg=#3d3535 gui=none
+endif
+
+if exists("g:zenburn_alternate_Include")
+ " original setting
+ hi Include guifg=#ffcfaf gui=bold
+else
+ " new, less contrasted one
+ hi Include guifg=#dfaf8f gui=bold
+endif
+
+if exists("g:zenburn_color_also_Ignore")
+ " color the Ignore groups
+ " note: if you get strange coloring for your files, turn this off (unlet)
+ hi Ignore guifg=#545a4f
+endif
+
+" TODO check for more obscure syntax groups that they're ok
diff --git a/vim/plugin/indentprefs.vim b/vim/plugin/indentprefs.vim
new file mode 100644
index 0000000..260963b
--- /dev/null
+++ b/vim/plugin/indentprefs.vim
@@ -0,0 +1,35 @@
+" Vim plugin for setting user preferences for indenting
+" Maintainer: Mike Miller <[email protected]>
+" Last Change: 2012-01-27
+" License: Vim License
+
+if &cp || exists("g:loaded_indentprefs_plugin")
+ finish
+endif
+let g:loaded_indentprefs_plugin = 1
+
+" Callable function to set user indentation preferences. Inspired by
+" Vim tip #83 at <http://vim.wikia.com/wiki/Indenting_source_code>.
+function SetBufferIndentationPreferences(cols, ...)
+ let l:option = a:0 ? a:1 : "default"
+ let l:undo_ftplugin = "setl et< sw< sts< ts<"
+ if l:option == "spaces"
+ setlocal expandtab
+ let &l:shiftwidth=a:cols
+ let &l:softtabstop=a:cols
+ setlocal tabstop&
+ elseif l:option == "tabs"
+ let &l:shiftwidth=a:cols
+ let &l:tabstop=a:cols
+ setlocal expandtab& softtabstop&
+ else
+ let &l:shiftwidth=a:cols
+ let &l:softtabstop=a:cols
+ setlocal expandtab& tabstop&
+ endif
+ if exists("b:undo_ftplugin")
+ let b:undo_ftplugin = b:undo_ftplugin . " | " . l:undo_ftplugin
+ else
+ let b:undo_ftplugin = l:undo_ftplugin
+ endif
+endfunc
diff --git a/vim/vimrc_normal.vim b/vim/vimrc_normal.vim
new file mode 100644
index 0000000..23ff956
--- /dev/null
+++ b/vim/vimrc_normal.vim
@@ -0,0 +1,160 @@
+" vimrc_normal.vim: executed by Vim from ~/.vimrc during initialization.
+"
+" Maintainer: Mike Miller
+" Original Author: Bram Moolenaar <[email protected]>
+" Last Change: 2012-03-12
+"
+" Install in the runtime path (e.g. ~/.vim) to be found by ~/.vimrc.
+" This file is sourced only for Vim normal, big, or huge.
+
+" When started as "evim", evim.vim will already have done these settings.
+if v:progname =~? "evim" || v:progname =~? "eview"
+ finish
+endif
+
+" Use Vim settings, rather than Vi settings (much better!).
+" This must be first, because it changes other options as a side effect.
+set nocompatible
+
+" allow backspacing over everything in insert mode
+set backspace=indent,eol,start
+
+if has("vms")
+ set nobackup " do not keep a backup file, use versions instead
+else
+ set backup " keep a backup file
+endif
+set history=50 " keep 50 lines of command line history
+set ruler " show the cursor position all the time
+set showcmd " display incomplete commands
+set incsearch " do incremental searching
+set shortmess+=I " don't display the Vim intro at startup
+set laststatus=2 " always show the status line
+set visualbell t_vb= " no beeping or visual bell whatsoever
+
+" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
+" so that you can undo CTRL-U after inserting a line break.
+inoremap <C-U> <C-G>u<C-U>
+
+" In many terminal emulators the mouse works just fine, thus enable it.
+if has('mouse')
+ set mouse=a
+endif
+
+" Extend the runtimepath using the pathogen plugin.
+" http://github.com/tpope/vim-pathogen
+let s:pluginpath = 'pathogen#'
+if v:version >= 700
+ call {s:pluginpath}infect()
+ call {s:pluginpath}helptags()
+endif
+
+" Shortcut to display/hide the NERDTree window. Needs to be done after Vim is
+" done initializing.
+augroup vimInitCommands
+au!
+autocmd VimEnter *
+ \ if exists(":NERDTreeToggle") |
+ \ map <Leader>d :NERDTreeToggle<CR> |
+ \ endif
+augroup END
+
+" Switch syntax highlighting on, when the terminal has colors
+" Also switch on highlighting the last used search pattern.
+if &t_Co > 2 || has("gui_running")
+ syntax on
+ set hlsearch
+endif
+
+" Only do this part when compiled with support for autocommands.
+if has("autocmd")
+
+ " Enable file type detection.
+ " Use the default filetype settings, so that mail gets 'tw' set to 72,
+ " 'cindent' is on in C files, etc.
+ " Also load indent files, to automatically do language-dependent indenting.
+ filetype plugin indent on
+
+ " Put these in an autocmd group, so that we can delete them easily.
+ augroup vimrcNormal
+ au!
+
+ " For all text files set 'textwidth' to 78 characters.
+ autocmd FileType text setlocal textwidth=78
+
+ " When editing a file, always jump to the last known cursor position.
+ " Don't do it when the position is invalid or when inside an event handler
+ " (happens when dropping a file on gvim).
+ " Also don't do it when the mark is in the first line, that is the default
+ " position when opening a file.
+ autocmd BufReadPost *
+ \ if line("'\"") > 1 && line("'\"") <= line("$") |
+ \ exe "normal! g`\"" |
+ \ endif
+
+ augroup END
+
+else
+
+ set autoindent " always set autoindenting on
+
+endif " has("autocmd")
+
+" Convenient command to see the difference between the current buffer and the
+" file it was loaded from, thus the changes you made.
+" Only define it when not defined already.
+if !exists(":DiffOrig")
+ command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
+ \ | wincmd p | diffthis
+endif
+
+" Prefer a dark background on terminal emulators.
+if &term =~ "^xterm"
+ set background=dark
+ set t_Co=16
+endif
+
+" User customizations for syntax highlighting.
+if has("syntax")
+ let g:is_posix = 1
+ if v:version < 700
+ let g:is_kornshell = 1
+ endif
+ let g:fortran_fixed_source = 1
+ let g:fortran_have_tabs = 1
+endif
+
+" Settings specific to using the GUI.
+if has("gui")
+
+ " Fonts to use in gvim. Always have fallbacks, and handle each platform in
+ " its own special way, see :help setting-guifont.
+ if has("gui_gtk2")
+ set guifont=Liberation\ Mono\ 10,Monospace\ 10
+ elseif has("x11")
+ set guifont=-*-lucidatypewriter-medium-r-normal-*-*-120-*-*-m-*-*
+ elseif has("gui_win32")
+ set guifont=Lucida_Console:h9:cANSI,Courier_New:h9:cANSI,Terminal:h9
+ endif
+
+ " GUI customizations. No blinking cursor, no tearoffs, no toolbar.
+ set guicursor=a:blinkon0
+ set guioptions-=tT
+
+ " The following settings must be done when the GUI starts.
+ augroup guiInitCommands
+ au!
+
+ " Load my favorite color scheme by default.
+ autocmd GUIEnter * colorscheme zenburn
+
+ " Override default less options for a chance of working in the GUI
+ " (e.g. :shell command or man page lookup)
+ autocmd GUIEnter * let $LESS = $LESS . 'dr'
+
+ " Turn off visual bell feedback, needs to be done after the GUI starts.
+ autocmd GUIEnter * set t_vb=
+
+ augroup END
+
+endif
diff --git a/vimrc b/vimrc
new file mode 100644
index 0000000..074afb5
--- /dev/null
+++ b/vimrc
@@ -0,0 +1,54 @@
+" ~/.vimrc: initialize Vim to behave like Vim or vi depending on the
+" compiled-in feature set and how it is invoked.
+"
+" Copyright (C) 2011 Mike Miller
+" License: GPL-3+
+"
+" Intended behavior:
+" - If Vim is tiny or small, configure like vi.
+" - If Vim is invoked as ex, vi, or view, configure like vi.
+" - Otherwise, bootstrap vimrc_normal.vim to configure Vim.
+"
+" First fix some things that may be inherited from buggy system vimrc
+" configuration files, for either Vim or vi.
+" - Restore the default file character encoding list, see :help fencs.
+if v:lang =~ 'utf8$' || v:lang =~ 'UTF-8$'
+ set fileencodings=ucs-bom,utf-8,default,latin1
+endif
+" - Remove unwanted and just plain broken autocommands (sorry, Red Hat).
+if has('autocmd')
+ augroup fedora
+ autocmd!
+ augroup! fedora
+ augroup redhat
+ autocmd!
+ augroup! redhat
+ augroup END
+ autocmd!
+endif
+" If the command name is not ex, vi, or view, turn control over to
+" vimrc_normal.vim. If Vim is compiled with the tiny or small set of
+" features, the if..endif will be skipped over as well.
+if v:progname != 'ex' && v:progname !~ '^vi\(ew\)\?$'
+ runtime vimrc_normal.vim
+ finish
+endif
+" If this file is still sourcing, Vim is tiny or small or is invoked as
+" ex, vi, or view.
+" - Turn off automatic file type detection.
+if has('autocmd')
+ filetype off
+ filetype plugin indent off
+endif
+" - Turn off syntax highlighting.
+if has('syntax')
+ syntax off
+endif
+" - Set/reset editor options for vi compatibility.
+set compatible " Revert to vi-compatible mode.
+set cpoptions+={\|&/\\. " Enable POSIX vi compatibility.
+set cedit& viminfo& " Clear options not reset by above.
+set noloadplugins " Disable startup loading of plugins.
+set shortmess+=I " Disable Vim splash screen.
+set t_AB= t_AF= t_Sb= t_Sf= " Disable terminal color escape codes.
+source $HOME/.exrc " Execute commands from ~/.exrc.
|
monde/mms2r
|
4b4419580a1eccb55cc1862795d926852d4554bd
|
md formatting
|
diff --git a/README.md b/README.md
index 9979230..6c6f37e 100644
--- a/README.md
+++ b/README.md
@@ -1,227 +1,227 @@
# mms2r
https://github.com/monde/mms2r
## DESCRIPTION
MMS2R by Mike Mondragon
* https://github.com/monde/mms2r
* https://rubygems.org/gems/mms2r
* http://peepcode.com/products/mms2r-pdf
MMS2R is a library that decodes the parts of a MMS message to disk while
stripping out advertising injected by the mobile carriers. MMS messages are
multipart email and the carriers often inject branding into these messages. Use
MMS2R if you want to get at the real user generated content from a MMS without
having to deal with the cruft from the carriers.
If MMS2R is not aware of a particular carrier no extra processing is done to the
MMS other than decoding and consolidating its media.
MMS2R can be used to process any multipart email to conveniently access the
parts the mail is comprised of.
Contact the author to add additional carriers to be processed by the library.
Suggestions and patches appreciated and welcomed!
[](http://tip4commit.com/projects/198)
### Corpus of carriers currently processed by MMS2R:
* 1nbox/Idea: 1nbox.net
* 3 Ireland: mms.3ireland.ie
* Alltel: mms.alltel.com
* AT&T/Cingular/Legacy: mms.att.net, mm.att.net, txt.att.net, mmode.com, mms.mycingular.com, cingularme.com, mobile.mycingular.com pics.cingularme.com
* Bell Canada: txt.bell.ca
* Bell South / Suncom / SBC Global: bellsouth.net, sbcglobal.net
* Cricket Wireless: mms.mycricket.com
* Dobson/Cellular One: mms.dobson.net
* Helio: mms.myhelio.com
* Hutchison 3G UK Ltd: mms.three.co.uk
* INDOSAT M2: mobile.indosat.net.id
* LUXGSM S.A.: mms.luxgsm.lu
* Maroc Telecom / mms.mobileiam.ma
* MTM South Africa: mms.mtn.co.za
* NetCom (Norway): mms.netcom.no
* Nextel: messaging.nextel.com
* O2 Germany: mms.o2online.de
* O2 UK: mediamessaging.o2.co.uk
* Orange & Regional Oranges: orangemms.net, mmsemail.orange.pl, orange.fr
* PLSPICTURES.COM mms hosting: waw.plspictures.com
* PXT New Zealand: pxt.vodafone.net.nz
* Rogers of Canada: rci.rogers.com
* SaskTel: sasktel.com, sms.sasktel.com, cdma.sasktel.com
* Sprint: pm.sprint.com, messaging.sprintpcs.com, sprintpcs.com
* T-Mobile: tmomail.net, mmsreply.t-mobile.co.uk, tmo.blackberry.net
* TELUS Corporation (Canada): mms.telusmobility.com, msg.telus.com
* U.S. Cellular: mms.uscc.net
* UAE MMS: mms.ae
* Unicel: unicel.com, info2go.com (note: mobile number is tucked away in a text/plain part for unicel.com)
* Verizon: vzwpix.com, vtext.com, labwig.net
* Virgin Mobile: vmpix.com, pixmbl.com, vmobl.com, yrmobl.com
* Virgin Mobile of Canada: vmobile.ca
* Vodacom: mms.vodacom4me.co.za
* Cincinnati Bell: mms.gocbw.com
### Corpus of smart phones known to MMS2R:
* Apple iPhone variants
* Blackberry / Research In Motion variants
* Casio variants
* Droid variants
* Google / Nexus One variants
* HTC variants (T-Mobile Dash, Sprint HERO)
* LG Electronics variants
* Motorola variants
* Pantech variants
* Qualcom variants
* Samsung variants
* Sprint variants
* UTStarCom variants
### As Seen On The Internets - sites known to be using MMS2R in some fashion
* twitpic.com - http://www.twitpic.com/
* Simplton - http://simplton.com/
* fanchatter.com - http://www.fanchatter.com/
-* camura.com - [http://www.camura.com/
-* eachday.com - [http://www.eachday.com/
-* beenup2.com - [http://www.beenup2.com/
-* snapmylife.com - [http://www.snapmylife.com/
+* camura.com - http://www.camura.com/
+* eachday.com - http://www.eachday.com/
+* beenup2.com - http://www.beenup2.com/
+* snapmylife.com - http://www.snapmylife.com/
* email the author to be listed here
## FEATURES
* #default_media and #default_text methods return a File that can be used in attachment_fu or Paperclip
* #process supports blocks for enumerating over the content of the MMS
* #process can be made lazy when :process => :lazy is passed to new
* logging is enabled when :logger => your_logger is passed to new
* an mms instance acts like a Mail object, any methods not defined on the instance are delegated to it's underlying Mail object
* #device_type? returns a symbol representing a device or smartphone type. Known smartphones thus far: iPhone, BlackBerry, T-Mobile Dash, Droid, Samsung
## BOOKS
MMS2R, Making email useful
http://peepcode.com/products/mms2r-pdf
## SYNOPSIS
```ruby
begin
require 'mms2r'
rescue LoadError
require 'rubygems'
require 'mms2r'
end
# required for the example
require 'fileutils'
mail = MMS2R::Media.new(Mail.read('some_saved_mail.file'))
puts "mail has default carrier subject" if mail.subject.empty?
# access the sender's phone number
puts "mail was from phone #{mail.number}"
# most mail are either image or video, default_media will return the largest
# (non-advertising) video or image found
file = mail.default_media
puts "mail had a media: #{file.inspect}" unless file.nil?
# finds the largest (non-advertising) text found
file = mail.default_text
puts "mail had some text: #{file.inspect}" unless file.nil?
# mail.media is a hash that is indexed by mime-type.
# The mime-type key returns an array of filepaths
# to media that were extract from the mail and
# are of that type
mail.media['image/jpeg'].each {|f| puts "#{f}"}
mail.media['text/plain'].each {|f| puts "#{f}"}
# print the text (assumes mail had text)
text = IO.readlines(mail.media['text/plain'].first).join
puts text
# save the image (assumes mail had a jpeg)
FileUtils.cp mail.media['image/jpeg'].first, '/some/where/useful', :verbose => true
puts "does the mail have quicktime video? #{!mail.media['video/quicktime'].nil?}"
puts "plus run anything that Mail provides, e.g. #{mail.to.inspect}"
# check if the mail is from a mobile phone
puts "mail is from a mobile phone #{mail.is_mobile?}"
# determine the device type of the phone
puts "mail is from a mobile phone of type #{mail.device_type?}"
# inspect default media's exif data if exifr gem is installed and default
# media is a jpeg or tiff
puts "mail's default media's exif data is:"
puts mail.exif.inspect
# Block support, process and receive all media types of video.
mail.process do |media_type, files|
# assumes a Clip model that is an AttachmentFu
Clip.create(:uploaded_data => files.first, :title => "From phone") if media_type =~ /video/
end
# Another AttachmentFu example, Picture model is an AttachmentFu
picture = Picture.new
picture.title = mail.subject
picture.uploaded_data = mail.default_media
picture.save!
#remove all the media that was put to temporary disk
mail.purge
```
## REQUIREMENTS
* Mail (mail)
* Nokogiri (nokogiri)
* UUIDTools (uuidtools)
* EXIF Reader (exif)
## INSTALL
```
sudo gem install mms2r
```
## SOURCE
```
git clone git://github.com/monde/mms2r.git
```
## AUTHORS
Copyright (c) 2007-2012 by Mike Mondragon blog http://plasti.cx/
MMS2R's Flickr page http://www.flickr.com/photos/8627919@N05/
## CONTRIBUTORS
* Luke Francl - http://railspikes.com/
* Will Jessup - http://www.willjessup.com/
* Shane Vitarana - http://www.shanesbrain.net/
* Layton Wedgeworth - http://www.beenup2.com/
* Jason Haruska - http://software.haruska.com/
* Dave Myron - http://contentfree.com/
* Vijay Yellapragada
* Jesse Dp - http://github.com/jessedp
* David Alm
* Jeremy Wilkins
* Matt Conway - http://github.com/wr0ngway
* Kai Kai
* Michael DelGaudio
* Sai Emrys - http://saizai.com/
* Brendan Lim - http://github.com/brendanlim
* Scott Taylor - http://github.com/smtlaissezfaire
* Jaap van der Meer - http://github.com/japetheape
* Karl Baum - http://github.com/kbaum
* James McGrath - http://jamespmcgrath.com/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.