Permalink
Browse files

py3k: Use print function instead of statement.

  • Loading branch information...
QuLogic committed May 13, 2015
1 parent dd02fcc commit 7b8e0dc580f377e9415c1727633f10634bbca53f
View
@@ -1,3 +1,5 @@
from __future__ import print_function
from numpy import dtype
import tables
import re
@@ -10,7 +12,7 @@ def table_copy(source,dest,names=None,omit=[],verbose=1):
names = names.split()
for name in names:
a = source.getNode("/"+name)
if verbose: print "[copying",name,a.shape,a.atom,"]"
if verbose: print("[copying", name, a.shape, a.atom, "]")
if "VLArray" in str(a):
b = dest.createVLArray(dest.root,name,a.atom,filters=tables.Filters(9))
else:
@@ -28,7 +30,7 @@ def assign_array(db,name,a,verbose=1):
atom = tables.Float32Atom()
else:
raise Exception('unknown array type: %s'%a.dtype)
if verbose: print "[writing",name,a.shape,atom,"]"
if verbose: print("[writing", name, a.shape, atom, "]")
node = db.createEArray(db.root,name,atom,shape=[0]+list(a.shape[1:]),filters=tables.Filters(9))
node.append(a)
View
@@ -1,6 +1,8 @@
# TODO:
# - handle UTF-8 inputs correctly
from __future__ import print_function
from pylab import *
from collections import Counter,defaultdict
import re
@@ -47,7 +49,7 @@ def safe_readlines(stream,nonl=0):
try:
line = stream.readline()
except UnicodeDecodeError as e:
if not once: print lineno,":",e
if not once: print(lineno, ":", e)
once = 1
return
if line is None: return
@@ -75,14 +77,14 @@ def computeNGraphs(self,fnames,n):
lineskip = 0
linelimit = 2000
for fnum,fname in enumerate(fnames):
print fnum,"of",len(fnames),":",fname
print(fnum, "of", len(fnames), ":", fname)
if fname.startswith("lineskip="):
lineskip = int(fname.split("=")[1])
print "changing lineskip to",lineskip
print("changing lineskip to", lineskip)
continue
if fname.startswith("linelimit="):
linelimit = int(fname.split("=")[1])
print "changing linelimit to",linelimit
print("changing linelimit to", linelimit)
continue
with codecs.open(fname,"r","utf-8") as stream:
for lineno,line in enumerate(safe_readlines(stream)):
@@ -106,11 +108,11 @@ def __init__(self,*args,**kw):
NGraphsCounts.__init__(self,*args,**kw)
def buildFromFiles(self,fnames,n):
"""Given a set of files, build the log posteriors."""
print "reading",len(fnames),"files"
print("reading", len(fnames), "files")
counter = self.computeNGraphs(fnames,n)
print "got",sum(counter.values()),"%d-graphs"%(n,)
print("got", sum(counter.values()), "%d-graphs" % (n, ))
self.computePosteriors(counter)
print "done building lposteriors"
print("done building lposteriors")
def computePosteriors(self,counter):
"""Given a `counter` of all n-graphs, compute
(log) conditional probabilities."""
@@ -21,6 +21,8 @@
"cell_type": "code",
"collapsed": false,
"input": [
"from future import print_function\n",
"\n",
"from pylab import *\n",
"import os.path\n",
"import glob\n",
@@ -60,7 +62,7 @@
"cell_type": "code",
"collapsed": false,
"input": [
"print \"c_lstm\"\n",
"print(\"c_lstm\")\n",
"clstm = lstm_c.C_LSTM(Ni,Ns,No)\n",
"llayer = rnnscript.as_lstm2(clstm.net.hiddenLayers[0])\n",
"clstm.setLearningRate(1e-4,0.9)\n",
@@ -72,7 +74,7 @@
" err = sum((a-ys)**2)**.5\n",
" errs.append(err)\n",
" if i%10000==0:\n",
" print i,mean(errs[-1000:])\n",
" print(i, mean(errs[-1000:]))\n",
" s = clstm.states()\n",
" clf()\n",
" subplot(121);\n",
@@ -83,7 +85,7 @@
" draw()\n",
"\n",
"test_xs,test_ys = genseq()\n",
"print \"done\""
"print(\"done\")"
],
"language": "python",
"metadata": {},
@@ -221,7 +223,7 @@
"plot(deltas3,color='green',linestyle='dashed')\n",
"deltas4 = -array(before.nets[1].dzspre)\n",
"plot(deltas4,color='black',linestyle='dashed')\n",
"print deltas4.shape"
"print(deltas4.shape)"
],
"language": "python",
"metadata": {},
@@ -289,12 +291,12 @@
"clstm.ctrain(xs,ys,update=0)\n",
"h2o.debug = False\n",
"b2o.debug = False\n",
"print\n",
"print array(h2o.dinputs).reshape(3,2)\n",
"print array(h2o.dweights).reshape(3,2)\n",
"print\n",
"print array(b2o.dinputs).reshape(3)\n",
"print array(b2o.dweights).reshape(3)"
"print()\n",
"print(array(h2o.dinputs).reshape(3, 2))\n",
"print(array(h2o.dweights).reshape(3, 2))\n",
"print()\n",
"print(array(b2o.dinputs).reshape(3))\n",
"print(array(b2o.dweights).reshape(3))"
],
"language": "python",
"metadata": {},
@@ -364,4 +366,4 @@
"metadata": {}
}
]
}
}
View
@@ -3,6 +3,8 @@
### common functions for data structures, file name manipulation, etc.
################################################################
from __future__ import print_function
import os
import os.path
import re
@@ -96,7 +98,7 @@ def _wrap(f):
warned = 0
def _wrapper(*args,**kw):
if not warned:
print f,"has been DEPRECATED"
print(f, "has been DEPRECATED")
warned = 1
return f(*args,**kw)
return _wrap
@@ -248,7 +250,7 @@ def write_image_gray(fname,image,normalize=0,verbose=0):
type, its values are clipped to the range [0,1],
multiplied by 255 and converted to unsigned bytes. Otherwise,
the image must be of type unsigned byte."""
if verbose: print "# writing",fname
if verbose: print("# writing", fname)
if isfloatarray(image):
image = array(255*clip(image,0.0,1.0),'B')
assert image.dtype==dtype('B'),"array has wrong dtype: %s"%image.dtype
@@ -271,7 +273,7 @@ def write_image_binary(fname,image,verbose=0):
"""Write a binary image to disk. This verifies first that the given image
is, in fact, binary. The image may be of any type, but must consist of only
two values."""
if verbose: print "# writing",fname
if verbose: print("# writing", fname)
assert image.ndim==2
image = array(255*(image>midrange(image)),'B')
im = array2pil(image)
@@ -428,7 +430,7 @@ def bbox(self,i):
"""Return the bounding box in raster coordinates
(row0,col0,row1,col1)."""
r = self.objects[i]
# print "@@@bbox",i,r
# print("@@@bbox", i, r)
return (r[0].start,r[1].start,r[0].stop,r[1].stop)
def bboxMath(self,i):
"""Return the bounding box in math coordinates
@@ -442,7 +444,7 @@ def length(self):
def mask(self,index,margin=0):
"""Return the mask for component index."""
b = self.objects[index]
#print "@@@mask",index,b
# print("@@@mask", index, b)
m = self.labels[b]
m[m!=index] = 0
if margin>0: m = pad_by(m,margin)
@@ -499,7 +501,7 @@ class names that have changed."""
if not nofind:
fname = ocropus_find_file(fname)
if verbose:
print "# loading object",fname
print("# loading object", fname)
if zip==0 and fname.endswith(".gz"):
zip = 1
if zip>0:
@@ -833,7 +835,7 @@ def pyconstruct(s):
path = s[:s.find("(")]
if "." in path:
module = path[:path.rfind(".")]
print "import",module
print("import", module)
exec "import "+module in env
return eval(s,env)
@@ -890,15 +892,15 @@ def save_component(file,object,verbose=0,verify=0):
ocropus.save_component(file,object)
return
if verbose:
print "[save_component]"
print("[save_component]")
if verbose:
for k,v in object.__dict__.items():
print ":",k,obinfo(v)
print(":", k, obinfo(v))
with open(file,"wb") as stream:
pickle.dump(object,stream,pickle_mode)
if verify:
if verbose:
print "[trying to read it again]"
print("[trying to read it again]")
with open(file,"rb") as stream:
pickle.load(stream)
View
@@ -72,8 +72,8 @@ def xlevenshtein(a,b,context=1):
same = filters.minimum_filter(same,1+2*context)
als = "".join([al[i] if not same[i] else "~" for i in range(len(al))])
bls = "".join([bl[i] if not same[i] else "~" for i in range(len(bl))])
# print als
# print bls
# print(als)
# print(bls)
ags = re.split(r'~+',als)
bgs = re.split(r'~+',bls)
confusions = [(a,b) for a,b in zip(ags,bgs) if a!="" or b!=""]
View
@@ -2,6 +2,8 @@
### text image generation with Cairo
################################################################
from __future__ import print_function
import ctypes
import cairo
from cairoextras import *
@@ -104,7 +106,7 @@ def pango_render_string(s,spec=None,fontfile=None,size=None,bg=(0.0,0.0,0.0),fg=
else:
layout.set_markup(s)
((xbear,ybear,tw,th),_) = layout.get_pixel_extents()
# print xbear,ybear,tw,th
# print(xbear, ybear, tw, th)
tw = tw+2*pad
th = th+2*pad
if tw<=w and th<=h: break
@@ -160,12 +162,12 @@ def gauss_distort(images,maxdelta=2.0,sigma=10.0):
deltas /= max(amax(deltas),-amin(deltas))
deltas *= maxdelta
xy = transpose(array(meshgrid(range(n),range(m))),axes=[0,2,1])
# print xy.shape,deltas.shape
# print(xy.shape, deltas.shape)
deltas += xy
return [map_coordinates(image,deltas,order=1) for image in images]
if __name__=="__main__":
# print sorted(pango_families())
# print(sorted(pango_families()))
ion()
show()
while 1:
View
@@ -3,6 +3,8 @@
# Source: http://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/
# Author: Raymond Hettinger
from __future__ import print_function
import collections
import functools
from itertools import ifilterfalse
View
@@ -1,3 +1,5 @@
from __future__ import print_function
import sys
import os
import re
@@ -21,7 +23,7 @@ def __init__(self,target_height=48,params=(4,1.0,0.3)):
self.debug = int(os.getenv("debug_center") or "0")
self.target_height = target_height
self.range,self.smoothness,self.extra = params
print "# CenterNormalizer"
print("# CenterNormalizer")
def setHeight(self,target_height):
self.target_height = target_height
def measure(self,line):
View
@@ -24,6 +24,8 @@
# Author: Thomas M. Breuel
# License: Apache 2.0
from __future__ import print_function
import common as ocrolib
from pylab import *
from collections import defaultdict
@@ -223,7 +225,7 @@ def update(self):
ds.ravel()[:] = self.momentum * ds.ravel()[:] + self.learning_rate * dw.ravel()[:]
w.ravel()[:] += ds.ravel()[:]
if self.verbose:
print n,(amin(w),amax(w)),(amin(dw),amax(dw))
print(n, (amin(w), amax(w)), (amin(dw), amax(dw)))
''' The following are subclass responsibility:
@@ -281,7 +283,7 @@ def info(self):
vars = sorted("W2".split())
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def weights(self):
yield self.W2,self.DW2,"Logreg"
@@ -325,7 +327,7 @@ def info(self):
vars = sorted("W2".split())
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def weights(self):
yield self.W2,self.DW2,"Softmax"
@@ -514,7 +516,7 @@ def info(self):
vars = sorted(vars)
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def preSave(self):
self.max_n = max(500,len(self.ci))
self.allocate(1)
View
@@ -2,6 +2,8 @@
### various add-ons to the SciPy morphology package
################################################################
from __future__ import print_function
from numpy import *
import pylab
from pylab import *
@@ -198,9 +200,9 @@ def select_regions(binary,f,min=0,nbest=100000):
for i in best[-nbest:]:
if scores[i]<=min: continue
keep[i+1] = 1
# print scores,best[-nbest:],keep
# print sorted(list(set(labels.ravel())))
# print sorted(list(set(keep[labels].ravel())))
# print(scores, best[-nbest:], keep)
# print(sorted(list(set(labels.ravel()))))
# print(sorted(list(set(keep[labels].ravel()))))
return keep[labels]
@checks(SEGMENTATION)
Oops, something went wrong.

0 comments on commit 7b8e0dc

Please sign in to comment.