From 8228b432074af15a64ebb23920030eebdcee646b Mon Sep 17 00:00:00 2001 From: piernov Date: Sat, 28 Feb 2015 22:37:59 +0100 Subject: Fix lamda and has_key() syntax --- jm2l/captcha.py.orig | 151 -------------------------------------------- jm2l/templates/helpers.mako | 12 ++-- jm2l/views.py | 32 +++++----- 3 files changed, 22 insertions(+), 173 deletions(-) delete mode 100644 jm2l/captcha.py.orig diff --git a/jm2l/captcha.py.orig b/jm2l/captcha.py.orig deleted file mode 100644 index 8ec778f..0000000 --- a/jm2l/captcha.py.orig +++ /dev/null @@ -1,151 +0,0 @@ -# Stolen from tgcaptcha/plugins -# http://code.google.com/p/tgcaptcha/source/browse/trunk/tgcaptcha/plugins/image/vanasco_dowty/captcha.py - -import random -from PIL import Image, ImageDraw, ImageFont, ImageFilter -from io import BytesIO -import math -from pyramid.view import view_config -from .words import TabMots -from pyramid.response import Response - -class Captcha_Img(object): - def __init__( self, width, height): - self.width = width - self.height = height - self._layers = [ - _PyCaptcha_SineWarp(amplitudeRange = (4, 8) , periodRange=(0.65,0.73) ), - ] - - def getImg(self): - """Get a PIL image representing this CAPTCHA test, creating it if necessary""" - if not self._image: - self._image = self.render() - return self._image - - def render(self): - """Render this CAPTCHA, returning a PIL image""" - size = (self.width,self.height) - #img = Image.new("RGB", size ) - img = self._image - for layer in self._layers: - img = layer.render( img ) or img - self._image = img - return self._image - -class _PyCaptcha_WarpBase(object): - """Abstract base class for image warping. Subclasses define a - function that maps points in the output image to points in the input image. - This warping engine runs a grid of points through this transform and uses - PIL's mesh transform to warp the image. - """ - filtering = Image.BILINEAR - resolution = 40 - - def get_transform(self, image): - """Return a transformation function, subclasses should override this""" - return lambda x, y: (x, y) - - def render(self, image): - r = self.resolution - xPoints = image.size[0] // r + 2 - yPoints = image.size[1] // r + 2 - f = self.get_transform(image) - - # Create a list of arrays with transformed points - xRows = [] - yRows = [] - for j in xrange(yPoints): - xRow = [] - yRow = [] - for i in xrange(xPoints): - x, y = f(i*r, j*r) - - # Clamp the edges so we don't get black undefined areas - x = max(0, min(image.size[0]-1, x)) - y = max(0, min(image.size[1]-1, y)) - - xRow.append(x) - yRow.append(y) - xRows.append(xRow) - yRows.append(yRow) - - # Create the mesh list, with a transformation for - # each square between points on the grid - mesh = [] - for j in xrange(yPoints-1): - for i in xrange(xPoints-1): - mesh.append(( - # Destination rectangle - (i*r, j*r, - (i+1)*r, (j+1)*r), - # Source quadrilateral - (xRows[j ][i ], yRows[j ][i ], - xRows[j+1][i ], yRows[j+1][i ], - xRows[j+1][i+1], yRows[j+1][i+1], - xRows[j ][i+1], yRows[j ][i+1]), - )) - - return image.transform(image.size, Image.MESH, mesh, self.filtering) - -class _PyCaptcha_SineWarp(_PyCaptcha_WarpBase): - """Warp the image using a random composition of sine waves""" - - def __init__(self, - amplitudeRange = (1,1),#(2, 6), - periodRange = (1,1)#(0.65, 0.73), - ): - self.amplitude = random.uniform(*amplitudeRange) - self.period = random.uniform(*periodRange) - self.offset = (random.uniform(0, math.pi * 2 / self.period), - random.uniform(0, math.pi * 2 / self.period)) - - def get_transform(self, image): - return (lambda x, y, - a = self.amplitude, - p = self.period, - o = self.offset: - (math.sin( (y+o[0])*p )*a + x, - math.sin( (x+o[1])*p )*a + y)) - -@view_config(route_name='captcha') -def DoCaptcha(request): - ImgSize = (230,100) - WorkImg = Image.new( 'RGBA', ImgSize, (255, 255, 255, 0) ) - Xmax, Ymax = WorkImg.size - # Write something on it - draw = ImageDraw.Draw(WorkImg) - - # use a truetype font - #font = ImageFont.truetype("/var/lib/defoma/gs.d/dirs/fonts/LiberationMono-Regular.ttf", 40) - # use it - font = ImageFont.truetype("jm2l/static/fonts/LiberationMono-Regular.ttf",40) - # Re-position - # Choose a word for captcha - text = random.choice(TabMots) - Xt, Yt = font.getsize(text) - OrX, OrY = (ImgSize[0]-Xt)//2, (ImgSize[1]-Yt)//2 - draw.text((OrX, OrY), text, font=font, fill="#000000") - # Apply a Blur - # WorkImg=WorkImg.filter(ImageFilter.BLUR) - # Apply a DETAIL - WorkImg=WorkImg.filter(ImageFilter.DETAIL) - # randomize parameters for perspective - ax, ay = (random.uniform(0.9,1.2) , random.uniform(0.9,1.2)) - tx, ty = (random.uniform(0,0.0003),random.uniform(0,0.0003)) - bx, by = (random.uniform(0.5,0.8),random.uniform(0,0.2)) - # Apply perspective to Captcha - WorkImg= WorkImg.transform(ImgSize, Image.PERSPECTIVE, (ax, bx, -25, by, ay, -10, tx, ty)) - # Apply SinWarp to Captcha - tr = Captcha_Img(Xmax, Ymax) - tr._image = WorkImg - WorkImg = tr.render() - # Apply a Smooth on it - WorkImg=WorkImg.filter(random.choice([ImageFilter.SMOOTH, ImageFilter.SMOOTH_MORE])) - # Save Result - request.session['Captcha'] = text - #session.save() - ImgHandle = BytesIO() - WorkImg.save(ImgHandle,'png') - ImgHandle.seek(0) - return Response(app_iter=ImgHandle, content_type = 'image/png') diff --git a/jm2l/templates/helpers.mako b/jm2l/templates/helpers.mako index d02f12c..0f7007f 100644 --- a/jm2l/templates/helpers.mako +++ b/jm2l/templates/helpers.mako @@ -6,7 +6,7 @@ TabJs = {'select':[], 'desc':[]} %> % for FieldName, Field in form._fields.items(): - % if DicFormat.has_key(Field.name) and DicFormat[Field.name].get("Ignore"): + % if Field.name in DicFormat and DicFormat[Field.name].get("Ignore"): <% continue %> % endif % if Field.type in ['HiddenField', 'CSRFTokenField']: @@ -15,11 +15,11 @@ TabJs = {'select':[], 'desc':[]} % elif Field.type=="SelectField": <% TabJs['select'].append(Field.label.field_id) %> % endif -% if DicFormat.has_key(Field.name) and DicFormat[Field.name].get("fieldset"): +% if Field.name in DicFormat and DicFormat[Field.name].get("fieldset"):
${Field.label.text} % else: - % if DicFormat.has_key(Field.name) and DicFormat[Field.name].get("ContainerStyle"): + % if Field.name in DicFormat and DicFormat[Field.name].get("ContainerStyle"):
% else:
@@ -35,11 +35,11 @@ TabJs = {'select':[], 'desc':[]} % endif % endif - % if DicFormat.has_key(Field.name): + % if Field.name in DicFormat: <% PlaceHolder = DicFormat[Field.name].get("PlaceHolder") FieldStyle = DicFormat[Field.name].get("FieldStyle") - Class = [None,"ckeditor"][ DicFormat[Field.name].has_key("ckeditor") ] + Class = [None,"ckeditor"][ "ckeditor" in DicFormat[Field.name] ] %> % if PlaceHolder: ${Field(placeholder=PlaceHolder, style=FieldStyle, class_=Class)} @@ -56,7 +56,7 @@ TabJs = {'select':[], 'desc':[]} ${ error }
% endfor -% if DicFormat.has_key(Field.name) and DicFormat[Field.name].get("fieldset"): +% if Field.name in DicFormat and DicFormat[Field.name].get("fieldset"):
% else: diff --git a/jm2l/views.py b/jm2l/views.py index f5dc1b3..32ee9a5 100644 --- a/jm2l/views.py +++ b/jm2l/views.py @@ -565,20 +565,20 @@ def Modal(request): form.populate_obj(Exch) if modtype in ['AskC', 'PropC']: Exch.itin_id = Itinerary.itin_id - if form._fields.has_key("Hour_start"): + if "Hour_start" in form._fields: TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \ int(form.Day_start.data), form.Hour_start.data), "%Y %W %w %H:%M") Exch.start_time = TargetTime - elif form._fields.has_key("Day_start"): + elif "Day_start" in form._fields: TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \ int(form.Day_start.data)), "%Y %W %w") Exch.start_time = TargetTime - if form._fields.has_key("Hour_end"): + if "Hour_end" in form._fields: TargetTime = datetime.datetime.strptime('%d %d %d %s' % (year, int(Week), \ int(form.Day_end.data), form.Hour_end.data), "%Y %W %w %H:%M") Exch.end_time = TargetTime - elif form._fields.has_key("Day_end"): + elif "Day_end" in form._fields: TargetTime = datetime.datetime.strptime('%d %d %d' % (year, int(Week), \ int(form.Day_end.data)), "%Y %W %w") Exch.end_time = TargetTime @@ -800,7 +800,7 @@ def edit_event(request): ] if not duration in [15, 30, 60, 90]: form.duration.choices.append( (duration,u'Conférence (%d min)' % duration) ) - if not form._fields.has_key("uid"): + if not "uid" in form._fields: form.duration.data=60 elif intervention=="Stand": form.duration.choices =[ @@ -810,12 +810,12 @@ def edit_event(request): elif intervention=="Atelier": form.duration.choices = map( lambda d:(d, u'Atelier (%dh%.2d)' % (d/60, d%60) ), \ [60, 90, 120, 150, 180, 210, 240] ) - if not duration in map(lambda (d,y): d, form.duration.choices): + if not duration in map(lambda d,y: d, form.duration.choices): form.duration.choices.append( (duration,u'Atelier (%dh%.2d)' % (duration/60, duration%60) ) ) elif intervention=="Table_Ronde": form.duration.choices = map( lambda d:(d, u'Table ronde (%dh%.2d)' % (d/60, d%60) ), \ [60, 90, 120, 150] ) - if not duration in map(lambda (d,y): d, form.duration.choices): + if not duration in map(lambda d,y: d, form.duration.choices): form.duration.choices.append( (duration,u'Table ronde (%dh%.2d)' % (duration/60, duration%60) ) ) else: return HTTPForbidden(u"Pas encore disponible.") @@ -832,7 +832,7 @@ def edit_event(request): TheEvent.start_time = TheYear[0].AvailableTimeSlots[form.start_sel.data] TheEvent.end_time = TheEvent.start_time + datetime.timedelta(minutes=form.duration.data) # Ok, time to put in database - if not form._fields.has_key("uid"): + if not "uid" in form._fields: TheEvent.slug = slugify(TheEvent.name) DBSession.add(TheEvent) # Append creator by default @@ -938,7 +938,7 @@ def edit_tiers(request): form.populate_obj(TheTiers) # Handle Remove of accents TheTiers.slug = slugify(form.name.data) - if not form._fields.has_key('uid'): + if not "uid" in form._fields: TheTiers.creator_id = request.user.uid DBSession.add(TheTiers) DBSession.flush() @@ -965,32 +965,32 @@ def edit_tiers_category(request): regT= RegTitle.match(key) reg = RegExist.match(key) if reg: - if not DicResult.has_key(reg.group('slug')): + if not reg.group('slug') in DicResult: DicResult[reg.group('slug')] = dict() - if DicResult[reg.group('slug')].has_key('items'): + if 'items' in DicResult[reg.group('slug')]: DicResult[reg.group('slug')]['items'].append( ( int(reg.group('id')), value ) ) else: DicResult[reg.group('slug')]['items'] = [ ( int(reg.group('id')), value ) ] elif regN: - if not DicResult.has_key(regN.group('slug')): + if not regN.group('slug') in DicResult: DicResult[regN.group('slug')] = dict() - if DicResult[regN.group('slug')].has_key('items'): + if 'items' in DicResult[regN.group('slug')]: DicResult[regN.group('slug')]['items'].append( ( 'id', value ) ) else: DicResult[regN.group('slug')]['items'] = [ ( 'id', value ) ] ListChanges.append(('add', 0, DicResult[regN.group('slug')]['title'], value)) elif regT: - if not DicResult.has_key(regT.group('slug')): + if not regT.group('slug') in DicResult: DicResult[regT.group('slug')] = dict() DicResult[regT.group('slug')]['title'] = value else: raise for opt in DBSession.query(TiersOpt).all(): - if DicResult.has_key(opt.slug_entity_type): - found = filter( lambda (x,y): opt.uid==x, + if opt.slug_entity_type in DicResult: + found = filter( lambda x,y: opt.uid==x, DicResult[opt.slug_entity_type].get('items', [])) if not found: ListChanges.append(('remove', opt.uid, opt.entity_type, opt.entity_subtype)) -- cgit v1.2.3-70-g09d2