code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
# -*- coding: utf-8 -*- # # jQuery File Upload Plugin GAE Python Example 2.0 # https://github.com/blueimp/jQuery-File-Upload # # Copyright 2011, Sebastian Tschan # https://blueimp.net # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # from __future__ import with_statement from google.appengine.api import files, images from google.appengine.ext import blobstore, deferred from google.appengine.ext.webapp import blobstore_handlers import json, re, urllib, webapp2 WEBSITE = 'http://blueimp.github.com/jQuery-File-Upload/' MIN_FILE_SIZE = 1 # bytes MAX_FILE_SIZE = 5000000 # bytes IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)') ACCEPT_FILE_TYPES = IMAGE_TYPES THUMBNAIL_MODIFICATOR = '=s80' # max width / height EXPIRATION_TIME = 300 # seconds def cleanup(blob_keys): blobstore.delete(blob_keys) class UploadHandler(webapp2.RequestHandler): def initialize(self, request, response): super(UploadHandler, self).initialize(request, response) self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers[ 'Access-Control-Allow-Methods' ] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE' def validate(self, file): if file['size'] < MIN_FILE_SIZE: file['error'] = 'File is too small' elif file['size'] > MAX_FILE_SIZE: file['error'] = 'File is too big' elif not ACCEPT_FILE_TYPES.match(file['type']): file['error'] = 'Filetype not allowed' else: return True return False def get_file_size(self, file): file.seek(0, 2) # Seek to the end of the file size = file.tell() # Get the position of EOF file.seek(0) # Reset the file position to the beginning return size def write_blob(self, data, info): blob = files.blobstore.create( mime_type=info['type'], _blobinfo_uploaded_filename=info['name'] ) with files.open(blob, 'a') as f: f.write(data) files.finalize(blob) return files.blobstore.get_blob_key(blob) def handle_upload(self): results = [] blob_keys = [] for name, fieldStorage in self.request.POST.items(): if type(fieldStorage) is unicode: continue result = {} result['name'] = re.sub(r'^.*\\', '', fieldStorage.filename) result['type'] = fieldStorage.type result['size'] = self.get_file_size(fieldStorage.file) if self.validate(result): blob_key = str( self.write_blob(fieldStorage.value, result) ) blob_keys.append(blob_key) result['delete_type'] = 'DELETE' result['delete_url'] = self.request.host_url +\ '/?key=' + urllib.quote(blob_key, '') if (IMAGE_TYPES.match(result['type'])): try: result['url'] = images.get_serving_url( blob_key, secure_url=self.request.host_url\ .startswith('https') ) result['thumbnail_url'] = result['url'] +\ THUMBNAIL_MODIFICATOR except: # Could not get an image serving url pass if not 'url' in result: result['url'] = self.request.host_url +\ '/' + blob_key + '/' + urllib.quote( result['name'].encode('utf-8'), '') results.append(result) deferred.defer( cleanup, blob_keys, _countdown=EXPIRATION_TIME ) return results def options(self): pass def head(self): pass def get(self): self.redirect(WEBSITE) def post(self): if (self.request.get('_method') == 'DELETE'): return self.delete() result = {'files': self.handle_upload()} s = json.dumps(result, separators=(',',':')) redirect = self.request.get('redirect') if redirect: return self.redirect(str( redirect.replace('%s', urllib.quote(s, ''), 1) )) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s) def delete(self): blobstore.delete(self.request.get('key') or '') class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, key, filename): if not blobstore.get(key): self.error(404) else: # Cache for the expiration time: self.response.headers['Cache-Control'] =\ 'public,max-age=%d' % EXPIRATION_TIME self.send_blob(key, save_as=filename) app = webapp2.WSGIApplication( [ ('/', UploadHandler), ('/([^/]+)/([^/]+)', DownloadHandler) ], debug=True )
Python
# ================================================ # amboy.py - CheckNerds Labs. # http://www.checknerds.com # Backup all your items in CheckNerds. # Original Author: CNBorn, http://cnborn.net, 2009 # # # ================================================ ''' Usage: Create your .checknerds file in your home directory(for example, /home/yourname/.checknerds) cp ./.checknerds.sample ~/.checknerds Edit ~/.checknerds, filled in with your CheckNerds ID and ApiKey Run command in terminal: python amboy.py there will be a export.csv file with all your information in CheckNerds. ''' import httplib, urllib import hashlib import datetime import csv import getpass import sys from ConfigParser import ConfigParser import os filename = os.path.join(os.environ['HOME'], '.checknerds') config = ConfigParser() config.read([filename]) baseurl = config.get('base', 'base_url') if baseurl == None: baseurl = "www.checknerds.com" userid = config.get('base', 'userid') if userid == None: userid = raw_input("Please input your CheckNerds userid:") userkey = config.get('base', 'userkey') if userkey == None: userkey = getpass.getpass("Please input your API key:") appid = 74611 service392key = "0b34d532fca3bf5efd72be82f3edc8b1" #Get Debug information debug_mode = config.get('base', 'debug') if debug_mode == '1': debug_baseurl = config.get('base', 'debug_base_url') if debug_baseurl != None: baseurl = debug_baseurl debug_userid = config.get('base', 'debug_userid') if debug_userid != None: userid = debug_userid debug_userkey = config.get('base', 'debug_userkey') if debug_userkey != None: userkey = debug_userkey debug_appid = config.get('base', 'debug_appid') if debug_appid != None: appid = debug_appid debug_service392key = config.get('base', 'debug_service392key') if debug_service392key != None: service392key = debug_service392key sentkey = hashlib.sha256(service392key).hexdigest() sentuserkey = hashlib.sha256(userkey).hexdigest() print "Connecting to server..." beforedate = '' edata_total = [] count = 1 conn = httplib.HTTPConnection(baseurl) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} while count!=0: params = urllib.urlencode({'apiappid':appid, 'servicekey':sentkey, 'apiuserid':userid, 'apikey':sentuserkey , 'userid':userid, 'beforedate':beforedate, 'maxitems':8}) #print params conn.request("POST", "http://" + baseurl + "/service/item/", params, headers) response = conn.getresponse() data = response.read() conn.close() #print data #To Add Failure detection. try: edata = eval(data) count = len(edata) '''for a in edata: print a['date'] print '------' ''' if count >= 1: beforedate = edata[count-1]['date'] #print "THIS IS IT:" + str(beforedate) #print count edata_total += edata except: if len(data) == 0: if len(edata_total) > 0: print "fetched " + str(len(edata_total)) + " items." print 'No more records, query finished.' else: print "Something is wrong. " print data count = 0 # Write CSVs. fieldnames = ('id', 'name', 'comment', 'date', 'done', 'expectdate', 'donedate', 'routine', 'public', 'tags') writer = csv.DictWriter(open("export.csv", "wb"), fieldnames=fieldnames ) headers = {} for n in fieldnames: headers[n] = n writer.writerow(headers) for eachItem in edata_total: record = {} # untested pseudocode for basestring-only case: for k, v in eachItem.iteritems(): try: record[k]=v.encode('utf8') except: record[k] = v #print record writer.writerow(record)
Python
# ================================================ # trigo.py - CheckNerds Labs API testing script. # http://www.checknerds.com # # Original Author: CNBorn, http://cnborn.net, 2009 # # # ================================================ ''' Usage: Create your .checknerds file in your home directory(for example, /home/yourname/.checknerds) cp ./.checknerds.sample ~/.checknerds Edit ~/.checknerds, filled in with your CheckNerds ID and ApiKey ''' #from checknerds import * import checknerds.validator import httplib, urllib import hashlib import datetime import csv import getpass print "Connecting to server..." cn = checknerds.validator.checknerdsValidator() cn.getConfigFromFile("/home/cnborn/.checknerds") #cn.validate(None, None) if cn.debug_mode == 0: cn.validate(74611, "0b34d532fca3bf5efd72be82f3edc8b1") else: cn.validate(cn.debug_appid, cn.debug_servicekey) #print cn.get_friends(206) print cn.userid #print cn.get_user(cn.userid) #print cn.get_friends(1) #print cn.get_useritems(cn.userid) print cn.get_items() print cn.get_items(done=True) print cn.add_item(name=str(hashlib.md5(str(datetime.datetime.now())).hexdigest())[:8])
Python
# ================================================ # # http://www.checknerds.com # # Original Author: CNBorn, http://cnborn.net, 2009 # # # ================================================ import sys from ConfigParser import ConfigParser import os import datetime import hashlib import urllib import httplib class checknerdsValidator(): def __init__(self): self.userid = 0 self.userkey = "" self.appid = 0 self.servicekey = "" self.sentkey = "" self.sentuserkey = "" self.baseurl = "" self.debug_mode = 0 self.debug_userid = 0 self.debug_userkey = "" self.debug_appid = 0 self.debug_servicekey = "" self.headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} pass def __init_conn__(self): return httplib.HTTPConnection(self.baseurl) def __init_params__(self): #return urllib.urlencode({'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey , 'userid': userid }) return {'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey} #return basicpara def validate(self, appid, servicekey): #if the parameter is not given, check whether they are in the .checknerds debug section #(which should be read from ParseConfigfromFile) if not appid: if self.appid != 0: pass else: self.appid = appid self.servicekey = servicekey self.sentkey = hashlib.sha256(self.servicekey).hexdigest() self.sentuserkey = hashlib.sha256(self.userkey).hexdigest() def get_friends(self, userid): conn = self.__init_conn__ params = urllib.urlencode(self.__init_params__) conn.request("POST", "http://" + self.baseurl + "/service/friends/", params, self.headers) response = conn.getresponse() data = response.read() conn.close() return data def get_useritems(self, userid): conn = httplib.HTTPConnection(self.baseurl) params = urllib.urlencode({'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey , 'userid': userid}) #print params conn.request("POST", "http://" + self.baseurl + "/service/item/", params, self.headers) response = conn.getresponse() data = response.read() conn.close() #print data edata = eval(data) return edata def get_items(self, done=False, routine='none', public='none', maxitems=15): conn = self.__init_conn__() urlpara = self.__init_params__() urlpara['userid'] = self.userid #temp urlpara['done'] = done urlpara['routine'] = routine urlpara['public'] = public urlpara['maxitems'] = maxitems params = urllib.urlencode(urlpara) conn.request("POST", "http://" + self.baseurl + "/service/item/", params, self.headers) response = conn.getresponse() data = response.read() conn.close() #print data if len(data) != 0: edata = eval(data) return edata else: return None def add_item(self, name, comment="", routine="none", public="public", date="", tags=""): conn = self.__init_conn__() urlpara = self.__init_params__() urlpara['name'] = name urlpara['comment'] = comment urlpara['routine'] = routine urlpara['public'] = public urlpara['date'] = date urlpara['tags'] = tags params = urllib.urlencode(urlpara) conn.request("POST", "http://" + self.baseurl + "/service/additem/", params, self.headers) response = conn.getresponse() data = response.read() conn.close() print data #edata = eval(data) return data def get_user(self, userid): conn = self.__init_conn__() urlpara = self.__init_params__() urlpara['userid'] = userid params = urllib.urlencode(urlpara) conn.request("POST", "http://" + self.baseurl + "/service/user/", params, self.headers) response = conn.getresponse() data = response.read() conn.close() userdata = eval(data) return userdata def getConfigFromFile(self, filename): if not filename: filename = os.path.join(os.environ['HOME'], '.checknerds') config = ConfigParser() config.read([filename]) self.baseurl = config.get('base', 'base_url') if self.baseurl == None: self.baseurl = "www.checknerds.com" self.userid = config.get('base', 'userid') if self.userid == None: #userid = raw_input("Please input your CheckNerds userid:") pass self.userkey = config.get('base', 'userkey') if self.userkey == None: #userkey = getpass.getpass("Please input your API key:") pass #Get Debug information self.debug_mode = config.get('base', 'debug') if self.debug_mode == '1': self.debug_baseurl = config.get('base', 'debug_base_url') if self.debug_baseurl != None: self.baseurl = self.debug_baseurl self.debug_userid = config.get('base', 'debug_userid') if self.debug_userid != None: self.userid = self.debug_userid self.debug_userkey = config.get('base', 'debug_userkey') if self.debug_userkey != None: self.userkey = self.debug_userkey self.debug_appid = config.get('base', 'debug_appid') if self.debug_appid != None: self.appid = self.debug_appid self.debug_servicekey = config.get('base', 'debug_service392key') if self.debug_servicekey != None: self.servicekey = self.debug_servicekey self.sentkey = hashlib.sha256(self.servicekey).hexdigest() self.sentuserkey = hashlib.sha256(self.userkey).hexdigest()
Python
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fishes.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Python
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'fishes.views.home', name='home'), # url(r'^fishes/', include('fishes.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^model/', include('model.urls')), url(r'^admin/', include(admin.site.urls)), )
Python
# Django settings for fishes project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/home/cedric/code/fishes/database.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en//ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'hv(7@8+3zz@ms9e(co8&amp;2*#hk2et4-s^h0$30j3g7i#0@n#9qw' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'fishes.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'fishes.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. 'templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'model', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
Python
""" WSGI config for fishes project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fishes.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Python
# coding=utf-8 from django.db import models class Image(models.Model): url = models.CharField(max_length=1000) description = models.CharField(max_length=2000) def __unicode__(self): return self.url class ImageWelcome(Image): pass class Question(models.Model): question = models.CharField(max_length=1000) answer = models.CharField(max_length=5000) def __unicode__(self): if len(self.question) < 100: return self.question else: return self.question[:97] + '...' class Group(models.Model): name = models.CharField(max_length=40) def __unicode__(self): return self.name def hasItem(self): #nSubGroups = len(SubGroup.objects.filter(group=self)) #return nSubGroups > 0 return True #TODO class SubGroup(models.Model): group = models.ForeignKey(Group) name = models.CharField(max_length=40) def __unicode__(self): return self.name class Item(Image): subGroup = models.ForeignKey(SubGroup) name = models.CharField(max_length=200) price = models.FloatField(default=10) def getPriceString(self): return 'A partir de ' + `self.price` + '€' def __unicode__(self): return self.name
Python
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
Python
from django.conf.urls import patterns, url from model import views urlpatterns = patterns('', url(r'^$', views.index, name='index') )
Python
from django.contrib import admin from model.models import * admin.site.register(ImageWelcome) admin.site.register(Question) admin.site.register(Group) admin.site.register(SubGroup) admin.site.register(Item)
Python
from django.shortcuts import render from model.models import * def index(request): #latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] welcomeImages = ImageWelcome.objects.all() groups = Group.objects.all() questions = Question.objects.all() context = {'welcomeImages': welcomeImages, 'groups': groups, 'questions': questions, } return render(request, 'model/index.html', context)
Python
#!/usr/bin/env python # -*- encoding:utf8 -*- # protoc-gen-erl # Google's Protocol Buffers project, ported to lua. # https://code.google.com/p/protoc-gen-lua/ # # Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com # All rights reserved. # # Use, modification and distribution are subject to the "New BSD License" # as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. import sys import os.path as path from cStringIO import StringIO import plugin_pb2 import google.protobuf.descriptor_pb2 as descriptor_pb2 _packages = {} _files = {} _message = {} FDP = plugin_pb2.descriptor_pb2.FieldDescriptorProto if sys.platform == "win32": import msvcrt, os msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) class CppType: CPPTYPE_INT32 = 1 CPPTYPE_INT64 = 2 CPPTYPE_UINT32 = 3 CPPTYPE_UINT64 = 4 CPPTYPE_DOUBLE = 5 CPPTYPE_FLOAT = 6 CPPTYPE_BOOL = 7 CPPTYPE_ENUM = 8 CPPTYPE_STRING = 9 CPPTYPE_MESSAGE = 10 CPP_TYPE ={ FDP.TYPE_DOUBLE : CppType.CPPTYPE_DOUBLE, FDP.TYPE_FLOAT : CppType.CPPTYPE_FLOAT, FDP.TYPE_INT64 : CppType.CPPTYPE_INT64, FDP.TYPE_UINT64 : CppType.CPPTYPE_UINT64, FDP.TYPE_INT32 : CppType.CPPTYPE_INT32, FDP.TYPE_FIXED64 : CppType.CPPTYPE_UINT64, FDP.TYPE_FIXED32 : CppType.CPPTYPE_UINT32, FDP.TYPE_BOOL : CppType.CPPTYPE_BOOL, FDP.TYPE_STRING : CppType.CPPTYPE_STRING, FDP.TYPE_MESSAGE : CppType.CPPTYPE_MESSAGE, FDP.TYPE_BYTES : CppType.CPPTYPE_STRING, FDP.TYPE_UINT32 : CppType.CPPTYPE_UINT32, FDP.TYPE_ENUM : CppType.CPPTYPE_ENUM, FDP.TYPE_SFIXED32 : CppType.CPPTYPE_INT32, FDP.TYPE_SFIXED64 : CppType.CPPTYPE_INT64, FDP.TYPE_SINT32 : CppType.CPPTYPE_INT32, FDP.TYPE_SINT64 : CppType.CPPTYPE_INT64 } def printerr(*args): sys.stderr.write(" ".join(args)) sys.stderr.write("\n") sys.stderr.flush() class TreeNode(object): def __init__(self, name, parent=None, filename=None, package=None): super(TreeNode, self).__init__() self.child = [] self.parent = parent self.filename = filename self.package = package if parent: self.parent.add_child(self) self.name = name def add_child(self, child): self.child.append(child) def find_child(self, child_names): if child_names: for i in self.child: if i.name == child_names[0]: return i.find_child(child_names[1:]) raise StandardError else: return self def get_child(self, child_name): for i in self.child: if i.name == child_name: return i return None def get_path(self, end = None): pos = self out = [] while pos and pos != end: out.append(pos.name) pos = pos.parent out.reverse() return '.'.join(out) def get_global_name(self): return self.get_path() def get_local_name(self): pos = self while pos.parent: pos = pos.parent if self.package and pos.name == self.package[-1]: break return self.get_path(pos) def __str__(self): return self.to_string(0) def __repr__(self): return str(self) def to_string(self, indent = 0): return ' '*indent + '<TreeNode ' + self.name + '(\n' + \ ','.join([i.to_string(indent + 4) for i in self.child]) + \ ' '*indent +')>\n' class Env(object): filename = None package = None extend = None descriptor = None message = None context = None register = None def __init__(self): self.message_tree = TreeNode('') self.scope = self.message_tree def get_global_name(self): return self.scope.get_global_name() def get_local_name(self): return self.scope.get_local_name() def get_ref_name(self, type_name): try: node = self.lookup_name(type_name) except: # if the child doesn't be founded, it must be in this file return type_name[len('.'.join(self.package)) + 2:] if node.filename != self.filename: return node.filename + '_pb.' + node.get_local_name() return node.get_local_name() def lookup_name(self, name): names = name.split('.') if names[0] == '': return self.message_tree.find_child(names[1:]) else: return self.scope.parent.find_child(names) def enter_package(self, package): if not package: return self.message_tree names = package.split('.') pos = self.message_tree for i, name in enumerate(names): new_pos = pos.get_child(name) if new_pos: pos = new_pos else: return self._build_nodes(pos, names[i:]) return pos def enter_file(self, filename, package): self.filename = filename self.package = package.split('.') self._init_field() self.scope = self.enter_package(package) def exit_file(self): self._init_field() self.filename = None self.package = [] self.scope = self.scope.parent def enter(self, message_name): self.scope = TreeNode(message_name, self.scope, self.filename, self.package) def exit(self): self.scope = self.scope.parent def _init_field(self): self.descriptor = [] self.context = [] self.message = [] self.register = [] def _build_nodes(self, node, names): parent = node for i in names: parent = TreeNode(i, parent, self.filename, self.package) return parent class Writer(object): def __init__(self, prefix=None): self.io = StringIO() self.__indent = '' self.__prefix = prefix def getvalue(self): return self.io.getvalue() def __enter__(self): self.__indent += ' ' return self def __exit__(self, type, value, trackback): self.__indent = self.__indent[:-4] def __call__(self, data): self.io.write(self.__indent) if self.__prefix: self.io.write(self.__prefix) self.io.write(data) DEFAULT_VALUE = { FDP.TYPE_DOUBLE : '0.0', FDP.TYPE_FLOAT : '0.0', FDP.TYPE_INT64 : '0', FDP.TYPE_UINT64 : '0', FDP.TYPE_INT32 : '0', FDP.TYPE_FIXED64 : '0', FDP.TYPE_FIXED32 : '0', FDP.TYPE_BOOL : 'false', FDP.TYPE_STRING : '""', FDP.TYPE_MESSAGE : 'nil', FDP.TYPE_BYTES : '""', FDP.TYPE_UINT32 : '0', FDP.TYPE_ENUM : '1', FDP.TYPE_SFIXED32 : '0', FDP.TYPE_SFIXED64 : '0', FDP.TYPE_SINT32 : '0', FDP.TYPE_SINT64 : '0', } def code_gen_enum_item(index, enum_value, env): full_name = env.get_local_name() + '.' + enum_value.name obj_name = full_name.upper().replace('.', '_') + '_ENUM' env.descriptor.append( "local %s = protobuf.EnumValueDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % enum_value.name) context('.index = %d\n' % index) context('.number = %d\n' % enum_value.number) env.context.append(context.getvalue()) return obj_name def code_gen_enum(enum_desc, env): env.enter(enum_desc.name) full_name = env.get_local_name() obj_name = full_name.upper().replace('.', '_') env.descriptor.append( "local %s = protobuf.EnumDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % enum_desc.name) context('.full_name = "%s"\n' % env.get_global_name()) values = [] for i, enum_value in enumerate(enum_desc.value): values.append(code_gen_enum_item(i, enum_value, env)) context('.values = {%s}\n' % ','.join(values)) env.context.append(context.getvalue()) env.exit() return obj_name def code_gen_field(index, field_desc, env): full_name = env.get_local_name() + '.' + field_desc.name obj_name = full_name.upper().replace('.', '_') + '_FIELD' env.descriptor.append( "local %s = protobuf.FieldDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % field_desc.name) context('.full_name = "%s"\n' % ( env.get_global_name() + '.' + field_desc.name)) context('.number = %d\n' % field_desc.number) context('.index = %d\n' % index) context('.label = %d\n' % field_desc.label) if field_desc.HasField("default_value"): context('.has_default_value = true\n') value = field_desc.default_value if field_desc.type == FDP.TYPE_STRING: context('.default_value = "%s"\n'%value) else: context('.default_value = %s\n'%value) else: context('.has_default_value = false\n') if field_desc.label == FDP.LABEL_REPEATED: default_value = "{}" elif field_desc.HasField('type_name'): default_value = "nil" else: default_value = DEFAULT_VALUE[field_desc.type] context('.default_value = %s\n' % default_value) if field_desc.HasField('type_name'): type_name = env.get_ref_name(field_desc.type_name).upper().replace('.', '_') if field_desc.type == FDP.TYPE_MESSAGE: context('.message_type = %s\n' % type_name) else: context('.enum_type = %s\n' % type_name) if field_desc.HasField('extendee'): type_name = env.get_ref_name(field_desc.extendee) env.register.append( "%s.RegisterExtension(%s)\n" % (type_name, obj_name) ) context('.type = %d\n' % field_desc.type) context('.cpp_type = %d\n\n' % CPP_TYPE[field_desc.type]) env.context.append(context.getvalue()) return obj_name def code_gen_message(message_descriptor, env, containing_type = None): env.enter(message_descriptor.name) full_name = env.get_local_name() obj_name = full_name.upper().replace('.', '_') env.descriptor.append( "local %s = protobuf.Descriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % message_descriptor.name) context('.full_name = "%s"\n' % env.get_global_name()) nested_types = [] for msg_desc in message_descriptor.nested_type: msg_name = code_gen_message(msg_desc, env, obj_name) nested_types.append(msg_name) context('.nested_types = {%s}\n' % ', '.join(nested_types)) enums = [] for enum_desc in message_descriptor.enum_type: enums.append(code_gen_enum(enum_desc, env)) context('.enum_types = {%s}\n' % ', '.join(enums)) fields = [] for i, field_desc in enumerate(message_descriptor.field): fields.append(code_gen_field(i, field_desc, env)) context('.fields = {%s}\n' % ', '.join(fields)) if len(message_descriptor.extension_range) > 0: context('.is_extendable = true\n') else: context('.is_extendable = false\n') extensions = [] for i, field_desc in enumerate(message_descriptor.extension): extensions.append(code_gen_field(i, field_desc, env)) context('.extensions = {%s}\n' % ', '.join(extensions)) if containing_type: context('.containing_type = %s\n' % containing_type) env.message.append('%s = protobuf.Message(%s)\n' % (full_name, obj_name)) env.context.append(context.getvalue()) env.exit() return obj_name def write_header(writer): writer("""-- Generated By protoc-gen-lua Do not Edit """) def code_gen_file(proto_file, env, is_gen): filename = path.splitext(proto_file.name)[0] env.enter_file(filename, proto_file.package) includes = [] for f in proto_file.dependency: inc_file = path.splitext(f)[0] includes.append(inc_file) # for field_desc in proto_file.extension: # code_gen_extensions(field_desc, field_desc.name, env) for enum_desc in proto_file.enum_type: code_gen_enum(enum_desc, env) for enum_value in enum_desc.value: env.message.append('%s = %d\n' % (enum_value.name, enum_value.number)) for msg_desc in proto_file.message_type: code_gen_message(msg_desc, env) if is_gen: lua = Writer() write_header(lua) lua('local protobuf = require "protobuf"\n') for i in includes: lua('local %s_pb = require("%s_pb")\n' % (i, i)) lua("module('%s_pb')\n" % env.filename) lua('\n\n') map(lua, env.descriptor) lua('\n') map(lua, env.context) lua('\n') env.message.sort() map(lua, env.message) lua('\n') map(lua, env.register) _files[env.filename+ '_pb.lua'] = lua.getvalue() env.exit_file() def main(): plugin_require_bin = sys.stdin.read() code_gen_req = plugin_pb2.CodeGeneratorRequest() code_gen_req.ParseFromString(plugin_require_bin) env = Env() for proto_file in code_gen_req.proto_file: code_gen_file(proto_file, env, proto_file.name in code_gen_req.file_to_generate) code_generated = plugin_pb2.CodeGeneratorResponse() for k in _files: file_desc = code_generated.file.add() file_desc.name = k file_desc.content = _files[k] sys.stdout.write(code_generated.SerializeToString()) if __name__ == "__main__": main()
Python
import csv import operator def calculateTotalMark(emmark,epcmark,qpmark,qpmaxmark,qcmark,qcmaxmark,qmmark,qmmaxmark,sno): #print emmark,epcmark,qpmark,qpmaxmark,qcmark,qcmaxmark,qmmark,qmmaxmark status="" reason="" emmark=float(emmark) epcmark=float(epcmark) qpmark=float(qpmark) qpmaxmark=float(qpmaxmark) qcmark=float(qcmark) qcmaxmark=float(qcmaxmark) qmmark=float(qmmark) qmmaxmark=float(qmmaxmark) pcmplus2=qpmark+qcmark+qmmark pcmplus2max=qpmaxmark+qcmaxmark+qmmaxmark pcment=emmark+epcmark pcmentmax=960.0 plus2perc=((pcmplus2/pcmplus2max)*100) pcmentperc=((pcment/pcmentmax)*100) if (qmmark/qmmaxmark)*100 < 50: status="RJCT" reason ="Maths < 50" if emmark<10: status="RJCT" reason ="paper 2 < 10" if epcmark<10: status="RJCT" reason ="paper 1 < 10" if int(sno)==9999: status="RJCT" reason ="Not recieved" return [round(plus2perc+pcmentperc,4),plus2perc,pcmentperc,status,reason] #add code to reject any negative marks def check_rejection(marks,sno): return [False,"No reason"] writer=csv.writer(open("ranklist.csv", 'w'),delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL) fullwriter=csv.writer(open("ranklistfulldata.csv", 'w'),delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL) rjwriter=csv.writer(open("rjctdapps.csv", 'w'),delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL) totallist=[] rjctdlist=[] fulltotallist=[] with open('applicationforranklist.csv', 'rb') as f: reader = csv.reader(f, delimiter='%', quoting=csv.QUOTE_NONE) for row in reader: if row[0][0]=='N': continue marks=calculateTotalMark(row[5],row[6],row[11],row[12],row[13],row[14],row[15],row[16],row[1]) if marks[3]=='RJCT': rjctdlist.append([marks[0],marks[1],marks[2],row[1],row[2],row[3],row[10],marks[4]]) continue totallist.append([marks[0],marks[1],marks[2],row[1],row[2],row[3],row[10]]) fulltotallist.append([marks[0],marks[1],marks[2],row[1],row[2],row[3],row[10],row[11],row[12],row[13],row[14],row[15],row[16]]) totallist.sort(reverse=True,key=operator.itemgetter(0)) fulltotallist.sort(reverse=True,key=operator.itemgetter(0)) i=1 for row in totallist: row=[i,row[0],row[1],row[2],row[3],row[4],row[5],row[6]] writer.writerow(row) print row i=i+1 for row in fulltotallist: #row=[i,row[0],row[1],row[2],row[3],row[4],row[5],row[6]] fullwriter.writerow(row) print row i=i+1 for row in rjctdlist: rjwriter.writerow(row) i=i+1
Python
import httplib, urllib import csv apprange=3000 def send_to_server(rankdtl,cmd): if cmd=='E': print rankdtl params = urllib.urlencode({'cmd':cmd,'rank':rankdtl[0],'score': rankdtl[1],'pcm':rankdtl[2],'entmark':rankdtl[3],'sno':rankdtl[4],'erollno':rankdtl[5][5:],'name':rankdtl[6],'qualboard':rankdtl[7]}) elif cmd=='D': params = urllib.urlencode({'cmd':cmd,'erollno':rankdtl}) elif cmd=="DA": params = urllib.urlencode({'cmd':cmd,'erollno':rankdtl}) else: return False headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = httplib.HTTPConnection("localhost:8080") conn.request("POST", "/rankcmd", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() print data while 1: cmd=raw_input("Enter command->") if cmd=="exit": break if cmd=="update": with open('ranklist.csv', 'rb') as f: reader = csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONE) for row in reader: send_to_server(row,'E') if cmd=="delete": erollno=raw_input("Enter erollno->") send_to_server(erollno,'D') if cmd=="deleteall": send_to_server("0000000000",'DA')
Python
import sys import os from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * import re import time from datetime import date from os import environ def getSNo(erollno): try: smap=serialNoMap.all() smap.filter("erollno =",erollno) serialno=smap.fetch(1)[0] return serialno.sno except: return dsno def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips class Download(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=application.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.order('applieddtime') apps=btechapp.fetch(max_apps) stream.writerow(['SNo','AppID','Name','ResPh','MobPh','Panchayath','PAddress','Caddress','DOB','Gender','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax', 'Choice1','Choice2','Choice3','Choice4','Choice5','Choice6','DDNo','DDBank','CreatedBy']) for app in apps: sno=getSNo(app.erollno) stream.writerow([sno,app.appid,app.name,app.resphone,app.mobphone, app.panchayath,app.paddress,app.caddress,app.dob,app.gender, app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, app.bp1,app.bp2,app.bp3,app.bp4,app.bp5,app.bp6,app.ddno,app.ddbank,app.appcreatedby]) class VDownload(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=application.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.order('name') apps=btechapp.fetch(max_apps) stream.writerow(['No','SNo','AppID','Name','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax', ]) i=1 for app in apps: sno=getSNo(app.erollno) stream.writerow([str(i),sno,app.appid,app.name.upper(), app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, ]) i=i+1 class RLDownload(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=applicationforranklist.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.order('name') apps=btechapp.fetch(max_apps) stream.writerow(['No','SNo','AppID','Name','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax','AppStatus' ]) i=1 for app in apps: sno=getSNo(app.erollno) stream.writerow([str(i),sno,app.appid,app.name.upper(), app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, app.appstatus]) i=i+1 class MKDownload(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=applicationmookannoor.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.filter('panchayath =','MKR') apps=btechapp.fetch(max_apps) stream.writerow(['No','SNo','AppID','Name','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax','PAddress','CAddress' ]) i=1 for app in apps: sno=getSNo(app.erollno) stream.writerow([str(i),sno,app.appid,app.name.upper(), app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, app.paddress,app.caddress ]) i=i+1 class FBPDownload(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=applicationfbspatron.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.filter('pfboaesmemno !=','NA') apps=btechapp.fetch(max_apps) stream.writerow(['No','SNo','AppID','Name','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax','MemNo','Fathername', 'FatherDesig','Fatheroffice','Fatherphone','Mothername','MotheDesig','Motheroffice','Motherphone']) i=1 for app in apps: sno=getSNo(app.erollno) stream.writerow([str(i),sno,app.appid,app.name.upper(), app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, app.pfboaesmemno,app.fathername,app.fatherdesig,app.fatheraddress,app.fatherphone,app.mothername,app.motherdesig,app.motheraddress,app.motherphone]) i=i+1 class FBMDownload(webapp.RequestHandler): def get(self): if check_access()==False: return self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=applicationfbsmember.csv' stream=csv.writer(self.response.out,delimiter='%',quotechar='|', quoting=csv.QUOTE_MINIMAL) btechapp=btechApp.all() btechapp.filter('mfboaesmemno !=','NA') apps=btechapp.fetch(max_apps) stream.writerow(['No','SNo','AppID','Name','EntROllNo','EntPCMark','EntMMarks', 'QualBoard','QualYear','QualExamNo','QualExam','QualPmark','QualPMax','QualCMark','QualCMax','QualMMark','QualMMax','MemNo','Fathername', 'FatherDesig','Fatheroffice','Fatherphone','Mothername','MotheDesig','Motheroffice','Motherphone']) i=1 for app in apps: sno=getSNo(app.erollno) stream.writerow([str(i),sno,app.appid,app.name.upper(), app.erollno,app.epcmark,app.emmark, app.qualboard,app.qualexamyear,app.qualexamno,app.qualexam,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark, app.mfboaesmemno,app.fathername,app.fatherdesig,app.fatheraddress,app.fatherphone,app.mothername,app.motherdesig,app.motheraddress,app.motherphone]) i=i+1 application = webapp.WSGIApplication( [('/download', Download),('/vdownload', VDownload),('/fbmdownload', FBMDownload), ('/fbpdownload', FBPDownload),('/mkdownload', MKDownload),('/rldownload', RLDownload) ], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import httplib, urllib import csv apprange=3000 def send_to_server(rankdtl,cmd): if cmd=='E': print rankdtl params = urllib.urlencode({'cmd':cmd,'rank':rankdtl[0],'score': rankdtl[1],'pcm':rankdtl[2],'entmark':rankdtl[3],'sno':rankdtl[4],'erollno':rankdtl[5][5:],'name':rankdtl[6],'qualboard':rankdtl[7]}) elif cmd=='D': params = urllib.urlencode({'cmd':cmd,'erollno':rankdtl}) elif cmd=="DA": params = urllib.urlencode({'cmd':cmd,'erollno':rankdtl}) else: return False headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = httplib.HTTPConnection("fisatbtechapplication.appspot.com") conn.request("POST", "/rankcmd", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() print data while 1: cmd=raw_input("Enter command->") if cmd=="exit": break if cmd=="update": with open('ranklist.csv', 'rb') as f: reader = csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONE) for row in reader: send_to_server(row,'E') if cmd=="delete": erollno=raw_input("Enter erollno->") send_to_server(erollno,'D') if cmd=="deleteall": send_to_server("0000000000",'DA')
Python
"""Models""" from google.appengine.ext import db class serialNoMap(db.Model): sno=db.StringProperty() erollno=db.StringProperty() class rankList(db.Model): rank=db.StringProperty() score=db.StringProperty() erollno=db.StringProperty() qualboard=db.StringProperty() pcm=db.StringProperty() entmark=db.StringProperty() sno=db.StringProperty() name=db.StringProperty() class appStatus(db.Model): keyword=db.StringProperty() status=db.StringProperty() desc=db.StringProperty() class btechApp(db.Model): appid=db.StringProperty() apptype=db.StringProperty() appcreatedby=db.StringProperty() appstatus=db.StringProperty() applieddtime=db.DateTimeProperty(auto_now_add=True) apprank=db.StringProperty name=db.StringProperty() paddress=db.TextProperty() resphone=db.StringProperty() mobphone=db.StringProperty() panchayath=db.StringProperty() samepaddress=db.TextProperty() caddress=db.TextProperty() email=db.EmailProperty() dob=db.DateProperty() gender=db.StringProperty() nation=db.StringProperty() religion=db.StringProperty() caste=db.StringProperty() category=db.StringProperty() fathername=db.StringProperty() fatheremployed=db.StringProperty() fatherocc=db.StringProperty() fatherdesig=db.StringProperty() fatheraddress=db.TextProperty() fatherphone=db.StringProperty() mothername=db.StringProperty() motheremployed=db.StringProperty() motherocc=db.StringProperty() motherdesig=db.StringProperty() motheraddress=db.TextProperty() motherphone=db.StringProperty() mfboaesmemno=db.StringProperty() pfboaesmemno=db.StringProperty() income=db.StringProperty() erollno=db.StringProperty() erank=db.StringProperty() epcmark=db.StringProperty() epcmaxmark=db.StringProperty() emmark=db.StringProperty() emmaxmark=db.StringProperty() insaddress=db.TextProperty() insphone=db.StringProperty() qualboard=db.StringProperty() qualexamyear=db.StringProperty() qualexamno=db.StringProperty() qualexam=db.StringProperty() qpmark=db.StringProperty() qpmaxmark=db.StringProperty() qcmark=db.StringProperty() qcmaxmark=db.StringProperty() qmmark=db.StringProperty() qmmaxmark=db.StringProperty() bp1=db.StringProperty() bp2=db.StringProperty() bp3=db.StringProperty() bp4=db.StringProperty() bp5=db.StringProperty() bp6=db.StringProperty() extra=db.TextProperty() addinfo=db.TextProperty() ddno=db.StringProperty() dddate=db.StringProperty() ddbank=db.StringProperty() ddbranch=db.StringProperty() clientip=db.StringProperty()
Python
import os from google.appengine.dist import use_library use_library('django', '0.96') from google.appengine.api import mail from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * from os import environ ranktabletitle="""<tr bgcolor="white"><td>Name</td><td>PCM %(A)</td><td>Entrance %(B)</td><td>Index Mark(A+B)</td><td>FISAT Rank</td><tr>""" def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips class ShowRank(webapp.RequestHandler): def get(self): if publish_rank==0 and check_access()==False: return rank={"error":"","ranktable":""} values={"rank":rank} path = os.path.join(os.path.dirname(__file__), 'rank.html') self.response.out.write(template.render(path, values)) def post(self): if publish_rank==0 and check_access()==False: return rank={"error":"","ranktable":""} values={"rank":rank} appid=self.request.get("appid").strip() if appid.find('F')>-1: erollno=appid[5:] else: erollno=appid try: rankdtls=rankList.all() rankdtls.filter("erollno =",erollno) rankdtl=rankdtls.fetch(1)[0] rank['ranktable']=ranktabletitle+"<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>" % (rankdtl.name,rankdtl.pcm,rankdtl.entmark,rankdtl.score,rankdtl.rank) except: rank['ranktable']="""<tr><td colspan="5" >Rank details not avialable. Please contact college for more information</td></tr>""" path = os.path.join(os.path.dirname(__file__), 'rank.html') self.response.out.write(template.render(path, values)) #I know this is vulnerable, I have to add a better authentication and ssl. class RankCmd(webapp.RequestHandler): def write_status(self,msg): print 'Content-Type: text/plain' print '' print msg def post(self): if check_access()==False: return if lock_rank==1: return cmd=self.request.get("cmd") rank=self.request.get("rank") erollno=self.request.get("erollno") sno=self.request.get("sno") rank=self.request.get("rank") pcm=self.request.get("pcm") entmark=self.request.get("entmark") score=self.request.get("score") qualboard=self.request.get("qualboard") name=self.request.get("name") if cmd=='E': try: rankdtls=rankList.all() rankdtls.filter("erollno =",erollno) rankdtl=rankdtls.fetch(1)[0] rankdtl.sno=sno rankdtl.rank=rank rankdtl.pcm=pcm rankdtl.entmark=entmark rankdtl.score=score rankdtl.qualboard=qualboard rankdtl.name=name rankdtl.put() self.write_status("EDIT ENTRY") except: rankdtl=rankList() rankdtl.sno=sno rankdtl.rank=rank rankdtl.pcm=pcm rankdtl.entmark=entmark rankdtl.score=score rankdtl.erollno=erollno rankdtl.qualboard=qualboard rankdtl.name=name rankdtl.put() self.write_status("NEW ENTRY") elif cmd=='D': try: rankdtls=rankList.all() rankdtls.filter("erollno =",erollno) rankdtl=rankdtls.fetch(1)[0] rankdtl.delete() self.write_status("DEL ENTRY") except: self.write_status("UNABLE DEL") elif cmd=="DA": rankdtls=rankList.all() rankdtl=rankdtls.fetch(max_apps) db.delete(rankdtl) self.write_status("DEL ALL") application = webapp.WSGIApplication( [('/rank',ShowRank),('/rankcmd',RankCmd) ], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import os from google.appengine.dist import use_library use_library('django', '0.96') from google.appengine.api import mail from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * from os import environ def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips class FillDefaults(webapp.RequestHandler): def get(self): if check_access(): btechapp=btechApp.all() btechapp.filter("appstatus =",None) apps=btechapp.fetch(limit=5000) for app in apps: app.appstatus=defstatus[0][0] app.put() for status in defstatus: statusentry=appStatus() statusentry.keyword=status[0] statusentry.status=status[1] statusentry.desc=status[2] statusentry.put() class ShowStatus(webapp.RequestHandler): def get_status(self,rollno): btechapp=btechApp.all() btechapp.filter("erollno =",rollno) app=btechapp.fetch(1)[0] if app.appstatus==None: return appstatus_null % rollno else: try: status_keyword=app.appstatus status_dtl=appStatus.all() status_dtl.filter("keyword =",status_keyword) statusen=status_dtl.fetch(1)[0] statustable="""<tr><td>%s</td><td>%s</td><td>%s</td><tr>""" %(app.name,statusen.status,statusen.desc) return statustable except: return """<tr><td></td><td>Contact college</td><td></td><tr>""" def check_id(self,rollno): btechapp=btechApp.all() btechapp.filter("erollno =",rollno) try: app=btechapp.fetch(1)[0] return True except: return False def get(self): status={"error":"","appstatustable":""} values={"status":status} path = os.path.join(os.path.dirname(__file__), 'appstatus.html') self.response.out.write(template.render(path, values)) def post(self): status={"error":"","appstatustable":""} values={"status":status} appid=self.request.get("appid").strip() if appid.find('F')>-1: rollno=appid[5:] else: rollno=appid if self.check_id(rollno): status["appstatustable"]=self.get_status(rollno) path = os.path.join(os.path.dirname(__file__), 'appstatus.html') self.response.out.write(template.render(path, values)) else: status["error"]="Application ID does not exist. Please contact college." path = os.path.join(os.path.dirname(__file__), 'appstatus.html') self.response.out.write(template.render(path, values)) application = webapp.WSGIApplication( [('/status',ShowStatus), ('/filldb',FillDefaults)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.dist import use_library use_library('django', '0.96') sys.path.insert(0, 'reportlab.zip') from google.appengine.api import mail from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * import re import time from datetime import date import reportlab from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics import time from reportlab.lib.enums import TA_JUSTIFY,TA_RIGHT,TA_LEFT,TA_CENTER from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle,PageBreak,CondPageBreak,NextPageTemplate from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.lib import colors from reportlab.graphics.barcode import code39 from reportlab.lib.units import mm,inch from os import environ import recaptcha folderFonts = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' def sendapp_mail(appid,name,mailadd): try: mail.send_mail(sender="<admissions@fisat.ac.in>",to=mailadd,subject="FISAT BTech 2012 Admission",body=(onlinemailbody % (name,appid,appid))) except: pass def get_captcha(error=None): chtml = recaptcha.displayhtml(public_key = "6LdlodESAAAAAOe3WjJCRjUyk2w4aCpG8O-Nt5Xg",use_ssl = False,error = error) return chtml def validate_captcha(challenge,response,remoteip): cResponse = recaptcha.submit(challenge,response,"6LdlodESAAAAAI-6LiN3pQ87i07kLZUb1G6TDw_p",remoteip) return cResponse class MainPage(webapp.RequestHandler): def writedisabled(self): values="" path = os.path.join(os.path.dirname(__file__), 'disabled.html') self.response.out.write(template.render(path, values)) def get(self): if disablesubmit==1: self.writedisabled() return form=defaults() chtml=get_captcha() values={"formv":form.values,"forme":form.errors,'captchahtml': chtml} path = os.path.join(os.path.dirname(__file__), 'apptemplate.html') self.response.out.write(template.render(path, values)) def validate_name(self,name): USER_RE = re.compile("^[a-zA-Z. ][a-zA-Z. ]+$") return USER_RE.match(name) def validate_phno(self,phone): RE = re.compile("^[0-9-]+$") return (RE.match(phone)and(len(phone)>phoneno_length)) def validate_income(self,income): RE = re.compile("^[0-9]+$") return (RE.match(income)) def validate_email(self,email): EMAIL_RE = re.compile("^[\S]+@[\S]+\.[\S]+$") return EMAIL_RE.match(email) def validate_erollno(self,rollno): RE = re.compile("^[0-9A-Za-z-/]+$") return (RE.match(rollno)and(len(rollno)>erollno_length)) def validate_erank(self,rank): RE = re.compile("^[0-9]+$") return (RE.match(rank)) def validate_mark(self,mark): try: RE = re.compile("^[0-9-.]+$") return (RE.match(mark) and float(mark)!=0) except: return False def validate_year(self,year): RE = re.compile("^[0-9-]+$") return (RE.match(year) and len(year)==4) def rot13alg(self,letter): L="ABCDEFGHIJKLMNOPQRSTUVWXYZ" try: index=L.find(letter) if index>-1: if index>=13: index=index-13 return L[index] else: return L[index+13] else: return 'F' except: return 'F' def generate_id(self,rollno,name): a1="F" a2="T" try: a1=self.rot13alg(name[0].capitalize()) a2=self.rot13alg(name[2].capitalize()) except: pass appid="F12"+a1+a2+str(rollno) return appid def check_id(self,erollno): btechapp=btechApp.all() btechapp.filter("erollno =",erollno) try: app=btechapp.fetch(1)[0] return True except: return False def save_form(self,form): btechapp=btechApp() btechapp.appcreatedby="system" appid=self.generate_id(form.values['erollno'],form.values['name']) btechapp.appid=appid btechapp.name=form.values["name"] btechapp.paddress=form.values["paddress"] btechapp.resphone=form.values["resphone"] btechapp.mobphone=form.values["mobphone"] if form.values['panchayath']=="Others": btechapp.panchayath=form.values['inpanchayath'] else: btechapp.panchayath=form.values["panchayath"] btechapp.caddress=form.values["caddress"] btechapp.email=form.values["email"] dob=date(int(form.values["dobyear"]),int(form.values["dobmonth"]),int(form.values["dobdate"])) btechapp.dob=dob btechapp.gender=form.values["gender"] btechapp.nation=form.values["nation"] btechapp.religion=form.values["religion"] btechapp.caste=form.values["caste"] btechapp.category=form.values["category"] btechapp.fathername=form.values["fathername"] btechapp.fatheremployed=form.values["fatheremployed"] btechapp.fatherocc=form.values["fatherocc"] if form.values["fatheremployed"]=="YES": btechapp.fatheremployed="YES" btechapp.fatherdesig=form.values["fatherdesig"] btechapp.fatheraddress=form.values["fatheraddress"] btechapp.fatherphone=form.values["fatherphone"] else: btechapp.fatheremployed="NO" btechapp.fatherdesig="NA" btechapp.fatheraddress="NA" btechapp.fatherphone="NA" btechapp.mothername=form.values["mothername"] btechapp.motheremployed=form.values["motheremployed"] btechapp.motherocc=form.values["motherocc"] if form.values["motheremployed"]=="YES": btechapp.motheremployed="YES" btechapp.motherdesig=form.values["motherdesig"] btechapp.motheraddress=form.values["motheraddress"] btechapp.motherphone=form.values["motherphone"] else: btechapp.motheremployed="NO" btechapp.motherdesig="NA" btechapp.motheraddress="NA" btechapp.motherphone="NA" if form.values['enablemfboaes']=='ON': btechapp.mfboaesmemno=form.values["mfboaesmemno"] else: btechapp.mfboaesmemno="NA" if form.values['enablepfboaes']=='ON': btechapp.pfboaesmemno=form.values["pfboaesmemno"] else: btechapp.pfboaesmemno="NA" btechapp.income=(form.values["income"]) btechapp.erollno=form.values["erollno"] btechapp.erank=form.values["erank"] btechapp.epcmark=(form.values["epcmark"]) btechapp.epcmaxmark=(form.values["epcmaxmark"]) btechapp.emmark=(form.values["emmark"]) btechapp.emmaxmark=(form.values["emmaxmark"]) btechapp.insaddress=form.values["insaddress"] btechapp.insphone=form.values["insphone"] btechapp.qualboard=form.values["qualboard"] btechapp.qualexamyear=form.values["qualexamyear"] btechapp.qualexamno=form.values["qualexamno"] btechapp.qualexam=form.values["qualexam"] btechapp.inqualexam=form.values["inqualexam"] btechapp.qpmark=(form.values["qpmark"]) btechapp.qpmaxmark=(form.values["qpmaxmark"]) btechapp.qcmark=(form.values["qcmark"]) btechapp.qcmaxmark=(form.values["qcmaxmark"]) btechapp.qmmark=(form.values["qmmark"]) btechapp.qmmaxmark=(form.values["qmmaxmark"]) btechapp.bp1=form.values["bp1"] btechapp.bp2=form.values["bp2"] btechapp.bp3=form.values["bp3"] btechapp.bp4=form.values["bp4"] btechapp.bp5=form.values["bp5"] btechapp.bp6=form.values["bp6"] btechapp.extra=form.values["extra"] btechapp.addinfo=form.values["addinfo"] btechapp.ddno=form.values["ddno"] btechapp.dddate=form.values["dddate"] btechapp.ddbank=form.values["ddbank"] btechapp.ddbranch=form.values["ddbranch"] btechapp.clientip=environ['REMOTE_ADDR'] btechapp.appstatus=defstatus[0][0] btechapp.put() sendapp_mail(appid,form.values["name"],form.values["email"]) return appid def post(self): if disablesubmit==1: self.writedisabled() return form=defaults() form.values["name"]=self.request.get("name").strip() form.values["paddress"]=self.request.get("paddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["resphone"]=self.request.get("resphone").strip().replace(" ","") form.values["mobphone"]=self.request.get("mobphone").strip().replace(" ","") form.values["panchayath"]=self.request.get("panchayath").strip() form.values["inpanchayath"]=self.request.get("inpanchayath").strip() form.values["samepaddress"]=self.request.get("samepaddress").strip() form.values["caddress"]=self.request.get("caddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["email"]=self.request.get("email").strip() form.values["dobdate"]=self.request.get("dobdate").strip() form.values["dobmonth"]=self.request.get("dobmonth").strip() form.values["dobyear"]=self.request.get("dobyear").strip() form.values["gender"]=self.request.get("gender").strip() form.values["nation"]=self.request.get("nation").strip() form.values["religion"]=self.request.get("religion").strip() form.values["caste"]=self.request.get("caste").strip() form.values["category"]=self.request.get("category").strip() form.values["fathername"]=self.request.get("fathername").strip() form.values["fatheremployed"]=self.request.get("fatheremployed").strip() form.values["fatherocc"]=self.request.get("fatherocc").strip() form.values["fatherdesig"]=self.request.get("fatherdesig").strip() form.values["fatheraddress"]=self.request.get("fatheraddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["fatherphone"]=self.request.get("fatherphone").strip() form.values["mothername"]=self.request.get("mothername").strip() form.values["motheremployed"]=self.request.get("motheremployed").strip() form.values["motherocc"]=self.request.get("motherocc").strip() form.values["motherdesig"]=self.request.get("motherdesig").strip() form.values["motheraddress"]=self.request.get("motheraddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["motherphone"]=self.request.get("motherphone").strip().replace(" ","") form.values["enablemfboaes"]=self.request.get("enablemfboaes").strip() form.values["mfboaesmemno"]=self.request.get("mfboaesmemno").strip() form.values["enablepfboaes"]=self.request.get("enablepfboaes").strip() form.values["pfboaesmemno"]=self.request.get("pfboaesmemno").strip() form.values["income"]=self.request.get("income").strip() form.values["erollno"]=self.request.get("erollno").strip() form.values["erank"]=self.request.get("erank").strip() form.values["epcmark"]=self.request.get("epcmark").strip() form.values["epcmaxmark"]=self.request.get("epcmaxmark").strip() form.values["emmark"]=self.request.get("emmark").strip() form.values["emmaxmark"]=self.request.get("emmaxmark").strip() form.values["insaddress"]=self.request.get("insaddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["insphone"]=self.request.get("insphone").strip().replace(" ","") form.values["qualboard"]=self.request.get("qualboard").strip() form.values["qualexamyear"]=self.request.get("qualexamyear").strip() form.values["qualexamno"]=self.request.get("qualexamno").strip() form.values["qualexam"]=self.request.get("qualexam").strip() form.values["inqualexam"]=self.request.get("inqualexam").strip() form.values["qpmark"]=self.request.get("qpmark").strip() form.values["qpmaxmark"]=self.request.get("qpmaxmark").strip() form.values["qcmark"]=self.request.get("qcmark").strip() form.values["qcmaxmark"]=self.request.get("qcmaxmark").strip() form.values["qmmark"]=self.request.get("qmmark").strip() form.values["qmmaxmark"]=self.request.get("qmmaxmark").strip() form.values["bp1"]=self.request.get("bp1").strip() form.values["bp2"]=self.request.get("bp2").strip() form.values["bp3"]=self.request.get("bp3").strip() form.values["bp4"]=self.request.get("bp4").strip() form.values["bp5"]=self.request.get("bp5").strip() form.values["bp6"]=self.request.get("bp6").strip() form.values["extra"]=self.request.get("extra").strip().replace("\n"," ").replace("\r"," ").replace("\""," ")[0:35] form.values["addinfo"]=self.request.get("addinfo").strip().replace("\n"," ").replace("\r"," ").replace("\""," ")[0:35] form.values["ddno"]=self.request.get("ddno").strip() form.values["dddate"]=self.request.get("dddate").strip() form.values["ddbank"]=self.request.get("ddbank").strip() form.values["ddbranch"]=self.request.get("ddbranch").strip() challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] error=0 if self.validate_name(form.values['name']): form.errors['name']="" else: form.errors['name']="&nbsp;Invalid Name" error=1 if len(form.values['paddress'])>address_length: form.errors['paddress']="" else: form.errors['paddress']="&nbsp;Invalid address" error=1 if self.validate_phno(form.values['resphone']): form.errors['resphone']="" else: form.errors['resphone']="&nbsp;Invalid Phone NO" error=1 if self.validate_phno(form.values['mobphone']): form.errors['mobphone']="" else: form.errors['mobphone']="&nbsp;Invalid Phone NO" error=1 #if form.values['panchayath']=="Others": # form.values['panchayath']=form.values['inpanchayath'] if form.values['samepaddress']=='ON': form.values['caddress']=form.values['paddress'] else: if len(form.values['caddress'])>address_length: form.errors['caddress']="" else: form.errors['caddress']="&nbsp;Invalid address" error=1 if self.validate_email(form.values['email']): form.errors['email']="" else: form.errors['email']="&nbsp;Invalid Email" error=1 if len(form.values['nation'])>nation_length: form.errors['nation']="" else: form.errors['nation']="&nbsp;Invalid Nationality" error=1 if self.validate_name(form.values['fathername']): form.errors['fathername']="" else: form.errors['fathername']="&nbsp;Invalid Name" error=1 if form.values['fatheremployed']=='YES': if len(form.values['fatheraddress'])>address_length: form.errors['fatheraddress']="" else: form.errors['fatheraddress']="&nbsp;Invalid Address" if self.validate_name(form.values['mothername']): form.errors['mothername']="" else: form.errors['mothername']="&nbsp;Invalid Name" error=1 if form.values['motheremployed']=='YES': if len(form.values['motheraddress'])>address_length: form.errors['motheraddress']="" else: form.errors['motheraddress']="&nbsp;Invalid Address" if form.values['enablemfboaes']=='ON': if len(form.values['mfboaesmemno'])>fboaes_length: form.errors['mfboaesmemno']="" else: form.errors['mfboaesmemno']="&nbsp;Invalid Membership No" if form.values['enablepfboaes']=='ON': if len(form.values['pfboaesmemno'])>fboaes_length: form.errors['pfboaesmemno']="" else: form.errors['pfboaesmemno']="&nbsp;Invalid Membership No" if self.validate_income(form.values['income']): form.errors['income']="" else: form.errors['income']="&nbsp;Invalid Annual Income" error=1 if self.validate_erollno(form.values['erollno']): form.errors['erollno']="" else: form.errors['erollno']="&nbsp;Invalid" error=1 if self.validate_erank(form.values['erank']): form.errors['erank']="" else: form.errors['erank']=""#"&nbsp;Invalid Rank" form.values['erank']="NA" #error=1 if self.validate_mark(form.values['epcmark']): form.errors['epcmark']="" else: form.errors['epcmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['epcmaxmark']): form.errors['epcmaxmark']="" else: form.errors['epcmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['emmark']): form.errors['emmark']="" else: form.errors['emmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['emmaxmark']): form.errors['emmaxmark']="" else: form.errors['emmaxmark']="&nbsp;Invalid" error=1 if len(form.values['insaddress'])>address_length: form.errors['insaddress']="" else: form.errors['insaddress']="&nbsp;Invalid address" error=1 if self.validate_phno(form.values['insphone']): form.errors['insphone']="" else: form.errors['insphone']="&nbsp;Invalid Phone NO" error=1 if self.validate_year(form.values['qualexamyear']): form.errors['qualexamyear']="" else: form.errors['qualexamyear']="&nbsp;Invalid" error=1 if len(form.values['qualexamno'])>qualexamno_length: pass else: form.errors['qualexamno']="&nbsp;Invalid" error=1 if form.values['qualexam']=='Others': if len(form.values['inqualexam'])>qualexam_length: form.errors['inqualexam']="" else: form.errors['inqualexam']="Invalid" if len(form.values['qualboard'])>qualboard_length: form.errors['qualboard']="" else: form.errors['qualboard']="Invalid" if self.validate_mark(form.values['qpmark']): form.errors['qpmark']="" else: form.errors['qpmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qpmaxmark']): form.errors['qpmaxmark']="" else: form.errors['qpmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qcmark']): form.errors['qcmark']="" else: form.errors['qcmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qcmaxmark']): form.errors['qcmaxmark']="" else: form.errors['qcmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qmmark']): form.errors['qmmark']="" else: form.errors['qmmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qmmaxmark']): form.errors['qmmaxmark']="" else: form.errors['qmmaxmark']="&nbsp;Invalid" error=1 validate_bp= form.values['bp1']== form.values['bp2'] or form.values['bp1']== form.values['bp3'] or form.values['bp1']== form.values['bp4'] or form.values['bp1']== form.values['bp5'] or form.values['bp1']== form.values['bp6'] or form.values['bp2']== form.values['bp3'] or form.values['bp2']== form.values['bp4'] or form.values['bp2']== form.values['bp5'] or form.values['bp2']== form.values['bp6'] or form.values['bp3']== form.values['bp4'] or form.values['bp3']== form.values['bp5'] or form.values['bp3']== form.values['bp6'] or form.values['bp4']== form.values['bp5'] or form.values['bp4']== form.values['bp6'] or form.values['bp5']== form.values['bp6'] if validate_bp==False: form.errors['bp1']="" if form.values['bp1']!='0': form.errors['bp1']="" else: form.errors['bp1']="Select a branch" error=1 if form.values['bp2']!='0': form.errors['bp2']="" else: form.errors['bp2']="Select a branch" error=1 if form.values['bp3']!='0': form.errors['bp3']="" else: form.errors['bp3']="Select a branch" error=1 if form.values['bp4']!='0': form.errors['bp4']="" else: form.errors['bp4']="Select a branch" error=1 if form.values['bp5']!='0': form.errors['bp5']="" else: form.errors['bp5']="Select a branch" error=1 if form.values['bp6']!='0': form.errors['bp6']="" else: form.errors['bp6']="Select a branch" error=1 else: form.errors['bp1']="&nbsp;&nbsp;&nbsp;All Choices must be different" error=1 if len(form.values['ddno'])>ddno_length: form.errors['ddno']="" else: form.errors['ddno']="&nbsp;Invalid" error=1 if len(form.values['ddbank'])>ddbank_length: form.errors['ddbank']="" else: form.errors['ddbank']="&nbsp;Invalid" error=1 if len(form.values['dddate'])==10: form.errors['dddate']="" else: form.errors['dddate']="&nbsp;Invalid" error=1 if len(form.values['ddbranch'])>ddno_length: form.errors['ddbranch']="" else: form.errors['ddbranch']="&nbsp;Invalid " error=1 formerror={"error":""} if error==1: formerror['error']="Some of the fields are invalid. Please check. " if self.check_id(form.values['erollno']): formerror['error']="Your application already exist.Try reprint application or send mail to admissions@fisat.ac.in." error=1 captcha=validate_captcha(challenge,response,remoteip) if captcha.is_valid or response=="master": form.errors['captcha']="" else: form.errors['captcha']="The characters you entered didn't match<br> the word verification. Please try again." error=1 if error==1: chtml=get_captcha(captcha.error_code) values={"formv":form.values,"forme":form.errors,"formerror":formerror,'captchahtml': chtml} path = os.path.join(os.path.dirname(__file__), 'apptemplate.html') self.response.out.write(template.render(path, values)) else: appid=self.save_form(form) #self.print_pdf(form) self.redirect("/submit?appid="+appid,permanent=True) class SubmitApp(webapp.RequestHandler): def writedisabled(self): values="" path = os.path.join(os.path.dirname(__file__), 'disabled.html') self.response.out.write(template.render(path, values)) def check_id(self,appid): btechapp=btechApp.all() btechapp.filter("appid =",appid) try: app=btechapp.fetch(1)[0] return True except: return False def get(self): if disablesubmit==1: self.writedisabled() return appid=self.request.get("appid").replace(" ","").replace("\\","").replace(".","") if self.check_id(appid): values={"form":{"appid":appid}} path = os.path.join(os.path.dirname(__file__), 'appprint.html') self.response.out.write(template.render(path, values)) else: self.redirect("/h404",permanent=True) class PrintApp(webapp.RequestHandler): def check_id(self,appid): btechapp=btechApp.all() btechapp.filter("appid =",appid) try: app=btechapp.fetch(1)[0] return True except: return False def validate_appid(self,name): USER_RE = re.compile("^[A-Z0-9][A-Z0-9]+$") return USER_RE.match(name) def add_space(self,no): spaces="" for i in range(0,no): spaces=spaces+" " return spaces def get(self): appid=self.request.get("appid") if self.check_id(appid) and self.validate_appid(appid): self.print_pdf(appid) else: self.redirect("/h404",permanent=True) def post(self): appid=self.request.get("appid") self.print_pdf(appid) def chopline(self,line): if len(line)<=chop_length: return line try: cant = len(line) /chop_length cant += 1 strline = "" index = chop_length for i in range(1,cant): index = chop_length * i strline += "%s\n" %(line[(index-chop_length):index]) strline += "%s\n" %(line[index:]) return strline except: return line def print_pdf(self,appid): btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] self.response.headers['Content-Type'] = 'application/pdf' self.response.headers['Content-Disposition'] = 'attachment;filename=%s.pdf' % appid doc = SimpleDocTemplate(self.response.out,pagesize=A4,rightMargin=20,leftMargin=20,topMargin=30,bottomMargin=30) styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) nametext=Paragraph("<para fontSize=10>Name:</para>",styles["Left"]) name=Paragraph("<para fontSize=10><b>%s</b></para>" % app.name,styles["Left"]) paddresstext=Paragraph("<para fontSize=10>Permanent Address:</para>",styles["Justify"]) caddress=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.caddress.replace("&","&amp;")),styles["Left"]) caddresstext=Paragraph("<para fontSize=10>Communication Address:</para>",styles["Left"]) paddress=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.paddress.replace("&","&amp;")),styles["Justify"]) dobtext=Paragraph("<para fontSize=10>Date of Birth:</para>",styles["Left"]) dob=Paragraph("<para fontSize=10><b>%s</b></para>" % app.dob,styles["Left"]) emailtext=Paragraph("<para fontSize=10>Email:</para>",styles["Left"]) email=Paragraph("<para fontSize=10><b>%s</b></para>" % app.email,styles["Left"]) resphonetext=Paragraph("<para fontSize=10>Residential Phone:</para>",styles["Left"]) resphone=Paragraph("<para fontSize=10><b>%s</b></para>" % app.resphone,styles["Left"]) mobphonetext=Paragraph("<para fontSize=10>Mobile Phone:</para>",styles["Left"]) mobphone=Paragraph("<para fontSize=10><b>%s</b></para>" % app.mobphone,styles["Left"]) gendertext=Paragraph("<para fontSize=10>Gender:</para>",styles["Left"]) gender=Paragraph("<para fontSize=10><b>%s</b></para>" % app.gender,styles["Left"]) nationtext=Paragraph("<para fontSize=10>Nationality:</para>",styles["Left"]) panchayathtext=Paragraph("<para fontSize=10>Panchayath:</para>",styles["Left"]) panchayath=Paragraph("<para fontSize=10><b>%s</b></para>" % app.panchayath,styles["Left"]) nation=Paragraph("<para fontSize=10><b>%s</b></para>" % app.nation,styles["Left"]) religiontext=Paragraph("<para fontSize=10>Religion:</para>",styles["Left"]) religion=Paragraph("<para fontSize=10><b>%s</b></para>" % app.religion,styles["Left"]) castetext=Paragraph("<para fontSize=10>Community:</para>",styles["Left"]) caste=Paragraph("<para fontSize=10><b>%s</b></para>" % app.caste,styles["Left"]) categorytext=Paragraph("<para fontSize=10>Category:</para>",styles["Left"]) category=Paragraph("<para fontSize=10><b>%s</b></para>" % app.category,styles["Left"]) fathernametext=Paragraph("<para fontSize=10>Father's Name:</para>",styles["Left"]) fathername=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.fathername),styles["Left"]) fatherocctext=Paragraph("<para fontSize=10>Occupation:</para>",styles["Left"]) fatherocc=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.fatherocc.replace("&","&amp;")),styles["Left"]) fatherdesigtext=Paragraph("<para fontSize=10>Designation:</para>",styles["Left"]) fatherdesig=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.fatherdesig.replace("&","&amp;")),styles["Left"]) fatheraddress=Paragraph("<para fontSize=10>Address:</para>",styles["Left"]) fatherphonetext=Paragraph("<para fontSize=10>Phone:</para>",styles["Left"]) fatherphone=Paragraph("<para fontSize=10><b>%s</b></para>" % app.fatherphone,styles["Left"]) fatheraddresstext=Paragraph("<para fontSize=10>Address:</para>",styles["Left"]) fatheraddress=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.fatheraddress.replace("&","&amp;")),styles["Left"]) mothernametext=Paragraph("<para fontSize=10>Mother's Name:</para>",styles["Left"]) mothername=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.mothername),styles["Left"]) motherocctext=Paragraph("<para fontSize=10>Occupation:</para>",styles["Left"]) motherocc=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.motherocc.replace("&","&amp;")),styles["Left"]) motherdesigtext=Paragraph("<para fontSize=10>Designation:</para>",styles["Left"]) motherdesig=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.motherdesig.replace("&","&amp;")),styles["Left"]) motheraddresstext=Paragraph("<para fontSize=10>Address:</para>",styles["Left"]) #print self.chopline(app.motheraddress) motheraddress=Paragraph("<para fontSize=10><b>%s</b></para>" % self.chopline(app.motheraddress.replace('&','and')),styles["Left"]) motherphonetext=Paragraph("<para fontSize=10>Phone:</para>",styles["Left"]) motherphone=Paragraph("<para fontSize=10><b>%s</b></para>" % app.motherphone,styles["Left"]) mfboaesmemnotext=Paragraph("<para fontSize=10>FBOAES(Member) Membership No:</para>",styles["Left"]) mfboaesmemno=Paragraph("<para fontSize=10><br/><b>%s</b></para>" % app.mfboaesmemno,styles["Left"]) pfboaesmemnotext=Paragraph("<para fontSize=10>FBOAES(Patron) Membership No:</para>",styles["Left"]) pfboaesmemno=Paragraph("<para fontSize=10><b>%s</b></para>" % app.pfboaesmemno,styles["Left"]) incometext=Paragraph("<para fontSize=10>Annual Income:</para>",styles["Left"]) income=Paragraph("<para fontSize=10><b>%s</b></para>" % app.income,styles["Left"]) eexamtext=Paragraph("<para fontSize=12><b>Kerala Entrance 2012 </b></para>",styles["Left"]) erollnotext=Paragraph("<para fontSize=10>Roll No:</para>",styles["Left"]) erollno=Paragraph("<para fontSize=10><b>%s</b></para>" % app.erollno,styles["Left"]) eranktext=Paragraph("<para fontSize=10>Rank No:</para>",styles["Left"]) #print app.entrank erank=Paragraph("<para fontSize=10><b>%s</b></para>" % app.erank,styles["Left"]) epcmarks=Paragraph("<para fontSize=10>Physics and Chemistry<br/>Mark:<b>%s</b>&nbsp;&nbsp;Max:<b>%s</b></para>" % (app.epcmark,app.epcmaxmark),styles["Left"]) emmarks=Paragraph("<para fontSize=10>Maths<br/>Mark:<b>%s</b>&nbsp;&nbsp;Max:<b>%s</b></para>" % (app.emmark,app.emmaxmark),styles["Left"]) qualexamdtltext=Paragraph("<para fontSize=12><b>Qualifying Exam</b></para>",styles["Left"]) qualexamno=Paragraph("<para fontSize=10>Roll No:<b>%s</b></para>"% app.qualexamno,styles["Left"]) qualexamboardyear=Paragraph("<para fontSize=10>Year:<b>%s</b><br/>Board:<b>%s</b></para>" % (app.qualexamyear,app.qualboard),styles["Left"]) qualexamtext=Paragraph("<para fontSize=10>Qualifying exam:</para>",styles["Left"]) qualexam=Paragraph("<para fontSize=10><b>%s</b></para>" % app.qualexam,styles["Left"]) qpmarks=Paragraph("<para fontSize=10>Physics<br/>Mark:<b>%s</b>&nbsp;&nbsp;Max:<b>%s</b></para>" % (app.qpmark,app.qpmaxmark),styles["Left"]) qcmarks=Paragraph("<para fontSize=10>Chemistry<br/> Mark:<b>%s</b>&nbsp;&nbsp;Max:<b>%s</b></para>" % (app.qcmark,app.qcmaxmark),styles["Left"]) qmmarks=Paragraph("<para fontSize=10>Maths<br/>Mark:<b>%s</b>&nbsp;&nbsp;Max:<b>%s</b></para>" % (app.qmmark,app.qmmaxmark),styles["Left"]) choicetitle=Paragraph("<para fontSize=12><b>Branch preferences</b></para>",styles["Left"]) choice1=Paragraph("<para fontSize=10>Choice1:<b>%s</b></para>" % (app.bp1),styles["Left"]) choice2=Paragraph("<para fontSize=10>Choice2:<b>%s</b></para>" % (app.bp2),styles["Left"]) choice3=Paragraph("<para fontSize=10>Choice3:<b>%s</b></para>" % (app.bp3),styles["Left"]) choice4=Paragraph("<para fontSize=10>Choice4:<b>%s</b></para>" % (app.bp4),styles["Left"]) choice5=Paragraph("<para fontSize=10>Choice5:<b>%s</b></para>" % (app.bp5),styles["Left"]) choice6=Paragraph("<para fontSize=10>Choice6:<b>%s</b></para>" % (app.bp6),styles["Left"]) insttext=Paragraph("<para fontSize=10><b>Name and address of the school/institution last studied:</b><br/>%s<para>" % (app.insaddress.replace("&","&amp; ")),styles["Left"]) insphone=Paragraph("<para fontSize=10><b>Phone:</b><br/>%s</para>" % (app.insphone),styles["Left"]) extratext=Paragraph("<para fontSize=10><b>Extra-curricular activities:</b><br/>%s<para>" % (app.extra.replace("&","&amp;")),styles["Left"]) addinfo=Paragraph("<para fontSize=10><b>Additional Information:</b><br/>%s</para>" % (app.addinfo.replace("&","&amp;")),styles["Left"]) payinfo=Paragraph("<para fontSize=12><b>Payment Information</b></para>",styles["Left"]) ddno=Paragraph("<para fontSize=10><b>DD No:</b>%s<para>" % (app.ddno),styles["Left"]) dddate=Paragraph("<para fontSize=10><b>DD Date:</b>%s<para>" % (app.dddate),styles["Left"]) ddbank=Paragraph("<para fontSize=10><b>Bank:</b>%s<para>" % (app.ddbank),styles["Left"]) ddbranch=Paragraph("<para fontSize=10><b>Branch:</b>%s<para>" % (app.ddbranch),styles["Left"]) applicantdec=Paragraph("<para fontSize=10><b>Declaration</b><br/><br/>I hereby solemnly affirm that the statement made and information furnished in my application and also in all the enclosures there to submitted by me are true. I declare that, I shall, if admitted, abide by the rules and regulations of the college. I will not engage in any undesirable activity either inside or outside the College that will adversely affect the orderly working, discipline and the reputation of the college.</b><br/></para>",styles["Justify"]) station=Paragraph("<para fontSize=10>Station:</para>",styles["Left"]) sign=Paragraph("<para fontSize=10>Signature:</para>",styles["Left"]) date=Paragraph("<para fontSize=10>Date:</para>",styles["Left"]) appname=Paragraph("<para fontSize=10>Name:%s</para>" % app.name ,styles["Left"]) parentdec=Paragraph("<para fontSize=10> If my son/daughter/ward <b>%s</b> is admitted to the College,I hereby undertake to see to his/her good conduct and discipline within and outside the College.</b><br/></para>"% app.name,styles["Justify"]) parentname=Paragraph("<para fontSize=10>Name:</para>" ,styles["Left"]) officeusetext=Paragraph("<para fontSize=10><b>Office Use</b><br/>Certificate is verified by ............................................<br/><br/>Admitted to Branch ..........on ....................................<br/><br/>Administrative Officer / Superintendent </para>",styles["Left"]) personifodata=[[paddresstext,paddress,caddresstext,caddress], [dobtext,dob,emailtext,email], [panchayathtext,panchayath,nationtext,nation], [nationtext,nation,religiontext,religion], [castetext,caste,categorytext,category], [mfboaesmemnotext,mfboaesmemno,pfboaesmemnotext,pfboaesmemno], [fathernametext,fathername,mothernametext,mothername], [fatherocctext,fatherocc,motherocctext,motherocc], [fatherdesigtext,fatherdesig,motherdesigtext,motherdesig], [fatheraddresstext,fatheraddress,motheraddresstext,motheraddress], [fatherphonetext,fatherphone,motherphonetext,motherphone], [incometext,income]] eexamtabledata=[[eexamtext], [erollnotext,erollno,eranktext,erank], [epcmarks,emmarks]] qexamtabledata=[[qualexamdtltext], [qualexamtext,qualexam], [qualexamboardyear,qualexamno], [qpmarks,qcmarks,qmmarks]] choicedata=[[choicetitle], [choice1,choice2,choice3,choice4,choice5,choice6], ] extradata=[[insttext,insphone], [extratext,addinfo]] payinfodata=[[payinfo],[ddno,dddate],[ddbank,ddbranch]] appdecdata=[[applicantdec],[station,sign],[date,appname]] parentdecdata=[[parentdec],[station,sign],[date,parentname]] appidtext=Paragraph("<para fontSize=12>APPLICATION ID: %s" % appid,styles["Left"]) inscopy=Paragraph("<para fontSize=12>INSTITUTE COPY</b></para>",styles["Right"]) candcopy=Paragraph("<para fontSize=12>CANDIDATE COPY</b></para>",styles["Right"]) institle=Paragraph("<para fontSize=15>FEDERAL INSTITUTE OF SCIENCE AND TECHNOLOGY (FISAT)<font size='10'><super>TM</super></font></para>",styles["Center"]) iso=Paragraph("<para fontSize=10>(ISO 9001:2000 Certified Engineering College managed by the Federal Bank Officers' Association Educational Society)</para>",styles["Center"]) address=Paragraph("<para fontSize=11><b>HORMIS NAGAR, MOOKKANNOOR P.O., ANGAMALY - 683 577, KERALA</b></para>",styles["Center"]) approval=Paragraph("<para fontSize=11>(Approved by AICTE - Affiliated to Mahatma Gandhi University, Kottayam)</para>",styles["Center"]) web=Paragraph("<para fontSize=11>Website: www.fisat.ac.in E-mail: mail@fisat.ac.in</para>",styles["Center"]) barcode=code39.Extended39(appid,barWidth=0.5*mm,barHeight=15*mm,humanReadable=True) photo=Image('photo.jpg',36*mm, 36*mm) Category=Paragraph("<para fontSize=10><b>Category: General</b><br/></para>",styles["Left"]) headerinstable=Table([[appidtext,inscopy]]) headercantable=Table([[appidtext,candcopy]]) titletable=Table([[institle],[iso],[address],[approval],[web]]) titletable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) linetable=Table([[self.add_space(13),self.add_space(13)]],rowHeights =[5*mm]) linetable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'CENTER'), ('LINEBELOW',(0,0),(-1,-1),.2*mm,colors.black), ])) qexamtable=Table(qexamtabledata) qexamtable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'),])) eexamtable=Table(eexamtabledata) eexamtable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'),])) personifotable=Table(personifodata) personifotable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('ALIGN',(1,0),(1,0),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) choicetable=Table(choicedata) choicetable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('SPAN',(0,0),(1,0)), ])) extratable=Table(extradata) extratable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) choicetable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('SPAN',(0,0),(1,0)), ])) payinotable=Table(payinfodata) appdectable=Table(appdecdata) appdectable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('SPAN',(0,0),(1,0)), ])) parentdectable=Table(parentdecdata) parentdectable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('SPAN',(0,0),(1,0)), ])) officeusetable=Table([[officeusetext,barcode]],rowHeights=[40*mm]) officeusetable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'CENTER'), ('OUTLINE',(0,0),(-1,-1),.2*mm,colors.black), ])) basicinfotable=Table([[nametext,name],[resphonetext,resphone],[mobphonetext,mobphone],[gendertext,gender]]) basicinfotable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) metatable=Table([[Category],[basicinfotable]]) metatable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) infotable=Table([[metatable,photo]]) infotable.setStyle(TableStyle([('ALIGN',(0,0),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('OUTLINE',(0,0),(-1,-1),.2*mm,colors.black), ])) insbreak=PageBreak() App=[] App.append(headerinstable) App.append(Spacer(3, 12)) App.append(titletable) App.append(Spacer(1, 12)) App.append(infotable) App.append(Spacer(3, 12)) App.append(personifotable) App.append(linetable) App.append(eexamtable) App.append(insbreak) App.append(linetable) App.append(qexamtable) App.append(linetable) App.append(choicetable) App.append(linetable) App.append(extratable) App.append(linetable) App.append(payinotable) App.append(linetable) App.append(appdectable) App.append(linetable) App.append(parentdectable) App.append(linetable) App.append(officeusetable ) App.append(headerinstable) App.append(insbreak) App.append(headercantable) App.append(Spacer(3, 12)) App.append(titletable) App.append(Spacer(1, 12)) App.append(infotable) App.append(Spacer(3, 12)) App.append(personifotable) App.append(linetable) App.append(eexamtable) App.append(insbreak) App.append(linetable) App.append(qexamtable) App.append(linetable) App.append(choicetable) App.append(linetable) App.append(extratable) App.append(linetable) App.append(payinotable) App.append(linetable) App.append(appdectable) App.append(linetable) App.append(parentdectable) App.append(linetable) App.append(officeusetable ) App.append(headercantable) doc.build(App) class ReprintApp(webapp.RequestHandler): def chopline(self,line): if len(line)<=chop_length: return line try: cant = len(line) /chop_length cant += 1 strline = "" index = chop_length for i in range(1,cant): index = chop_length * i strline += "%s\n" %(line[(index-chop_length):index]) strline += "%s\n" %(line[index:]) return strline except: return line def check_id(self,appid): btechapp=btechApp.all() btechapp.filter("appid =",appid) try: app=btechapp.fetch(1)[0] return True except: return False def get(self): reprint={"error":""} values={"reprint":reprint} path = os.path.join(os.path.dirname(__file__), 'reprint.html') self.response.out.write(template.render(path, values)) def post(self): reprint={"error":""} values={"reprint":reprint} appid=self.request.get("appid") if self.check_id(appid): self.redirect("/print?appid="+appid,permanent=True) pass else: reprint["error"]="Application ID does not exist. Please contact college." path = os.path.join(os.path.dirname(__file__), 'reprint.html') self.response.out.write(template.render(path, values)) class h404Handler(webapp.RequestHandler): def get(self): values="" path = os.path.join(os.path.dirname(__file__), '404.html') self.response.out.write(template.render(path, values)) application = webapp.WSGIApplication( [('/', MainPage), ('/print', PrintApp), ('/submit', SubmitApp), ('/reprint',ReprintApp), ('/h404',h404Handler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import urllib from google.appengine.api import urlfetch """ Adapted from http://pypi.python.org/pypi/recaptcha-client to use with Google App Engine by Joscha Feth <joscha@feth.com> Version 0.1 """ API_SSL_SERVER ="https://api-secure.recaptcha.net" API_SERVER ="http://api.recaptcha.net" VERIFY_SERVER ="api-verify.recaptcha.net" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error_code = error_code def displayhtml (public_key, use_ssl = False, error = None): """Gets the HTML to display for reCAPTCHA public_key -- The public api key use_ssl -- Should the request be sent over ssl? error -- An error message to display (from RecaptchaResponse.error_code)""" error_param = '' if error: error_param = '&error=%s' % error if use_ssl: server = API_SSL_SERVER else: server = API_SERVER return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script> <noscript> <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript> """ % { 'ApiServer' : server, 'PublicKey' : public_key, 'ErrorParam' : error_param, } def submit (recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip): """ Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form recaptcha_response_field -- The value of recaptcha_response_field from the form private_key -- your reCAPTCHA private key remoteip -- the user's ip address """ if not (recaptcha_response_field and recaptcha_challenge_field and len (recaptcha_response_field) and len (recaptcha_challenge_field)): return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol') headers = { 'Content-type': 'application/x-www-form-urlencoded', "User-agent" : "reCAPTCHA GAE Python" } params = urllib.urlencode ({ 'privatekey': private_key, 'remoteip' : remoteip, 'challenge': recaptcha_challenge_field, 'response' : recaptcha_response_field, }) httpresp = urlfetch.fetch( url = "http://%s/verify" % VERIFY_SERVER, payload = params, method = urlfetch.POST, headers = headers ) if httpresp.status_code == 200: # response was fine # get the return values return_values = httpresp.content.splitlines(); # get the return code (true/false) return_code = return_values[0] if return_code == "true": # yep, filled perfectly return RecaptchaResponse (is_valid=True) else: # nope, something went wrong return RecaptchaResponse (is_valid=False, error_code = return_values [1]) else: # recaptcha server was not reachable return RecaptchaResponse (is_valid=False, error_code = "recaptcha-not-reachable")
Python
import sys import os from google.appengine.dist import use_library use_library('django', '0.96') from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * import re import time from datetime import date from os import environ table_html="""<tr><td><b>%s</b></td><td><b>%s</b></td><td>P:<b>%s/%s</b><br>C:<b>%s/%s</b><br>M:<b>%s/%s</b></td><td>PC:<b>%s/%s</b><br>M:<b>%s/%s</b></td><td>Phone:%s</td> <td><button type=button onclick='changestatus("/editstatus?appid=%s");'>status</button></td><td><button type="button" onclick='changemarks("/editmarks?appid=%s");'>Editmark</button></td><td><button type="button" onclick='addserial("/map?appid=%s");'>SNo:%s</button></td></tr>""" def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips class Search(webapp.RequestHandler): def getSNo(self,erollno): try: smap=serialNoMap.all() smap.filter("erollno =",erollno) serialno=smap.fetch(1)[0] return serialno.sno except: return dsno def addSNo(self,erollno,sno): smap=serialNoMap() smap.erollno=erollno smap.sno=so smap.put() def get(self): if check_access()==False: return results={"result":""} values={"results":results} path = os.path.join(os.path.dirname(__file__), 'search.html') self.response.out.write(template.render(path, values)) def post(self): search_html="" if check_access()==False: return erollno=self.request.get("query").strip() btechapp=btechApp.all() btechapp.filter("erollno =",erollno) apps=btechapp.fetch(max_apps) sno=self.getSNo(erollno) if sno==str(dsno): sno="NA" for app in apps: search_html=search_html+table_html %(app.appid,app.name, app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark,app.epcmark,app.epcmaxmark,app.emmark,app.emmaxmark,app.resphone,app.appid,app.appid,app.appid,sno) results={"result":search_html} values={"results":results} path = os.path.join(os.path.dirname(__file__), 'search.html') self.response.out.write(template.render(path, values)) application = webapp.WSGIApplication( [('/search', Search)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
publish_rank=1 lock_rank=0 disablesubmit=1 dsno=9999 max_apps=5000 address_length=10 phoneno_length=9 nation_length=1 fboaes_length=2 erollno_length=3 qualexamno_length=2 qualexam_length=2 qualboard_length=2 ddno_length=3 ddbranch_length=3 dddate_length=9 ddbank_length=2 chop_length=25 appstatus_null="""<tr><td>%s</td><td>Online Submitted,Under Processing</td><td>Documents not yet received/Under Processing</td><tr>""" onlinemailbody="""Dear %s You application for B.Tech under management quota at Federal Insitute of Science and Technology (FISAT) has been submitted. Your Application ID is %s. This ID will be used to track you application at every stage. The application form can be downloaded from http://fisatbtechapplication.appspot.com/print?appid=%s You can reprint the application from http://fisatbtechapplication.appspot.com/reprint List of documents to be enclosed with printout 1. Attested copy of 10th Standard mark list/ Certificate 2. Attested copy of 12th Standard Mark list 3. Attested copyof Entrance Admit Card 4. Attested copy of Entrance Mark List 5.DD The printed application need to be sent to the following address. The Principal Federal Institute of Science And Technology (FISAT) Hormis Nagar, Mookkannoor P O, Angamaly, Ernakulam Dt. Kerala, India, Pin - 683 577 Visit http://admission.fisat.ac.in for any information regarding admissions. This is a system generated mail. Do not reply to this mail. All the best.""" offlinemailbody="""Dear %s You application for B.Tech under management quota at Federal Insitute of Science and Technology (FISAT) has been recieved. Your Application ID is %s. This ID will be used to track you application at every stage. You can check the status of the application visit the site http://fisatbtechapplication.appspot.com/status Visit http://admission.fisat.ac.in for any information regarding admissions. This is a system generated mail. Do not reply to this mail. All the best.""" class defaults(): def __init__(self): self.values={ "name":"", "paddress":"", "resphone":"", "mobphone":"", "panchayath":"0", "inpanchayath":"", "samepaddress":"", "caddress":"", "email":"", "dobdate":"01", "dobmonth":"01", "dobyear":"1994", "gender":"M", "nation":"", "religion":"Hindu", "caste":"", "category":"General", "fathername":"", "fatheremployed":"", "fatherocc":"", "fatherdesig":"", "fatheraddress":"", "fatherphone":"", "mothername":"", "motheremployed":"", "motherocc":"", "motherdesig":"", "motheraddress":"", "motherphone":"", "enablemfboaes":"", "mfboaesmemno":"", "enablepfboaes":"", "pfboaesmemno":"", "income":"", "erollno":"", "erank":"", "epcmark":"", "epcmaxmark":"", "emmark":"", "emmaxmark":"", "insaddress":"", "insphone":"", "qualboard":"", "qualexamyear":"", "qualexamno":"", "qualexam":"", "inqualexam":"", "qpmark":"", "qpmaxmark":"", "qcmark":"","":"", "qcmaxmark":"", "qmmark":"", "qmmaxmark":"", "bp1":"0", "bp2":"0", "bp3":"0", "bp4":"0", "bp5":"0", "bp6":"0", "ddno":"", "dddate":"", "ddbank":"", "ddbranch":""} self.errors={ "name":"", "paddress":"", "resphone":"", "mobphone":"", "panchayath":"", "inpanchayath":"", "samepaddress":"", "caddress":"", "email":"", "dobdate":"", "dobmonth":"", "dobyear":"", "gender":"", "nation":"", "religion":"", "caste":"", "category":"", "fathername":"", "fatheremployed":"", "fatherocc":"", "fatherdesig":"", "fatheraddress":"", "fatherphone":"", "mothername":"", "motheremployed":"", "motherocc":"", "motherdesig":"", "motheraddress":"", "motherphone":"", "enablemfboaes":"", "mfboaesmemno":"", "enablepfboaes":"", "pfboaesmemno":"", "income":"", "erollno":"", "erank":"", "epcmark":"", "epcmaxmark":"", "emmark":"", "emmaxmark":"", "insaddress":"", "insphone":"", "qualboard":"", "qualexamyear":"", "qualexamno":"", "qualexam":"", "inqualexam":"", "qpmark":"", "qpmaxmark":"", "qcmark":"","":"", "qcmaxmark":"", "qmmark":"", "qmmaxmark":"", "bp1":"", "bp2":"", "bp3":"", "bp4":"", "bp5":"", "bp6":"", "extra":"", "addinfo":"", "ddno":"", "dddate":"", "ddbank":"", "ddbranch":"", "captcha":""} adminips=['202.88.252.50','117.239.78.52','127.0.0.1','202.88.252.51'] defstatus=[['ONLINENOTRECVD',"Online Submitted,Under Processing","Documents not yet received/Under Processing"], ['ONLINERECVD',"Online Submitted,Under Processing","Documents received/Under verification process"], ['OFFLINERECVD',"Offline Submitted,Under Processing","Documents received/Under Processing"], ['REJECTD',"Application rejected","Please contact college for more details"], ['ACCPTD',"Document verification Completed","Verification completed/Under Processing"]]
Python
import sys import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library use_library('django', '0.96') from google.appengine.api import mail from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * import re import time from datetime import date from os import environ def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips def sendapp_mail(appid,name,mailadd): try: mail.send_mail(sender="<admissions@fisat.ac.in>",to=mailadd,subject="FISAT BTech 2012 Admission",body=(offlinemailbody % (name,appid))) except: pass class MainPage(webapp.RequestHandler): def get(self): if check_access()==False: self.redirect("/h404",permanent=True) else: form=defaults() form.values['nation']="Indian" form.values['epcmaxmark']="480" form.values['emmaxmark']="480" values={"formv":form.values,"forme":form.errors} path = os.path.join(os.path.dirname(__file__), 'offlineapptemplate.html') self.response.out.write(template.render(path, values)) def validate_name(self,name): USER_RE = re.compile("^[a-zA-Z. ][a-zA-Z. ]+$") return USER_RE.match(name) def validate_phno(self,phone): RE = re.compile("^[0-9-]+$") return (RE.match(phone)and(len(phone)>phoneno_length)) def validate_income(self,income): RE = re.compile("^[0-9]+$") return (RE.match(income)) def validate_email(self,email): EMAIL_RE = re.compile("^[\S]+@[\S]+\.[\S]+$") return EMAIL_RE.match(email) def validate_erollno(self,rollno): RE = re.compile("^[0-9A-Za-z-/]+$") return (RE.match(rollno)and(len(rollno)>erollno_length)) def validate_erank(self,rank): RE = re.compile("^[0-9]+$") return (RE.match(rank)) def validate_mark(self,mark): RE = re.compile("^[0-9-.]+$") return (RE.match(mark) and float(mark)!=0) def validate_year(self,year): RE = re.compile("^[0-9-]+$") return (RE.match(year) and len(year)==4) def rot13alg(self,letter): L="ABCDEFGHIJKLMNOPQRSTUVWXYZ" try: index=L.find(letter) if index>-1: if index>=13: index=index-13 return L[index] else: return L[index+13] else: return 'F' except: return 'F' def generate_id(self,rollno,name): a1="F" a2="T" try: a1=self.rot13alg(name[0].capitalize()) a2=self.rot13alg(name[2].capitalize()) except: pass appid="F12"+a1+a2+str(rollno) return appid def check_id(self,erollno): btechapp=btechApp.all() btechapp.filter("erollno =",erollno) try: app=btechapp.fetch(1)[0] return True except: return False def save_form(self,form): btechapp=btechApp() btechapp.appcreatedby="college" appid=self.generate_id(form.values['erollno'],form.values['name']) btechapp.appid=appid btechapp.name=form.values["name"] btechapp.paddress=form.values["paddress"] btechapp.resphone=form.values["resphone"] btechapp.mobphone=form.values["mobphone"] if form.values['panchayath']=="Others": btechapp.panchayath=form.values['inpanchayath'] else: btechapp.panchayath=form.values["panchayath"] btechapp.caddress=form.values["caddress"] btechapp.email=form.values["email"] dob=date(int(form.values["dobyear"]),int(form.values["dobmonth"]),int(form.values["dobdate"])) btechapp.dob=dob btechapp.gender=form.values["gender"] btechapp.nation=form.values["nation"] btechapp.religion=form.values["religion"] btechapp.caste=form.values["caste"] btechapp.category=form.values["category"] btechapp.fathername=form.values["fathername"] btechapp.fatheremployed=form.values["fatheremployed"] btechapp.fatherocc=form.values["fatherocc"] if form.values["fatheremployed"]=="YES": btechapp.fatheremployed="YES" btechapp.fatherdesig=form.values["fatherdesig"] btechapp.fatheraddress=form.values["fatheraddress"] btechapp.fatherphone=form.values["fatherphone"] else: btechapp.fatheremployed="NO" btechapp.fatherdesig="NA" btechapp.fatheraddress="NA" btechapp.fatherphone="NA" btechapp.mothername=form.values["mothername"] btechapp.motheremployed=form.values["motheremployed"] btechapp.motherocc=form.values["motherocc"] if form.values["motheremployed"]=="YES": btechapp.motheremployed="YES" btechapp.motherdesig=form.values["motherdesig"] btechapp.motheraddress=form.values["motheraddress"] btechapp.motherphone=form.values["motherphone"] else: btechapp.motheremployed="NO" btechapp.motherdesig="NA" btechapp.motheraddress="NA" btechapp.motherphone="NA" if form.values['enablemfboaes']=='ON': btechapp.mfboaesmemno=form.values["mfboaesmemno"] else: btechapp.mfboaesmemno="NA" if form.values['enablepfboaes']=='ON': btechapp.pfboaesmemno=form.values["pfboaesmemno"] else: btechapp.pfboaesmemno="NA" btechapp.income=(form.values["income"]) btechapp.erollno=form.values["erollno"] btechapp.erank=form.values["erank"] btechapp.epcmark=(form.values["epcmark"]) btechapp.epcmaxmark=(form.values["epcmaxmark"]) btechapp.emmark=(form.values["emmark"]) btechapp.emmaxmark=(form.values["emmaxmark"]) btechapp.insaddress=form.values["insaddress"] btechapp.insphone=form.values["insphone"] btechapp.qualboard=form.values["qualboard"] btechapp.qualexamyear=form.values["qualexamyear"] btechapp.qualexamno=form.values["qualexamno"] btechapp.qualexam=form.values["qualexam"] btechapp.inqualexam=form.values["inqualexam"] btechapp.qpmark=(form.values["qpmark"]) btechapp.qpmaxmark=(form.values["qpmaxmark"]) btechapp.qcmark=(form.values["qcmark"]) btechapp.qcmaxmark=(form.values["qcmaxmark"]) btechapp.qmmark=(form.values["qmmark"]) btechapp.qmmaxmark=(form.values["qmmaxmark"]) btechapp.bp1=form.values["bp1"] btechapp.bp2=form.values["bp2"] btechapp.bp3=form.values["bp3"] btechapp.bp4=form.values["bp4"] btechapp.bp5=form.values["bp5"] btechapp.bp6=form.values["bp6"] btechapp.extra=form.values["extra"] btechapp.addinfo=form.values["addinfo"] btechapp.ddno=form.values["ddno"] btechapp.dddate=form.values["dddate"] btechapp.ddbank=form.values["ddbank"] btechapp.ddbranch=form.values["ddbranch"] btechapp.clientip=environ['REMOTE_ADDR'] btechapp.appstatus=defstatus[2][0] btechapp.put() sendapp_mail(appid,form.values["name"],form.values["email"]) return appid def post(self): if check_access()==False: self.redirect("/h404",permanent=True) return form=defaults() form.values["name"]=self.request.get("name").strip() form.values["paddress"]=self.request.get("paddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["resphone"]=self.request.get("resphone").strip().replace(" ","") form.values["mobphone"]=self.request.get("mobphone").strip().replace(" ","") form.values["panchayath"]=self.request.get("panchayath").strip() form.values["inpanchayath"]=self.request.get("inpanchayath").strip() form.values["samepaddress"]=self.request.get("samepaddress").strip() form.values["caddress"]=self.request.get("caddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["email"]=self.request.get("email").strip() form.values["dobdate"]=self.request.get("dobdate").strip() form.values["dobmonth"]=self.request.get("dobmonth").strip() form.values["dobyear"]=self.request.get("dobyear").strip() form.values["gender"]=self.request.get("gender").strip() form.values["nation"]=self.request.get("nation").strip() form.values["religion"]=self.request.get("religion").strip() form.values["caste"]=self.request.get("caste").strip() form.values["category"]=self.request.get("category").strip() form.values["fathername"]=self.request.get("fathername").strip() form.values["fatheremployed"]=self.request.get("fatheremployed").strip() form.values["fatherocc"]=self.request.get("fatherocc").strip() form.values["fatherdesig"]=self.request.get("fatherdesig").strip() form.values["fatheraddress"]=self.request.get("fatheraddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["fatherphone"]=self.request.get("fatherphone").strip() form.values["mothername"]=self.request.get("mothername").strip() form.values["motheremployed"]=self.request.get("motheremployed").strip() form.values["motherocc"]=self.request.get("motherocc").strip() form.values["motherdesig"]=self.request.get("motherdesig").strip() form.values["motheraddress"]=self.request.get("motheraddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["motherphone"]=self.request.get("motherphone").strip().replace(" ","") form.values["enablemfboaes"]=self.request.get("enablemfboaes").strip() form.values["mfboaesmemno"]=self.request.get("mfboaesmemno").strip() form.values["enablepfboaes"]=self.request.get("enablepfboaes").strip() form.values["pfboaesmemno"]=self.request.get("pfboaesmemno").strip() form.values["income"]=self.request.get("income").strip() form.values["erollno"]=self.request.get("erollno").strip() form.values["erank"]=self.request.get("erank").strip() form.values["epcmark"]=self.request.get("epcmark").strip() form.values["epcmaxmark"]=self.request.get("epcmaxmark").strip() form.values["emmark"]=self.request.get("emmark").strip() form.values["emmaxmark"]=self.request.get("emmaxmark").strip() form.values["insaddress"]=self.request.get("insaddress").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["insphone"]=self.request.get("insphone").strip().replace(" ","") form.values["qualboard"]=self.request.get("qualboard").strip() form.values["qualexamyear"]=self.request.get("qualexamyear").strip() form.values["qualexamno"]=self.request.get("qualexamno").strip() form.values["qualexam"]=self.request.get("qualexam").strip() form.values["inqualexam"]=self.request.get("inqualexam").strip() form.values["qpmark"]=self.request.get("qpmark").strip() form.values["qpmaxmark"]=self.request.get("qpmaxmark").strip() form.values["qcmark"]=self.request.get("qcmark").strip() form.values["qcmaxmark"]=self.request.get("qcmaxmark").strip() form.values["qmmark"]=self.request.get("qmmark").strip() form.values["qmmaxmark"]=self.request.get("qmmaxmark").strip() form.values["bp1"]=self.request.get("bp1").strip() form.values["bp2"]=self.request.get("bp2").strip() form.values["bp3"]=self.request.get("bp3").strip() form.values["bp4"]=self.request.get("bp4").strip() form.values["bp5"]=self.request.get("bp5").strip() form.values["bp6"]=self.request.get("bp6").strip() form.values["extra"]=self.request.get("extra").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["addinfo"]=self.request.get("addinfo").strip().replace("\n"," ").replace("\r"," ").replace("\""," ") form.values["ddno"]=self.request.get("ddno").strip() form.values["dddate"]=self.request.get("dddate").strip() form.values["ddbank"]=self.request.get("ddbank").strip() form.values["ddbranch"]=self.request.get("ddbranch").strip() challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] error=0 if self.validate_name(form.values['name']): form.errors['name']="" else: form.errors['name']="&nbsp;Invalid Name" error=1 if len(form.values['paddress'])>address_length: form.errors['paddress']="" else: form.errors['paddress']="&nbsp;Invalid address" error=1 if self.validate_phno(form.values['resphone']): form.errors['resphone']="" else: form.errors['resphone']="&nbsp;Invalid Phone NO" error=1 if self.validate_phno(form.values['mobphone']): form.errors['mobphone']="" else: form.errors['mobphone']="&nbsp;Invalid Phone NO" error=1 #if form.values['panchayath']=="Others": # form.values['panchayath']=form.values['inpanchayath'] if form.values['samepaddress']=='ON': form.values['caddress']=form.values['paddress'] else: if len(form.values['caddress'])>address_length: form.errors['caddress']="" else: form.errors['caddress']="&nbsp;Invalid address" error=1 if self.validate_email(form.values['email']): form.errors['email']="" else: form.errors['email']="&nbsp;Invalid Email" error=1 if len(form.values['nation'])>nation_length: form.errors['nation']="" else: form.errors['nation']="&nbsp;Invalid Nationality" error=1 if self.validate_name(form.values['fathername']): form.errors['fathername']="" else: form.errors['fathername']="&nbsp;Invalid Name" error=1 if form.values['fatheremployed']=='YES': if len(form.values['fatheraddress'])>address_length: form.errors['fatheraddress']="" else: form.errors['fatheraddress']="&nbsp;Invalid Address" if self.validate_name(form.values['mothername']): form.errors['mothername']="" else: form.errors['mothername']="&nbsp;Invalid Name" error=1 if form.values['motheremployed']=='YES': if len(form.values['motheraddress'])>address_length: form.errors['motheraddress']="" else: form.errors['motheraddress']="&nbsp;Invalid Address" if form.values['enablemfboaes']=='ON': if len(form.values['mfboaesmemno'])>fboaes_length: form.errors['mfboaesmemno']="" else: form.errors['mfboaesmemno']="&nbsp;Invalid Membership No" if form.values['enablepfboaes']=='ON': if len(form.values['pfboaesmemno'])>fboaes_length: form.errors['pfboaesmemno']="" else: form.errors['pfboaesmemno']="&nbsp;Invalid Membership No" if self.validate_income(form.values['income']): form.errors['income']="" else: form.errors['income']="&nbsp;Invalid Annual Income" error=1 if self.validate_erollno(form.values['erollno']): form.errors['erollno']="" else: form.errors['erollno']="&nbsp;Invalid" error=1 if self.validate_erank(form.values['erank']): form.errors['erank']="" else: form.errors['erank']=""#"&nbsp;Invalid Rank" form.values['erank']="NA" #error=1 if self.validate_mark(form.values['epcmark']): form.errors['epcmark']="" else: form.errors['epcmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['epcmaxmark']): form.errors['epcmaxmark']="" else: form.errors['epcmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['emmark']): form.errors['emmark']="" else: form.errors['emmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['emmaxmark']): form.errors['emmaxmark']="" else: form.errors['emmaxmark']="&nbsp;Invalid" error=1 if len(form.values['insaddress'])>address_length: form.errors['insaddress']="" else: form.errors['insaddress']="&nbsp;Invalid address" error=1 if self.validate_phno(form.values['insphone']): form.errors['insphone']="" else: form.errors['insphone']="&nbsp;Invalid Phone NO" error=1 if self.validate_year(form.values['qualexamyear']): form.errors['qualexamyear']="" else: form.errors['qualexamyear']="&nbsp;Invalid" error=1 if len(form.values['qualexamno'])>qualexamno_length: form.errors['nation']="" else: form.errors['qualexamno']="&nbsp;Invalid" error=1 if form.values['qualexam']=='Others': if len(form.values['inqualexam'])>qualexam_length: form.errors['inqualexam']="" else: form.errors['inqualexam']="Invalid" if len(form.values['qualboard'])>qualboard_length: form.errors['qualboard']="" else: form.errors['qualboard']="Invalid" if self.validate_mark(form.values['qpmark']): form.errors['qpmark']="" else: form.errors['qpmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qpmaxmark']): form.errors['qpmaxmark']="" else: form.errors['qpmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qcmark']): form.errors['qcmark']="" else: form.errors['qcmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qcmaxmark']): form.errors['qcmaxmark']="" else: form.errors['qcmaxmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qmmark']): form.errors['qmmark']="" else: form.errors['qmmark']="&nbsp;Invalid" error=1 if self.validate_mark(form.values['qmmaxmark']): form.errors['qmmaxmark']="" else: form.errors['qmmaxmark']="&nbsp;Invalid" error=1 validate_bp= form.values['bp1']== form.values['bp2'] or form.values['bp1']== form.values['bp3'] or form.values['bp1']== form.values['bp4'] or form.values['bp1']== form.values['bp5'] or form.values['bp1']== form.values['bp6'] or form.values['bp2']== form.values['bp3'] or form.values['bp2']== form.values['bp4'] or form.values['bp2']== form.values['bp5'] or form.values['bp2']== form.values['bp6'] or form.values['bp3']== form.values['bp4'] or form.values['bp3']== form.values['bp5'] or form.values['bp3']== form.values['bp6'] or form.values['bp4']== form.values['bp5'] or form.values['bp4']== form.values['bp6'] or form.values['bp5']== form.values['bp6'] if validate_bp==False: form.errors['bp1']="" if form.values['bp1']!='0': form.errors['bp1']="" else: form.errors['bp1']="Select a branch" error=1 if form.values['bp2']!='0': form.errors['bp2']="" else: form.errors['bp2']="Select a branch" error=1 if form.values['bp3']!='0': form.errors['bp3']="" else: form.errors['bp3']="Select a branch" error=1 if form.values['bp4']!='0': form.errors['bp4']="" else: form.errors['bp4']="Select a branch" error=1 if form.values['bp5']!='0': form.errors['bp5']="" else: form.errors['bp5']="Select a branch" error=1 if form.values['bp6']!='0': form.errors['bp6']="" else: form.errors['bp6']="Select a branch" error=1 else: form.errors['bp1']="&nbsp;&nbsp;&nbsp;All Choices must be different" error=1 if len(form.values['ddno'])>ddno_length: form.errors['ddno']="" else: form.errors['ddno']="&nbsp;Invalid" error=1 if len(form.values['ddbank'])>ddbank_length: form.errors['ddbank']="" else: form.errors['ddbank']="&nbsp;Invalid" error=1 if len(form.values['dddate'])==10: form.errors['dddate']="" else: form.errors['dddate']="&nbsp;Invalid" error=1 if len(form.values['ddbranch'])>ddno_length: form.errors['ddbranch']="" else: form.errors['ddbranch']="&nbsp;Invalid " error=1 formerror={"error":""} if error==1: formerror['error']="Some of the fields are invalid. Please check. " if self.check_id(form.values['erollno']): formerror['error']="Your application already exist.Try reprint application or send mail to admissions@fisat.ac.in." error=1 if error==1: values={"formv":form.values,"forme":form.errors,"formerror":formerror} path = os.path.join(os.path.dirname(__file__), 'offlineapptemplate.html') self.response.out.write(template.render(path, values)) else: appid=self.save_form(form) #self.print_pdf(form) self.redirect("/offsubmit?appid="+appid,permanent=True) class SubmitApp(webapp.RequestHandler): def check_id(self,appid): btechapp=btechApp.all() btechapp.filter("appid =",appid) try: app=btechapp.fetch(1)[0] return True except: return False def get(self): if check_access()==False: self.redirect("/h404",permanent=True) return appid=self.request.get("appid").replace(" ","").replace("\\","").replace(".","") if self.check_id(appid): values={"form":{"appid":appid}} path = os.path.join(os.path.dirname(__file__), 'offappprint.html') self.response.out.write(template.render(path, values)) else: self.redirect("/h404",permanent=True) application = webapp.WSGIApplication( [('/offline', MainPage), ('/offsubmit', SubmitApp), ], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.dist import use_library use_library('django', '0.96') from google.appengine.ext.webapp import template import cgi import csv from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from defaults import * from models import * import re import time from datetime import date from os import environ def check_access(): ip=environ['REMOTE_ADDR'] return ip in adminips class EditStatus(webapp.RequestHandler): def get(self): if check_access()==False: return allstatus={"status":""} canid={"appid":""} values={"allstatus":allstatus,"canid":canid} appid=self.request.get("appid") canid['appid']=appid appstatus=appStatus.all() btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] statusall=appstatus.fetch(10) statusbuttons="" for status in statusall: if status.keyword==app.appstatus: button="""<input type="radio" name="status" value="%s" checked>%s(%s)<br>""" % (status.keyword,status.status,status.desc) statusbuttons=statusbuttons+button else: button="""<input type="radio" name="status" value="%s" >%s(%s)<br>""" % (status.keyword,status.status,status.desc) statusbuttons=statusbuttons+button allstatus['status']=statusbuttons path = os.path.join(os.path.dirname(__file__), 'editstatus.html') self.response.out.write(template.render(path, values)) def post(self): if check_access()==False: return appid=self.request.get("appid") status=self.request.get("status") btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] app.appstatus=status app.put() self.redirect("/editstatus?appid="+appid,permanent=True) class EditMarks(webapp.RequestHandler): def get(self): if check_access()==False: return allmarks={"marks":""} canid={"appid":""} values={"allmarks":allmarks,"canid":canid} appid=self.request.get("appid") canid['appid']=appid btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] inputs="""Ent PC<input type="text" value="%s" name="epcmark" id="epcmark">&nbsp;Max<input type="text" value="%s" name="epcmaxmark" id="epcmaxmark"><br> Ent M&nbsp;<input type="text" value="%s" name="emmark" id="emmark">&nbsp;Max<input type="text" value="%s" name="emmaxmark" id="emmaxmark"><br> +2 P&nbsp;&nbsp;&nbsp;<input type="text" value="%s" name="qpmark" id="qpmark">&nbsp;Max<input type="text" value="%s" name="qpmaxmark" id="qpmaxmark"><br> +2 C&nbsp;&nbsp;&nbsp;<input type="text" value="%s" name="qcmark" id="qcmark">&nbsp;Max<input type="text" value="%s" name="qcmaxmark" id="qccmaxmark"><br> +2 M&nbsp;&nbsp;<input type="text" value="%s" name="qmmark" id="qmmark">&nbsp;Max<input type="text" value="%s" name="qmmaxmark" id="qmmaxmark"><br>""" % (app.epcmark,app.epcmaxmark,app.emmark,app.emmaxmark,app.qpmark,app.qpmaxmark,app.qcmark,app.qcmaxmark,app.qmmark,app.qmmaxmark) allmarks['marks']=inputs path = os.path.join(os.path.dirname(__file__), 'editmarks.html') self.response.out.write(template.render(path, values)) def post(self): if check_access()==False: return appid=self.request.get("appid") epcmark=self.request.get("epcmark") emmark=self.request.get("emmark") qpmark=self.request.get("qpmark") qcmark=self.request.get("qcmark") qmmark=self.request.get("qmmark") epcmaxmark=self.request.get("epcmaxmark") emmaxmark=self.request.get("emmaxmark") qpmaxmark=self.request.get("qpmaxmark") qcmaxmark=self.request.get("qcmaxmark") qmmaxmark=self.request.get("qmmaxmark") btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] app.epcmark=epcmark app.emmark=emmark app.qpmark=qpmark app.qcmark=qcmark app.qmmark=qmmark app.epcmaxmark=epcmaxmark app.emmaxmark=emmaxmark app.qpmaxmark=qpmaxmark app.qcmaxmark=qcmaxmark app.qmmaxmark=qmmaxmark app.put() print 'Content-Type: text/plain' print '' print 'Saved' class EditSNo(webapp.RequestHandler): def validate_sno(self,sno): try: RE = re.compile("^[0-9]+$") return (RE.match(sno) and float(sno)!=0) except: return False def getSNo(self,erollno): try: smap=serialNoMap.all() smap.filter("erollno =",erollno) serialno=smap.fetch(1)[0] return serialno.sno except: return dsno def addSNo(self,erollno,sno): if self.validate_sno(sno)==False: return False try: smap=serialNoMap.all() smap.filter("erollno =",erollno) serialno=smap.fetch(1)[0] serialno.sno=sno serialno.put() return True except: smap=serialNoMap() smap.erollno=erollno smap.sno=sno smap.put() return True def get(self): if check_access()==False: return sall={"sno":""} canid={"appid":""} values={"sall":sall,"canid":canid} appid=self.request.get("appid") canid['appid']=appid btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] sno=self.getSNo(app.erollno) if sno==str(dsno): sno="" inputs="""Serial No<input type="text" value="%s" name="sno" id="sno"><br>""" % sno sall["sno"]=inputs path = os.path.join(os.path.dirname(__file__), 'map.html') self.response.out.write(template.render(path, values)) def post(self): if check_access()==False: return appid=self.request.get("appid") sno=self.request.get("sno") if sno.strip()=="": sno=str(dsno) btechapp=btechApp.all() btechapp.filter("appid =",appid) app=btechapp.fetch(1)[0] success=self.addSNo(app.erollno,sno) if success==False: print 'Content-Type: text/plain' print '' print 'Unable to save , check for any not numerical characters -:(' else: print 'Content-Type: text/plain' print '' print 'Saved' application = webapp.WSGIApplication( [('/editstatus', EditStatus),('/editmarks', EditMarks),('/map', EditSNo)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
capthalist={
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "2.0" '''Dr. Weather, a Google Wave robot. Gives the weather of a city. Usage: @city @city,country @city#language-code @city,country#language-code E.g.: @beijing @beijing,china @beijing#zh-cn @beijing,china#zh-cn ''' import logging import re import urllib2 from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi.ops import OpBuilder import gwapi CMD_NO = 'drweather:no' CMD_HELP = 'drweather:help' URL_GOOGLE = 'http://www.google.com' STR_USAGE = 'Usage: @city[,country][#language-code]\n(More: http://code.google.com/p/firstwave/wiki/DrWeather)' logger = logging.getLogger('Dr_Weather') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can see the future!\n"+STR_USAGE) def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" logger.debug('OnParticipantsChanged()') added = properties['participantsAdded'] for p in added: if p != 'shiny-sky@appspot.com' and p != 'dr-weather@appspot.com': Notify(context, "Do you wanna know weather information? Ask me!\n"+STR_USAGE) break def OnBlipSubmit(properties, context): """Invoked when new blip submitted. append rich formatted text to blip""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() newdoc = None try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass if CMD_NO in text: return if CMD_HELP in text: newBlip = blip.CreateChild() newdoc = newBlip.GetDocument() newdoc.SetText(STR_USAGE) queries = re.findall(r"(?i)@([^@#,\t\r\n\v\f]+(,[^@#,\t\r\n\v\f]*)?)(#([a-z]{2}(-[a-z]{2})?)?)?", text) #Iterate through search strings for q in queries: city = q[0].strip().encode('utf-8') lang = q[3].strip() logger.info('query: %s'+str(q)) city = urllib2.quote(city) logger.debug('quote city: %s' % city) weather_data = gwapi.get_weather_from_google(city, lang) if weather_data: if newdoc == None: newBlip = blip.CreateChild() newdoc = newBlip.GetDocument() newdoc.SetText(" ") reply = gooleWeatherConverter(weather_data) builder = OpBuilder(context) builder.DocumentAppendMarkup(newBlip.waveId, newBlip.waveletId, newBlip.GetId(), reply) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) def Fahrenheit2Celsius(F): '''convert F to C''' try: f = int(F) c = int(round((f-32)*5.0/9.0)) return str(c) except: return '(N/A)' def Celsius2Fahrenheit(C): '''convert C to F''' try: c = int(C) f = int(round(c*9.0/5.0+32)) return str(f) except: return '(N/A)' def TempConverter(t, u): '''temp temparature converter if we support multi languages in the future, this func is not needed any more. ''' if u.upper() == 'US': return u'%s°C(%s°F)'%(Fahrenheit2Celsius(t),t) else:# u == 'SI': return u'%s°C(%s°F)'%(t, Celsius2Fahrenheit(t)) def getImageURL(url): return (URL_GOOGLE+url) def gooleWeatherConverter(weatherData): '''convert data to html/txt''' replystr = u'<br/><br/><img src="%s" /><br/>' % getImageURL(weatherData['current_conditions']['icon']) replystr += u'<b>%s</b><br/>%s, %s°C(%s°F)<br/>%s<br/>%s<br/><br/>' % ( weatherData['forecast_information']['city'], weatherData['current_conditions']['condition'], weatherData['current_conditions']['temp_c'], weatherData['current_conditions']['temp_f'], weatherData['current_conditions']['humidity'], weatherData['current_conditions']['wind_condition']) for day in weatherData['forecasts']: replystr += u'<img src="%s" />' % getImageURL(day['icon']) replystr += u'<b>%s</b>: %s, %s ~ %s<br/>' % (day['day_of_week'], day['condition'], TempConverter(day['low'], weatherData['forecast_information']['unit_system']), TempConverter(day['high'], weatherData['forecast_information']['unit_system'])) return replystr if __name__ == '__main__': myRobot = robot.Robot('DrWeather', image_url='http://shiny-sky.appspot.com/assets/sunny.png', version='1.0', profile_url='http://code.google.com/p/firstwave/wiki/DrWeather') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) #myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- #Copyright (c) 2009 Eugene Kaznacheev <qetzal@gmail.com> #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. __author__ = 'shinysky' __license__ = "Apache License 2.0" __version__ = "2.0" """ Fetches weather reports from Google Weather """ import urllib2, re, logging from xml.dom import minidom GOOGLE_WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s' def get_weather_from_google(location_id, hl = ''): """ Fetches weather report from Google Parameters location_id: a zip code (10001); city name, state (weather=woodland,PA); city name, country (weather=london,england); or possibly others. hl: the language parameter (language code) Returns: weather_data: a dictionary of weather data that exists in XML feed. """ url = GOOGLE_WEATHER_URL % (location_id, hl) handler = urllib2.urlopen(url) content_type = handler.info().dict['content-type'] charset = re.search('charset\=(.*)',content_type).group(1) logging.debug('charset: %s' % charset) if charset.upper() == 'GB2312': charset = 'GB18030' xml_response = handler.read().decode(charset).encode('utf-8') dom = minidom.parseString(xml_response) handler.close() try: weather_data = {} weather_dom = dom.getElementsByTagName('weather')[0] data_structure = { 'forecast_information': ('city', 'postal_code', 'latitude_e6', 'longitude_e6', 'forecast_date', 'current_date_time', 'unit_system'), 'current_conditions': ('condition','temp_f', 'temp_c', 'humidity', 'wind_condition', 'icon') } for (tag, list_of_tags2) in data_structure.iteritems(): tmp_conditions = {} for tag2 in list_of_tags2: tmp_conditions[tag2] = weather_dom.getElementsByTagName(tag)[0].getElementsByTagName(tag2)[0].getAttribute('data') weather_data[tag] = tmp_conditions forecast_conditions = ('day_of_week', 'low', 'high', 'icon', 'condition') forecasts = [] for forecast in dom.getElementsByTagName('forecast_conditions'): tmp_forecast = {} for tag in forecast_conditions: tmp_forecast[tag] = forecast.getElementsByTagName(tag)[0].getAttribute('data') forecasts.append(tmp_forecast) weather_data['forecasts'] = forecasts dom.unlink() return weather_data except: return None
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging import re import urllib2 import gwapi def OnBlipSubmit(): """Invoked when new blip submitted. hl = zh-cn: chinese zh-tw: tranditional chinese en: english de: fr: """ while True: text = raw_input('query:') queries = re.findall(r"(?i)@([^@#,\t\r\n\v\f][^@#,\t\r\n\v\f]*(,[^@#,\t\r\n\v\f]*)?)(#([a-z]{2}(-[a-z]{2})?)?)?", text) #print queries if queries: print 'find %d queries...' % len(queries) #Iterate through search strings for q in queries: print urllib2.quote(q[0]) city = q[0].strip().decode('gb18030').encode('utf-8') lang = q[3].strip() print 'city and lang:', city.decode('utf-8'), lang city = urllib2.quote(city)#.replace(' ', '%20') print city weather_data = gwapi.get_weather_from_google(city, lang) if weather_data: print gooleWeatherConverter(weather_data)#.encode('utf-8') def Fahrenheit2Celsius(F): '''convert F to C''' try: f = int(F) c = int(round((f-32)*5.0/9.0)) return str(c) except: return '(N/A)' def Celsius2Fahrenheit(C): '''convert C to F''' try: c = int(C) f = int(round(c*9.0/5.0+32)) return str(f) except: return '(N/A)' def TempConverter(t, u): '''temp temparature converter if we support multi languages in the future, this func is not needed any more. ''' if u.upper() == 'US': return '%sC(%sF)'%(Fahrenheit2Celsius(t),t) else:# u == 'SI': return '%sC(%sF)'%(t, Celsius2Fahrenheit(t)) def gooleWeatherConverter(weatherData): '''convert data to html/txt''' text = '' text += '%s\n%s, %sC(%sF)\n' % ( weatherData['forecast_information']['city'].upper(), weatherData['current_conditions']['condition'], weatherData['current_conditions']['temp_c'], weatherData['current_conditions']['temp_f']) text += '%s\n' % weatherData['current_conditions']['humidity'] text += '%s\n\n' % weatherData['current_conditions']['wind_condition'] for day in weatherData['forecasts']: text += '%s: %s, %s ~ %s\n'%(day['day_of_week'], day['condition'], TempConverter(day['low'], weatherData['forecast_information']['unit_system']), TempConverter(day['high'], weatherData['forecast_information']['unit_system'])) return text if __name__ == '__main__': OnBlipSubmit()
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "2.0" '''Dr. Weather, a Google Wave robot. Gives the weather of a city. Intro: http://code.google.com/p/firstwave/wiki/DrWeather ''' import logging import re import urllib2 from waveapi import events from waveapi import model from waveapi import robot from waveapi import document import gwapi CMD_NO = 'drweather:no' CMD_HELP = 'drweather:help' URL_GOOGLE = 'http://www.google.com' STR_USAGE = '''Usage: [city] [city,country] [city,,language-code] [city,country,language-code] (More: http://code.google.com/p/firstwave/wiki/DrWeather)''' logger = logging.getLogger('Dr_Weather') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can see the future!\n"+STR_USAGE) def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" logger.debug('OnParticipantsChanged()') added = properties['participantsAdded'] for p in added: if p != 'shiny-sky@appspot.com' and p != 'dr-weather@appspot.com': Notify(context, "Do you wanna know weather information? Ask me!\n"+STR_USAGE) break def OnBlipSubmit(properties, context): """Invoked when new blip submitted. append rich formatted text to blip""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() newdoc = None try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass if CMD_NO in text: return if CMD_HELP in text: newBlip = doc.AppendInlineBlip() newdoc = newBlip.GetDocument() newdoc.SetText(STR_USAGE) queries = re.findall(r"(?i)\[([^,\[\]]+(,[^,\[\]]*)?)(,([a-z]{2}(-[a-z]{2})?)?)?\]", text) #Iterate through search strings for q in queries: city = q[0].strip().encode('utf-8') lang = q[3].strip() logger.info('query: %s'+str(q)) city = urllib2.quote(city) logger.debug('quote city: %s' % city) weather_data = gwapi.get_weather_from_google(city, lang) if weather_data: if newdoc == None: newBlip = doc.AppendInlineBlip() newdoc = newBlip.GetDocument() gooleWeatherConverter(weather_data, newdoc) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) def Fahrenheit2Celsius(F): '''convert F to C''' try: f = int(F) c = int(round((f-32)*5.0/9.0)) return str(c) except: return '(N/A)' def Celsius2Fahrenheit(C): '''convert C to F''' try: c = int(C) f = int(round(c*9.0/5.0+32)) return str(f) except: return '(N/A)' def TempConverter(t, u): '''temp temparature converter if we support multi languages in the future, this func is not needed any more. ''' if u.upper() == 'US': return u'%s°C(%s°F)'%(Fahrenheit2Celsius(t),t) else:# u == 'SI': return u'%s°C(%s°F)'%(t, Celsius2Fahrenheit(t)) def getImageObj(url): return document.Image(URL_GOOGLE+url) def gooleWeatherConverter(weatherData, doc): '''convert data to html/txt''' doc.AppendText(' \n\n ') doc.AppendElement(getImageObj(weatherData['current_conditions']['icon'])) doc.AppendText(u'\n%s\n%s, %s°C(%s°F)\n%s\n%s \n\n ' % ( weatherData['forecast_information']['city'].upper(), weatherData['current_conditions']['condition'], weatherData['current_conditions']['temp_c'], weatherData['current_conditions']['temp_f'], weatherData['current_conditions']['humidity'], weatherData['current_conditions']['wind_condition'])) for day in weatherData['forecasts']: doc.AppendElement(getImageObj(day['icon'])) doc.AppendText(u' %s: %s, %s ~ %s\n '%(day['day_of_week'], day['condition'], TempConverter(day['low'], weatherData['forecast_information']['unit_system']), TempConverter(day['high'], weatherData['forecast_information']['unit_system']))) if __name__ == '__main__': myRobot = robot.Robot('DrWeather', image_url='http://shiny-sky.appspot.com/assets/sunny.png', version='1.0', profile_url='http://code.google.com/p/firstwave/wiki/DrWeather') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) #myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "2.0" '''Dr. Weather, a Google Wave robot. Gives the weather of a city. Usage: @city @city,country @city#language-code @city,country#language-code E.g.: @beijing @beijing,china @beijing#zh-cn @beijing,china#zh-cn ''' import logging import re import urllib2 from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi.ops import OpBuilder import gwapi CMD_NO = 'drweather:no' CMD_HELP = 'drweather:help' URL_GOOGLE = 'http://www.google.com' STR_USAGE = 'Usage: @city[,country][#language-code]\n(More: http://code.google.com/p/firstwave/wiki/DrWeather)' logger = logging.getLogger('Dr_Weather') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can see the future!\n"+STR_USAGE) def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" logger.debug('OnParticipantsChanged()') added = properties['participantsAdded'] for p in added: if p != 'shiny-sky@appspot.com' and p != 'dr-weather@appspot.com': Notify(context, "Do you wanna know weather information? Ask me!\n"+STR_USAGE) break def OnBlipSubmit(properties, context): """Invoked when new blip submitted. append rich formatted text to blip""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() newdoc = None try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass if CMD_NO in text: return if CMD_HELP in text: newBlip = blip.CreateChild() newdoc = newBlip.GetDocument() newdoc.SetText(STR_USAGE) queries = re.findall(r"(?i)@([^@#,\t\r\n\v\f]+(,[^@#,\t\r\n\v\f]*)?)(#([a-z]{2}(-[a-z]{2})?)?)?", text) #Iterate through search strings for q in queries: city = q[0].strip().encode('utf-8') lang = q[3].strip() logger.info('query: %s'+str(q)) city = urllib2.quote(city) logger.debug('quote city: %s' % city) weather_data = gwapi.get_weather_from_google(city, lang) if weather_data: if newdoc == None: newBlip = blip.CreateChild() newdoc = newBlip.GetDocument() newdoc.SetText(" ") reply = gooleWeatherConverter(weather_data) builder = OpBuilder(context) builder.DocumentAppendMarkup(newBlip.waveId, newBlip.waveletId, newBlip.GetId(), reply) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) def Fahrenheit2Celsius(F): '''convert F to C''' try: f = int(F) c = int(round((f-32)*5.0/9.0)) return str(c) except: return '(N/A)' def Celsius2Fahrenheit(C): '''convert C to F''' try: c = int(C) f = int(round(c*9.0/5.0+32)) return str(f) except: return '(N/A)' def TempConverter(t, u): '''temp temparature converter if we support multi languages in the future, this func is not needed any more. ''' if u.upper() == 'US': return u'%s°C(%s°F)'%(Fahrenheit2Celsius(t),t) else:# u == 'SI': return u'%s°C(%s°F)'%(t, Celsius2Fahrenheit(t)) def getImageURL(url): return (URL_GOOGLE+url) def gooleWeatherConverter(weatherData): '''convert data to html/txt''' replystr = u'<br/><br/><img src="%s" /><br/>' % getImageURL(weatherData['current_conditions']['icon']) replystr += u'<b>%s</b><br/>%s, %s°C(%s°F)<br/>%s<br/>%s<br/><br/>' % ( weatherData['forecast_information']['city'], weatherData['current_conditions']['condition'], weatherData['current_conditions']['temp_c'], weatherData['current_conditions']['temp_f'], weatherData['current_conditions']['humidity'], weatherData['current_conditions']['wind_condition']) for day in weatherData['forecasts']: replystr += u'<img src="%s" />' % getImageURL(day['icon']) replystr += u'<b>%s</b>: %s, %s ~ %s<br/>' % (day['day_of_week'], day['condition'], TempConverter(day['low'], weatherData['forecast_information']['unit_system']), TempConverter(day['high'], weatherData['forecast_information']['unit_system'])) return replystr if __name__ == '__main__': myRobot = robot.Robot('DrWeather', image_url='http://shiny-sky.appspot.com/assets/sunny.png', version='1.0', profile_url='http://code.google.com/p/firstwave/wiki/DrWeather') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) #myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "2.0" '''Dr. Weather, a Google Wave robot. Gives the weather of a city. Intro: http://code.google.com/p/firstwave/wiki/DrWeather ''' import logging import re import urllib2 from waveapi import events from waveapi import model from waveapi import robot from waveapi import document import gwapi CMD_NO = 'drweather:no' CMD_HELP = 'drweather:help' URL_GOOGLE = 'http://www.google.com' STR_USAGE = '''Usage: [city] [city,country] [city,,language-code] [city,country,language-code] (More: http://code.google.com/p/firstwave/wiki/DrWeather)''' logger = logging.getLogger('Dr_Weather') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can see the future!\n"+STR_USAGE) def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" logger.debug('OnParticipantsChanged()') added = properties['participantsAdded'] for p in added: if p != 'shiny-sky@appspot.com' and p != 'dr-weather@appspot.com': Notify(context, "Do you wanna know weather information? Ask me!\n"+STR_USAGE) break def OnBlipSubmit(properties, context): """Invoked when new blip submitted. append rich formatted text to blip""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() newdoc = None try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass if CMD_NO in text: return if CMD_HELP in text: newBlip = doc.AppendInlineBlip() newdoc = newBlip.GetDocument() newdoc.SetText(STR_USAGE) queries = re.findall(r"(?i)\[([^,\[\]]+(,[^,\[\]]*)?)(,([a-z]{2}(-[a-z]{2})?)?)?\]", text) #Iterate through search strings for q in queries: city = q[0].strip().encode('utf-8') lang = q[3].strip() logger.info('query: %s'+str(q)) city = urllib2.quote(city) logger.debug('quote city: %s' % city) weather_data = gwapi.get_weather_from_google(city, lang) if weather_data: if newdoc == None: newBlip = doc.AppendInlineBlip() newdoc = newBlip.GetDocument() gooleWeatherConverter(weather_data, newdoc) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) def Fahrenheit2Celsius(F): '''convert F to C''' try: f = int(F) c = int(round((f-32)*5.0/9.0)) return str(c) except: return '(N/A)' def Celsius2Fahrenheit(C): '''convert C to F''' try: c = int(C) f = int(round(c*9.0/5.0+32)) return str(f) except: return '(N/A)' def TempConverter(t, u): '''temp temparature converter if we support multi languages in the future, this func is not needed any more. ''' if u.upper() == 'US': return u'%s°C(%s°F)'%(Fahrenheit2Celsius(t),t) else:# u == 'SI': return u'%s°C(%s°F)'%(t, Celsius2Fahrenheit(t)) def getImageObj(url): return document.Image(URL_GOOGLE+url) def gooleWeatherConverter(weatherData, doc): '''convert data to html/txt''' doc.AppendText(' \n\n ') doc.AppendElement(getImageObj(weatherData['current_conditions']['icon'])) doc.AppendText(u'\n%s\n%s, %s°C(%s°F)\n%s\n%s \n\n ' % ( weatherData['forecast_information']['city'].upper(), weatherData['current_conditions']['condition'], weatherData['current_conditions']['temp_c'], weatherData['current_conditions']['temp_f'], weatherData['current_conditions']['humidity'], weatherData['current_conditions']['wind_condition'])) for day in weatherData['forecasts']: doc.AppendElement(getImageObj(day['icon'])) doc.AppendText(u' %s: %s, %s ~ %s\n '%(day['day_of_week'], day['condition'], TempConverter(day['low'], weatherData['forecast_information']['unit_system']), TempConverter(day['high'], weatherData['forecast_information']['unit_system']))) if __name__ == '__main__': myRobot = robot.Robot('DrWeather', image_url='http://shiny-sky.appspot.com/assets/sunny.png', version='1.0', profile_url='http://code.google.com/p/firstwave/wiki/DrWeather') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) #myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- #Copyright (c) 2009 Eugene Kaznacheev <qetzal@gmail.com> #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. __author__ = 'shinysky' __license__ = "Apache License 2.0" __version__ = "2.0" """ Fetches weather reports from Google Weather """ import urllib2, re, logging from xml.dom import minidom GOOGLE_WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s' def get_weather_from_google(location_id, hl = ''): """ Fetches weather report from Google Parameters location_id: a zip code (10001); city name, state (weather=woodland,PA); city name, country (weather=london,england); or possibly others. hl: the language parameter (language code) Returns: weather_data: a dictionary of weather data that exists in XML feed. """ url = GOOGLE_WEATHER_URL % (location_id, hl) handler = urllib2.urlopen(url) content_type = handler.info().dict['content-type'] charset = re.search('charset\=(.*)',content_type).group(1) logging.debug('charset: %s' % charset) if charset.upper() == 'GB2312': charset = 'GB18030' xml_response = handler.read().decode(charset).encode('utf-8') dom = minidom.parseString(xml_response) handler.close() try: weather_data = {} weather_dom = dom.getElementsByTagName('weather')[0] data_structure = { 'forecast_information': ('city', 'postal_code', 'latitude_e6', 'longitude_e6', 'forecast_date', 'current_date_time', 'unit_system'), 'current_conditions': ('condition','temp_f', 'temp_c', 'humidity', 'wind_condition', 'icon') } for (tag, list_of_tags2) in data_structure.iteritems(): tmp_conditions = {} for tag2 in list_of_tags2: tmp_conditions[tag2] = weather_dom.getElementsByTagName(tag)[0].getElementsByTagName(tag2)[0].getAttribute('data') weather_data[tag] = tmp_conditions forecast_conditions = ('day_of_week', 'low', 'high', 'icon', 'condition') forecasts = [] for forecast in dom.getElementsByTagName('forecast_conditions'): tmp_forecast = {} for tag in forecast_conditions: tmp_forecast[tag] = forecast.getElementsByTagName(tag)[0].getAttribute('data') forecasts.append(tmp_forecast) weather_data['forecasts'] = forecasts dom.unlink() return weather_data except: return None
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging import re import urllib2, urlparse from waveapi import simplejson URL_TINYURL_PREVIEW = 'http://tinyurl.com/preview.php?num=%s' URL_TINYURL_HOST = 'tinyurl.com' URL_BITLY_EXPAND = 'http://api.bit.ly/expand?version=2.0.1&shortUrl=%s&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07' logger = logging.getLogger('BotURL') logger.setLevel(logging.DEBUG) hdlr = logging.FileHandler('boturl.log') logger.addHandler(hdlr) def getMatchGroup(text): """return URL match groups""" return re.findall(r"(?i)((https?|ftp|telnet|file|ms-help|nntp|wais|gopher|notes|prospero):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&]*))", text) def httpGet(url): logger.debug('urlfetch: %s' % url) handler = urllib2.urlopen(url) response = handler.read() try: logging.debug(str(handler.info())) charsets = set(['utf-8','GB18030','ISO-8859-1']) content_type = handler.info().dict['content-type'] csMat = re.search('charset\=(.*)',content_type) if csMat: charset = csMat.group(1) logging.debug('charset: %s' % charset) if charset.upper() == 'GB2312': charset = 'GB18030' response = response.decode(charset)#.encode('utf-8') else: for cs in charsets: try: logger.debug('try decode with %s'%cs) response = response.decode(cs)#.encode('utf-8') break except: logger.debug('trying decode with %s failed'%cs) continue except: pass handler.close() return response def getTitle(url): '''return user name''' pageStr = httpGet(url) #logger.debug('pageStr: %s' % pageStr) title = re.findall(r'''<title>(.*?)</title>''', pageStr) if title: return title[0].strip() else: return 'no title' def OnBlipSubmit(): """Invoked when new blip submitted. """ while True: text = raw_input('query:') queries = getMatchGroup(text) #print queries if queries: print 'find %d queries...' % len(queries) #Iterate through search strings for q in queries: print q title = getTitle(q[0]) print title logger.debug('title: %s' % title) if __name__ == '__main__': OnBlipSubmit()
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "1.0" '''BotURL, a Google Wave robot. Replace URLs with hyperlinks. Usage: Just add me as a participant, I will take care of the rest ''' import logging import re import urllib2, urlparse from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi import simplejson URL_TINYURL = 'http://tinyurl.com/api-create.php?url=%s' URL_TINYURL_PREVIEW = 'http://tinyurl.com/preview.php?num=%s' URL_BITLY_EXPAND = 'http://api.bit.ly/expand?version=2.0.1&shortUrl=%s&login=shinysky&apiKey=R_94be00f8f2d2cb123a10665b6728666b' CMD_NO = 'boturl:no' CMD_TITLE = 'boturl:title' CMD_SLEEP = 'boturl:goodnight' CMD_WAKEUP = 'boturl:wakeup' CMD_HELP = 'boturl:help' STR_LINK_TEXT = '[%s/...]' STR_LINK_TEXT_S = '[%s]' STR_USAGE = '''\nCommand: %s - BotURL will leave this blip alone %s - (NOT stable!)BotURL will replace the URLs in this blip with page titles %s - Print this help message More: http://code.google.com/p/firstwave/wiki/BotURL''' % (CMD_NO, CMD_TITLE, CMD_HELP) #%s - Deactivate BotURL in this wave #%s - Activate BotURL in this wave ISACTIVE = True logger = logging.getLogger('BotURL') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can replace full URLs with hyperlinks!\n"+STR_USAGE) def getMatchGroup(text): """return URL match groups""" return re.findall(r"(?i)((https?|ftp|telnet|file|ms-help|nntp|wais|gopher|notes|prospero):((//)|(\\\\))+([^\s]*))", text) def respDecode(pageStr, charset): if charset.upper() == 'GB2312': charset = 'GB18030' return pageStr.decode(charset) def httpGet(url): logger.debug('urlfetch: %s' % url) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] try: handler = opener.open(url) except: return '' response = handler.read() try: logging.debug(str(handler.info())) content_type = handler.info().dict['content-type'] csMat = re.search('(?i)charset=(.*)',content_type) if csMat: charset = csMat.group(1) logging.debug('charset: %s' % charset) response = respDecode(response, charset) else: #find charset from html head logging.debug('trying to search charset from html head') csMat = re.search(r'(?i)<head>.*<meta [^>]*charset=([\w-]+)[^>]*>.*</head>',response,re.DOTALL) if csMat: logging.debug('found') charset = csMat.group(1) charset = charset.replace('"','') charset = charset.strip() logging.debug('charset from meta: %s' % charset) response = respDecode(response, charset) else: logging.debug('not found') charsets = set(['utf-8','GB18030','Big5', 'EUC_CN','EUC_TW', 'Shift_JIS','EUC_JP','EUC-KR', 'ISO-8859-1','cp1251','windows-1251']) for cs in charsets: try: logger.debug('trying to decode with %s'%cs) response = response.decode(cs)#.encode('utf-8') break except: logger.debug('decoding with %s failed'%cs) continue except: pass handler.close() return response def getTitle(url): '''return user name''' pageStr = httpGet(url) title = re.findall(r'''(?is)<title>(.*?)</title>''', pageStr) if title: #logger.debug('title: %s' % title) return title[0].strip() logger.debug('pageStr: %s' % pageStr) return None def getLinkText(url, useTitle = False): '''return title of hyperlink, e.g. '[title.com/...]' ''' if useTitle: title = getTitle(url) if title: return STR_LINK_TEXT_S % title pu = urlparse.urlparse(url) host = pu.hostname if host.startswith('www.'): host = host[4:] path = pu.path.replace('/','') path = path.replace('\\','') if path == '': return STR_LINK_TEXT_S % host return STR_LINK_TEXT % host def OnBlipSubmit(properties, context): """Invoked when new blip submitted.""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() left = 0 useTitle = False try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass #global ISACTIVE #if CMD_WAKEUP in text: # logger.debug('active') # ISACTIVE = True #elif CMD_SLEEP in text: # logger.debug('deactive') # ISACTIVE = False #if not ISACTIVE: # return if CMD_NO in text: return if CMD_HELP in text: newBlip = blip.CreateChild() newBlip.GetDocument().SetText(STR_USAGE) if CMD_TITLE in text: useTitle = True queries = getMatchGroup(text) #Iterate through search strings for q in queries: fullurl = q[0] logger.info('query: %s' % fullurl) left = text.find(fullurl, left) if left < 0: logger.error('failed to find a matched string: %s' % fullurl) continue replaceRange = document.Range(left, left+len(fullurl)) if fullurl.startswith('http://tinyurl.com/'): tMat = re.match(r'(?i)^http://tinyurl.com/(\w+)$', fullurl) if tMat: #http://tinyurl.com/preview.php?num=dehdc url = URL_TINYURL_PREVIEW % (tMat.groups()[0]) response = httpGet(url) if response: oriurls = re.findall(r'(?i)<a id="redirecturl" href="([^<>]+)">', response) if oriurls: fullurl = oriurls[0] elif fullurl.startswith('http://bit.ly/'): bMat = re.match(r'(?i)^http://bit.ly/(\w+)$', fullurl) if bMat: url = URL_BITLY_EXPAND % fullurl response = httpGet(url) if response: bJson = simplejson.loads(response) #{u'errorCode': 0, u'errorMessage': u'', u'results': {u'31IqMl': {u'longUrl': u'http://cnn.com/'}}, u'statusCode': u'OK'} if bJson[u'errorCode'] == 0: fullurl = bJson[u'results'][bMat.groups()[0]][u'longUrl'] linkTxt = getLinkText(fullurl, useTitle) doc.SetTextInRange(replaceRange, linkTxt) doc.SetAnnotation(document.Range(left, left+len(linkTxt)), "link/manual", fullurl) text = text.replace(text[replaceRange.start:replaceRange.end], linkTxt, 1) left += len(linkTxt) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) if __name__ == '__main__': myRobot = robot.Robot('BotURL', image_url='http://boturl.appspot.com/assets/icon.png', version='2.0', profile_url='http://code.google.com/p/firstwave/wiki/BotURL') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "1.0" '''BotURL, a Google Wave robot. Replace URLs with hyperlinks. Usage: Just add me as a participant, I will take care of the rest ''' import logging import re import urllib2, urlparse from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi import simplejson URL_TINYURL = 'http://tinyurl.com/api-create.php?url=%s' URL_TINYURL_PREVIEW = 'http://tinyurl.com/preview.php?num=%s' URL_BITLY_EXPAND = 'http://api.bit.ly/expand?version=2.0.1&shortUrl=%s&login=shinysky&apiKey=R_94be00f8f2d2cb123a10665b6728666b' CMD_NO = 'boturl:no' CMD_TITLE = 'boturl:title' CMD_SLEEP = 'boturl:goodnight' CMD_WAKEUP = 'boturl:wakeup' CMD_HELP = 'boturl:help' STR_LINK_TEXT = '[%s/...]' STR_LINK_TEXT_S = '[%s]' STR_USAGE = '''\nCommand: %s - BotURL will leave this blip alone %s - (NOT stable!)BotURL will replace the URLs in this blip with page titles %s - Print this help message More: http://code.google.com/p/firstwave/wiki/BotURL''' % (CMD_NO, CMD_TITLE, CMD_HELP) #%s - Deactivate BotURL in this wave #%s - Activate BotURL in this wave ISACTIVE = True logger = logging.getLogger('BotURL') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I can replace full URLs with hyperlinks!\n"+STR_USAGE) def getMatchGroup(text): """return URL match groups""" return re.findall(r"(?i)((https?|ftp|telnet|file|ms-help|nntp|wais|gopher|notes|prospero):((//)|(\\\\))+([^\s]*))", text) def respDecode(pageStr, charset): if charset.upper() == 'GB2312': charset = 'GB18030' return pageStr.decode(charset) def httpGet(url): logger.debug('urlfetch: %s' % url) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] try: handler = opener.open(url) except: return '' response = handler.read() try: logging.debug(str(handler.info())) content_type = handler.info().dict['content-type'] csMat = re.search('(?i)charset=(.*)',content_type) if csMat: charset = csMat.group(1) logging.debug('charset: %s' % charset) response = respDecode(response, charset) else: #find charset from html head logging.debug('trying to search charset from html head') csMat = re.search(r'(?i)<head>.*<meta [^>]*charset=([\w-]+)[^>]*>.*</head>',response,re.DOTALL) if csMat: logging.debug('found') charset = csMat.group(1) charset = charset.replace('"','') charset = charset.strip() logging.debug('charset from meta: %s' % charset) response = respDecode(response, charset) else: logging.debug('not found') charsets = set(['utf-8','GB18030','Big5', 'EUC_CN','EUC_TW', 'Shift_JIS','EUC_JP','EUC-KR', 'ISO-8859-1','cp1251','windows-1251']) for cs in charsets: try: logger.debug('trying to decode with %s'%cs) response = response.decode(cs)#.encode('utf-8') break except: logger.debug('decoding with %s failed'%cs) continue except: pass handler.close() return response def getTitle(url): '''return user name''' pageStr = httpGet(url) title = re.findall(r'''(?is)<title>(.*?)</title>''', pageStr) if title: #logger.debug('title: %s' % title) return title[0].strip() logger.debug('pageStr: %s' % pageStr) return None def getLinkText(url, useTitle = False): '''return title of hyperlink, e.g. '[title.com/...]' ''' if useTitle: title = getTitle(url) if title: return STR_LINK_TEXT_S % title pu = urlparse.urlparse(url) host = pu.hostname if host.startswith('www.'): host = host[4:] path = pu.path.replace('/','') path = path.replace('\\','') if path == '': return STR_LINK_TEXT_S % host return STR_LINK_TEXT % host def OnBlipSubmit(properties, context): """Invoked when new blip submitted.""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() left = 0 useTitle = False try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass #global ISACTIVE #if CMD_WAKEUP in text: # logger.debug('active') # ISACTIVE = True #elif CMD_SLEEP in text: # logger.debug('deactive') # ISACTIVE = False #if not ISACTIVE: # return if CMD_NO in text: return if CMD_HELP in text: newBlip = blip.CreateChild() newBlip.GetDocument().SetText(STR_USAGE) if CMD_TITLE in text: useTitle = True queries = getMatchGroup(text) #Iterate through search strings for q in queries: fullurl = q[0] logger.info('query: %s' % fullurl) left = text.find(fullurl, left) if left < 0: logger.error('failed to find a matched string: %s' % fullurl) continue replaceRange = document.Range(left, left+len(fullurl)) if fullurl.startswith('http://tinyurl.com/'): tMat = re.match(r'(?i)^http://tinyurl.com/(\w+)$', fullurl) if tMat: #http://tinyurl.com/preview.php?num=dehdc url = URL_TINYURL_PREVIEW % (tMat.groups()[0]) response = httpGet(url) if response: oriurls = re.findall(r'(?i)<a id="redirecturl" href="([^<>]+)">', response) if oriurls: fullurl = oriurls[0] elif fullurl.startswith('http://bit.ly/'): bMat = re.match(r'(?i)^http://bit.ly/(\w+)$', fullurl) if bMat: url = URL_BITLY_EXPAND % fullurl response = httpGet(url) if response: bJson = simplejson.loads(response) #{u'errorCode': 0, u'errorMessage': u'', u'results': {u'31IqMl': {u'longUrl': u'http://cnn.com/'}}, u'statusCode': u'OK'} if bJson[u'errorCode'] == 0: fullurl = bJson[u'results'][bMat.groups()[0]][u'longUrl'] linkTxt = getLinkText(fullurl, useTitle) doc.SetTextInRange(replaceRange, linkTxt) doc.SetAnnotation(document.Range(left, left+len(linkTxt)), "link/manual", fullurl) text = text.replace(text[replaceRange.start:replaceRange.end], linkTxt, 1) left += len(linkTxt) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) if __name__ == '__main__': myRobot = robot.Robot('BotURL', image_url='http://boturl.appspot.com/assets/icon.png', version='2.0', profile_url='http://code.google.com/p/firstwave/wiki/BotURL') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "1.0" '''TiHistory, a Google Wave robot. Usage: Just add me as a participant, I will take care of the rest ''' import logging import re import urllib2, urlparse from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi import simplejson STR_USAGE = '''\nToday in the history''' logger = logging.getLogger('TiHistory') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I know what happened today in the history!\n"+STR_USAGE) def respDecode(pageStr, charset): if charset.upper() == 'GB2312': charset = 'GB18030' return pageStr.decode(charset) def httpGet(url): logger.debug('urlfetch: %s' % url) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] try: handler = opener.open(url) except: return '' response = handler.read() try: logging.debug(str(handler.info())) content_type = handler.info().dict['content-type'] csMat = re.search('charset\=(.*)',content_type) if csMat: charset = csMat.group(1) logging.debug('charset: %s' % charset) response = respDecode(response, charset) else: #find charset from html head logging.debug('trying to search charset from html head') csMat = re.search(r'(?i)<head>.*<meta http-equiv=[^>]*charset\=([^>]*)>.*</head>',response,re.DOTALL) if csMat: logging.debug('found') charset = csMat.group(1) charset = charset.replace('"','') charset = charset.strip() logging.debug('charset from meta: %s' % charset) response = respDecode(response, charset) else: logging.debug('not found') charsets = set(['utf-8','GB18030','Big5', 'EUC_CN','EUC_TW', 'Shift_JIS','EUC_JP','EUC-KR', 'ISO-8859-1','cp1251','windows-1251']) for cs in charsets: try: logger.debug('trying to decode with %s'%cs) response = response.decode(cs)#.encode('utf-8') break except: logger.debug('decoding with %s failed'%cs) continue except: pass handler.close() return response def getTitle(url): '''return user name''' pageStr = httpGet(url) #logger.debug('pageStr: %s' % pageStr) title = re.findall(r'''<title>(.*?)</title>''', pageStr) if title: return title[0].strip() return None def OnBlipSubmit(properties, context): """Invoked when new blip submitted.""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass pageStr = httpGet('http://zh.wikipedia.org/w/index.php?title=12%E6%9C%8831%E6%97%A5&variant=zh') newBlip = doc.AppendInlineBlip() newBlip.GetDocument().SetText(pageStr) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) if __name__ == '__main__': myRobot = robot.Robot('TodayInHistory', image_url='http://TiHistory.appspot.com/assets/icon.png', version='1.0', profile_url='http://TiHistory.appspot.com/assets/profile.html') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) myRobot.Run(debug=True)
Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = "shinysky" __license__ = "Apache License 2.0" __version__ = "1.0" '''TiHistory, a Google Wave robot. Usage: Just add me as a participant, I will take care of the rest ''' import logging import re import urllib2, urlparse from waveapi import events from waveapi import model from waveapi import robot from waveapi import document from waveapi import simplejson STR_USAGE = '''\nToday in the history''' logger = logging.getLogger('TiHistory') logger.setLevel(logging.DEBUG) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" logger.debug('OnRobotAdded()') Notify(context, "Hi, everybody, I know what happened today in the history!\n"+STR_USAGE) def respDecode(pageStr, charset): if charset.upper() == 'GB2312': charset = 'GB18030' return pageStr.decode(charset) def httpGet(url): logger.debug('urlfetch: %s' % url) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] try: handler = opener.open(url) except: return '' response = handler.read() try: logging.debug(str(handler.info())) content_type = handler.info().dict['content-type'] csMat = re.search('charset\=(.*)',content_type) if csMat: charset = csMat.group(1) logging.debug('charset: %s' % charset) response = respDecode(response, charset) else: #find charset from html head logging.debug('trying to search charset from html head') csMat = re.search(r'(?i)<head>.*<meta http-equiv=[^>]*charset\=([^>]*)>.*</head>',response,re.DOTALL) if csMat: logging.debug('found') charset = csMat.group(1) charset = charset.replace('"','') charset = charset.strip() logging.debug('charset from meta: %s' % charset) response = respDecode(response, charset) else: logging.debug('not found') charsets = set(['utf-8','GB18030','Big5', 'EUC_CN','EUC_TW', 'Shift_JIS','EUC_JP','EUC-KR', 'ISO-8859-1','cp1251','windows-1251']) for cs in charsets: try: logger.debug('trying to decode with %s'%cs) response = response.decode(cs)#.encode('utf-8') break except: logger.debug('decoding with %s failed'%cs) continue except: pass handler.close() return response def getTitle(url): '''return user name''' pageStr = httpGet(url) #logger.debug('pageStr: %s' % pageStr) title = re.findall(r'''<title>(.*?)</title>''', pageStr) if title: return title[0].strip() return None def OnBlipSubmit(properties, context): """Invoked when new blip submitted.""" blip = context.GetBlipById(properties['blipId']) doc = blip.GetDocument() text = doc.GetText() try: logger.debug('creator: %s' % blip.GetCreator()) logger.debug('text: %s' % text) except: pass pageStr = httpGet('http://zh.wikipedia.org/w/index.php?title=12%E6%9C%8831%E6%97%A5&variant=zh') newBlip = doc.AppendInlineBlip() newBlip.GetDocument().SetText(pageStr) def Notify(context, message): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(message) if __name__ == '__main__': myRobot = robot.Robot('TodayInHistory', image_url='http://TiHistory.appspot.com/assets/icon.png', version='1.0', profile_url='http://TiHistory.appspot.com/assets/profile.html') myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit) myRobot.Run(debug=True)
Python
#!/usr/bin/python # Copyright 2011 Muthu Kannan. All Rights Reserved. # # Script that searches for a string in a Blogger export XML file. import getopt import re import sys from xml.dom import minidom BLOGGER_HOST = 'draft.blogger.com' def FindPostsWithString(xml_doc, search_string): ids = [] for entry in xml_doc.getElementsByTagName('entry'): all_ids = entry.getElementsByTagName('id') if len(all_ids) != 1: print >>sys.stderr, 'Ignoring entry with %d ids.' % len(all_ids) continue entry_id = all_ids[0].childNodes[0].data if not re.match('^tag:blogger.com,1999:blog-\\d+.post-\\d+$', entry_id): continue all_contents = entry.getElementsByTagName('content') if len(all_contents) != 1: print >>sys.stderr, 'Ignoring entry with %d contents.' % len(all_contents) continue if search_string in all_contents[0].childNodes[0].data: ids.append(entry_id) return map(ParsePostIdString, ids) def ParsePostIdString(id_str): match = re.match('tag:blogger.com,1999:blog-(\\d+).post-(\\d+)', id_str) return {'blog_id': match.group(1), 'post_id': match.group(2)} def GetEditPostLink(post_info): return 'http://%s/post-edit.g?blogID=%s&postID=%s' % ( BLOGGER_HOST, post_info['blog_id'], post_info['post_id']) def main(): optlist, unused_args = getopt.gnu_getopt(sys.argv[1:], 'b:s:', ('blog=', 'search=')) if len(optlist) != 2: print >>sys.stderr, '%s -b blog_xml_file -s search_string' % sys.argv[0] return for opt, value in optlist: if opt in ('-b', '--blog'): blogger_xml_file = value elif opt in ('-s', '--search'): search_string = value post_ids = FindPostsWithString(minidom.parse(blogger_xml_file), search_string) print '\n'.join(map(GetEditPostLink, post_ids)) if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright 2010 Muthu Kannan. All Rights Reserved. # # Sets up an SSH tunnel and starts Synergy Client. import errno import os import signal import socket import subprocess import time SSH = '/usr/bin/ssh' SYNERGYC = '/usr/bin/synergyc' LOCAL_HOST = 'localhost' SERVER = 'SERVER_HOST_NAME' SYNERGY_PORT = 24800 LOCAL_PORT = 10100 LOCAL_SYNERGY_SERVER = '%s:%s' % (LOCAL_HOST, LOCAL_PORT) KEEP_ALIVE = 'while true; do echo -n ""; sleep 60; done' TUNNEL_ARG = '-L%s:%d:%s:%d' % (LOCAL_HOST, LOCAL_PORT, SERVER, SYNERGY_PORT) synergyc = None tunnel = None killing = False def Quit(*args): """Closes the tunnel and quits Synergy.""" global killing killing = True KillProcesses() def KillProcesses(): for process in (synergyc, tunnel): if process and (process.returncode is None): os.kill(process.pid, signal.SIGINT) def OpenTunnel(): return subprocess.Popen((SSH, TUNNEL_ARG, SERVER, KEEP_ALIVE)) def WaitForTunnelToOpen(): MAX_ATTEMPTS = 5 num_attempts = 0 sock = None while num_attempts < MAX_ATTEMPTS: num_attempts += 1 try: sock = socket.create_connection((LOCAL_HOST, LOCAL_PORT), 5.0) except socket.error, err: if err.errno == errno.ECONNREFUSED: time.sleep(1) if sock: sock.close() def StartSynergyc(): return subprocess.Popen((SYNERGYC, '-f', '--no-restart', LOCAL_SYNERGY_SERVER)) def main(): signal.signal(signal.SIGINT, Quit) while not killing: global synergyc, tunnel tunnel = OpenTunnel() WaitForTunnelToOpen() synergyc = StartSynergyc() try: synergyc.wait() except OSError: # When tunnel is killed, we get OSError. pass KillProcesses() if __name__ == '__main__': main()
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: user_id=i.admissionnumber if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: self.redirect("/usererror") return team=db.GqlQuery("SELECT * FROM teamDetails") project=db.GqlQuery("SELECT * FROM projectDetails") notif=db.GqlQuery("SELECT * FROM notificationDetails") qns=db.GqlQuery("SELECT * FROM questionanswer") tid=[] ti=[] temp=[] fla=0 for i in team: stri=i.teammember b=stri.split(',') for j in b: if (user_id==j): tid.append(i.projectids) t=[] for i in notif : if i.admissionnumber==user_id: temp1=[i.notification,i.notificationid] t.append(temp1) ans=[] for i in qns : if i.admissionnumber==user_id: temp1=[i.question,i.answer,i.questionid] ans.append(temp1) for i in project: for j in tid: temp=[] if i.projectid==j: temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed] ti.append(temp) path = os.path.join(os.path.dirname(__file__),'tab.html')#use template self.response.out.write(template.render(path,{"items":ti,"noti":t,"email":user.email(),"ans":ans}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) def post(self): delid=self.request.get("delval") if delid: notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid)) for i in notif : i.delete() delid=self.request.get("delans") if delid: ans=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s'"%(delid)) for i in ans : i.delete() self.redirect("/") application=webapp.WSGIApplication([('/user',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime global ids class MainPage(webapp.RequestHandler,db.Model): global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global ids ids=self.request.get("ids") category=[] c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: temp=[] temp.append(i.fieldname.replace(" ","_")) temp.append(i.fieldname) category.append(temp) lang=[] c1=db.GqlQuery("SELECT * FROM languages") for i in c1: lang.append(i.language) path = os.path.join(os.path.dirname(__file__),'create.html')#use template self.response.out.write(template.render(path,{"category":category,"language":lang}))#using template def post(self): global ids pro=db.GqlQuery("SELECT * FROM projectDetails") for k in pro: if k.projectid==ids: break c1=db.GqlQuery("SELECT * FROM languages") k.languages="" for i in c1: if self.request.get(i.language)=="yes": if k.languages=="": k.languages=k.languages+i.languageid else: k.languages=k.languages+","+i.languageid c1=db.GqlQuery("SELECT * FROM projectFields") k.fieldnames="" for i in c1: if self.request.get(i.fieldname.replace(" ","_"))=="yes": if(k.fieldnames==""): k.fieldnames=k.fieldnames+i.fieldid else: k.fieldnames=k.fieldnames+","+i.fieldid k.projectname=self.request.get("projectname") k.abstract=self.request.get("abstrct") k.link=self.request.get("link") k.confirmed=False k.put() c1=db.GqlQuery("SELECT * FROM teamDetails") for i in c1: if i.teamid==k.teamid: team=i.teammember.split(",") c2=db.GqlQuery("SELECT * FROM userDetails") for j in c2: if j.admissionnumber in team: if j.projectids==None: j.projectids=ids else: j.projectids=j.projectids+','+ids j.put() self.redirect("/user") application = webapp.WSGIApplication([('/create', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
"""Models""" from google.appengine.ext import db class userDetails(db.Model): #To store individual student details username=db.StringProperty() #Student name email=db.EmailProperty() #Email of student mobilenumber=db.StringProperty() #Mobile phone number admissionnumber=db.StringProperty() #Admission number branch=db.StringProperty() #College department projectids=db.StringProperty() #Current project IDs privilege=db.StringProperty() #User/administrator timestamp=db.DateTimeProperty(auto_now_add=True) #Data entry time approved=db.BooleanProperty() #Approval status class projectDetails(db.Model): #To store details of confirmed projects to be undertaken projectname=db.StringProperty() #Project name projectid=db.StringProperty() #Project ID teamid=db.StringProperty() #Team ID of team undertaking this project category=db.StringProperty() #Categories under which the project falls languages=db.StringProperty() #Programming languages fieldnames=db.StringProperty() #Field span of the project abstract=db.StringProperty() #Abstract of the project reviewdate=db.StringProperty() #Next review date confirmed=db.BooleanProperty() #Whether project is approved or not maxmembers=db.StringProperty() #Number of members per project (admin property) link=db.StringProperty() #Reference link class teamDetails(db.Model): #Details of individual teams teamid=db.StringProperty() #Team ID teammember=db.StringProperty() #Team members (number variable) projectids=db.StringProperty() #Project IDs of projects under this team locked=db.BooleanProperty() #Team members lock property class projectPool(db.Model): #Holds details of projects in the project pool poolprojectid=db.StringProperty() #Temporary project ID in the pool projectname=db.StringProperty() #Project name languages=db.StringProperty() #Programming languages abstract=db.StringProperty() #Project abstract category=db.StringProperty() fieldnames=db.StringProperty() lock=db.BooleanProperty() class projectCategory(db.Model): #Admin facility to store project categories categoryid=db.StringProperty() #Category ID categorytype=db.StringProperty() #The name of the category itself maxmembers=db.IntegerProperty() #Maximum number of members in a team who can undertake this type of project maxprojects=db.IntegerProperty() class notificationDetails(db.Model): #Details of notifications notificationid=db.StringProperty() #Notification ID admissionnumber=db.StringProperty() #Users who are concerned with the notification notification=db.StringProperty() #The notification itself class languages(db.Model): #Programming languages offered languageid=db.StringProperty() #ID of the programming language language=db.StringProperty() #Programming language class projectFields(db.Model): #Fields of the projects e.g.ML,HPC,Robotics... fieldid=db.StringProperty() #Field ID fieldname=db.StringProperty() #Name of the field class questionanswer(db.Model): #Q&A facility admissionnumber=db.StringProperty() #User ID that generated the question questionid=db.StringProperty() #Unique question ID question=db.StringProperty() #The question itself answer=db.StringProperty() #Answer
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ from models import * import datetime import random import re logout="""<p><a href="http://localhost:8080/_ah/login?continue=http%3A//localhost%3A8080/&action=Logout">Logout</a></p>""" go=""" <form action="/choice" method="get"> <input type="submit" value="Continue"> </form> """ class notificationPage(webapp.RequestHandler,db.Model): def get(self): global user,usr user = users.get_current_user() if user: self.response.out.write('Hello, '+user.nickname()) path = os.path.join(os.path.dirname(__file__),'test.html') self.response.out.write(template.render(path,{})) self.response.out.write(logout) else: self.redirect(users.create_login_url(self.request.uri)) def validate_emailid(self,emailid): #validating email ids if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)): return 1 else: return 0 def post(self): user = users.get_current_user() u=user.email() email=self.request.get("emailadr") emailid=email.split(',') n=1 f=0 f2=0 rest="" not_id="" frm_usrid="" userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==u): frm_usrid=usr.userid f2=0 break else: f2=1 if (f2!=0): self.response.out.write("No user details available for current user! \n") else: for i in emailid: a=i if(a!=""): check=self.validate_emailid(i) if(check==1): userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==a): rest=usr.userid+', '+rest not_id="NOTIFICATION"+str(random.randint(0,400)) n=notificationDetails(notificationid=not_id,frm_userid=frm_usrid,to_userid=usr.userid) n.put() path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':' Notifications sent to: '+i})) f=emailid.index(a) else: not_found=emailid.index(a) if (f<emailid.index(a)): path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':'No records found for :'+a})) else: path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':i+' is not a valid email id!'})) if(rest!=""): tid="CS"+str(random.randint(0,140)) team=teamDetails(teamid=tid,teammember=rest+frm_usrid) team.put() self.response.out.write(go) application = webapp.WSGIApplication([('/', notificationPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ from models import * import datetime import random import re global ids class HelloPage(webapp.RequestHandler,db.Model): global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global user,usr user = users.get_current_user() global ids ids="" user = users.get_current_user() url = self.request.url flag=0 for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): ids=ids+url[i] i=i+1 flag=1 break if flag==0: ids=self.request.get("ids") if user: self.response.out.write('Hello, '+user.nickname()) self.response.out.write(ids) path = os.path.join(os.path.dirname(__file__),'notifications.html') self.response.out.write(template.render(path,{"ids":ids})) else: self.redirect(users.create_login_url(self.request.uri)) def validate_emailid(self,emailid): #validating email ids if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)): return 1 else: return 0 def check_user(self,admno): #checks if member to be added is in anyother team. global m m="" t1=db.GqlQuery("SELECT * FROM teamDetails") for i in t1: self.response.out.write("hello"); mem=i.teammember.split(',') for j in mem: if admno==j: m='user hit!' self.response.out.write(m) return 0 return 1 def post(self): global ids user = users.get_current_user() u=user.email() email=self.request.get("emailadr") emailid=email.split(',') n=1 f=0 f2=0 rest="" not_id="" frm_usrid="" global m m="" msg=[] check2=2 dont_enter=0 userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==u): sender=usr.username frm_usrid=usr.admissionnumber f2=0 break else: f2=1 if self.request.get("single")=="Continue": team=teamDetails(teammember=frm_usrid,projectids=ids) key=team.put() tid=key.id() team.teamid=str(tid) team.put() proj=db.GqlQuery("SELECT * FROM projectDetails") for i in proj: if i.projectid==ids: break i.teamid=str(tid) i.maxmembers=str(1) i.put() m='Single user successfully added!' msg.append(m) self.response.out.write(ids) path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html') self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids})) #passing message frm 1st loop to template else: max_members=1 for i in emailid: #1st loop to extract email ids frm list a=i if(a!=""): check=self.validate_emailid(i) if(check==1): userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: #2nd loop to retrieve userdetails (usr id) if (usr.email==a): admno=usr.admissionnumber check2=self.check_user(admno) self.response.out.write("<br>"+str(check2)+"<br>"); if check2==1: max_members=max_members+1 rest=usr.admissionnumber+','+rest message="You have been added to the team of '%s'" %sender n=notificationDetails(notificationid=not_id,admissionnumber=usr.admissionnumber,notification=message) key=n.put() noteid=key.id() n.notificationid=str(noteid) n.put() m='Notifications sent to: '+i msg.append(m) f=emailid.index(a) elif check2==0: m=a+' has been already added!' msg.append(m) f=emailid.index(a) dont_enter=1 else: not_found=emailid.index(a) if (f<emailid.index(a)): m='No Records found for: '+a msg.append(m) dont_enter=1 else: m=i+' is not a valid email id!' msg.append(m) dont_enter=1 if(rest!="" and dont_enter==0): team=teamDetails(teammember=rest+frm_usrid,projectids=ids) key=team.put() tid=key.id() team.teamid=str(tid) team.put() proj=db.GqlQuery("SELECT * FROM projectDetails") for i in proj: if i.projectid==ids: break i.teamid=str(tid) i.maxmembers=str(max_members) i.put() self.response.out.write(ids) path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html') self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids})) #passing message frm 1st loop to template class SentPage(webapp.RequestHandler,db.Model): global ids def get(self): global ids self.redirect("/choice?%s=id" %ids) application = webapp.WSGIApplication([('/notification', HelloPage),('/sent',SentPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class Language(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() languages=[] alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: tmp=[] tmp.append(language.languageid) tmp.append(language.language) languages.append(tmp) path = os.path.join(os.path.dirname(__file__),'language.html')#specify file name self.response.out.write(template.render(path,{"list":languages}))#var name 'list' and 'name' is used in html def post(self): lang=db.GqlQuery("SELECT * FROM languages") for i in lang: if self.request.get(i.languageid) != i.languageid: i.delete() langs=self.request.get("addlan") langid=langs.split(',') for i in langid: if i: la=languages(language=str(i)) key=la.put() idnum=key.id() la.languageid=str(idnum) la.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatelanguage', Language)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ReviewProjectSubmission(webapp.RequestHandler): global projectid def post(self): global projectid is_confirm = self.request.get('confirm', None) is_reject = self.request.get('reject', None) details=[] projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid) for project in projects: teamid=project.teamid pname=project.projectname members=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %teamid) mem=members if is_confirm: query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid) confirmMe = db.GqlQuery(query) for project in confirmMe: note="Your project '%s' has been confirmed" %project.projectname project.confirmed=True project.put() for i in mem: listmembers=i.teammember members=listmembers.split(",") for member in members: newnote=notificationDetails(admissionnumber=member,notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_reject: query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid) deleteMe = db.GqlQuery(query) for project in deleteMe: note="Your project '%s' has been rejected" %project.projectname project.delete() for i in mem: listmembers=i.teammember members=listmembers.split(",") for member in members: newnote=notificationDetails(admissionnumber=member,notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() else: raise Exception('no form action given') self.redirect("/reviewprojectmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global projectid projectid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): projectid=projectid+url[i] i=i+1 break currentproject=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'"%projectid) tmp=[] for project in currentproject: tmp1=[] tmp1.append(project.projectid) tmp1.append(project.projectname) tmp1.append(project.abstract) tmp1.append(project.languages) tmp1.append(project.category) tmp1.append(project.fieldnames) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'reviewproject.html')#use template self.response.out.write(template.render(path,{"review":tmp}))#using template class ReviewProjectMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() notConfirmed=db.GqlQuery("SELECT * FROM projectDetails WHERE confirmed=False") path = os.path.join(os.path.dirname(__file__),'reviewprojectmain.html')#use template tmp=[] for project in notConfirmed: tmp1=[] tmp1.append(project.projectname) tmp1.append(project.projectid) tmp.append(tmp1) self.response.out.write(template.render(path,{"projects":tmp}))#using template application = webapp.WSGIApplication([('/reviewprojectsubmission', ReviewProjectSubmission),('/reviewprojectmain', ReviewProjectMain)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class BrowseUserActivity(webapp.RequestHandler): def post(self): self.redirect("/browseuseractivitymain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %admissionnumber) for user in users: tmp=[] tmp.append(user.username) currentprojectids=user.projectids if(currentprojectids==None): self.redirect("/browseuseractivitymain") return projids=currentprojectids.split(",") tmp1=[] for pid in projids: currentprojects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %pid) for project in currentprojects: tmpprojs=project.projectname tmp1.append(tmpprojs) tmp.append(tmp1) break path = os.path.join(os.path.dirname(__file__),'browseuser.html')#use template self.response.out.write(template.render(path,{"details":tmp}))#using template class BrowseUserActivityMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() users=db.GqlQuery("SELECT * FROM userDetails") tmp=[] for user in users: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp1.append(user.branch) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'browseusermain.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/browseuseractivitymain', BrowseUserActivityMain),('/browseuseractivity', BrowseUserActivity)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class EditUser(webapp.RequestHandler): global admissionnumber def post(self): global admissionnumber is_confirm = self.request.get('confirm', None) is_cancel = self.request.get('cancel', None) is_delete = self.request.get('delete', None) uname=self.request.get("username") umail=self.request.get("useremail") umobile=self.request.get("usermobile") uadmission=self.request.get("useradmission") ubranch=self.request.get("userbranch") uprivilege=self.request.get("userprivilege") users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) if is_confirm: for user in users: user.username=uname user.email=umail user.mobilenumber=umobile user.admissionnumber=uadmission user.privilege=uprivilege user.put() message="Your details have been edited by the administrator" newnote=notificationDetails(admissionnumber=admissionnumber,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_delete: for user in users: notesforme=db.GqlQuery("SELECT * FROM notificationDetails WHERE admissionnumber='%s'" %admissionnumber) for note in notesforme: note.delete() qnsfromme=db.GqlQuery("SELECT * FROM questionanswer WHERE admissionnumber='%s'" %admissionnumber) for qn in qnsfromme: qn.delete() userinteams=db.GqlQuery("SELECT * FROM teamDetails") for team in userinteams: members=team.teammember.split(",") for member in members: if member==uadmission: members.remove(member) newmembers='' for member in members: message="The member '%s' has been pulled out of your team" %uname newnote=notificationDetails(admissionnumber=member,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() if not newmembers: newmembers=member else: newmembers=newmembers+","+member team.teammember=newmembers team.put() user.delete() emptyteams=db.GqlQuery("SELECT * FROM teamDetails") for team in emptyteams: if team.teammember=="": team.delete() self.redirect("editusermain") return elif is_cancel: self.redirect("editusermain") return else: raise Exception('no form action given') self.redirect("/editusermain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global admissionnumber admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %admissionnumber) tmp=[] for user in users: path = os.path.join(os.path.dirname(__file__),'edituser.html')#use template self.response.out.write(template.render(path,{"name":user.username,"email":user.email,"mob":user.mobilenumber,"admno":user.admissionnumber,"branch":user.branch,"privilege":user.privilege}))#using template class EditUserMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() allusers=db.GqlQuery("SELECT * FROM userDetails") tmp=[] for user in allusers: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp1.append(user.email) tmp1.append(user.branch) tmp1.append(user.mobilenumber) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'editusermain.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/edituser', EditUser),('/editusermain', EditUserMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class AddToPool(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) languages=[] alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: tmp=[] tmp.append(language.languageid) tmp.append(language.language) languages.append(tmp) fieldnames=[] allfields=db.GqlQuery("SELECT * FROM projectFields") for fieldname in allfields: tmp=[] tmp.append(fieldname.fieldid) tmp.append(fieldname.fieldname) fieldnames.append(tmp) path = os.path.join(os.path.dirname(__file__),'addtopool.html')#use template self.response.out.write(template.render(path,{"category":category,"language":languages,"fieldname":fieldnames}))#using template def post(self): pname=self.request.get("projectname") pabstract=self.request.get("abstract") selcategory=self.request.get("category") catid=str(selcategory) pcategory=db.GqlQuery("SELECT * FROM projectCategory WHERE categoryid='%s'" %catid) for cat in pcategory: tmp=cat.categorytype pfields='' planguages='' allfields=db.GqlQuery("SELECT * FROM projectFields") alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: if(self.request.get("l"+language.languageid)=='yes'): if(planguages!=''): planguages=planguages+","+language.language else: planguages=language.language for fieldname in allfields: if(self.request.get("f"+fieldname.fieldid)=='yes'): if(pfields!=''): pfields=pfields+","+fieldname.fieldname else: pfields=fieldname.fieldname projecttopool=projectPool(projectname=pname,languages=planguages,category=tmp,abstract=pabstract,fieldnames=pfields,lock=False) key=projecttopool.put() idnum=key.id() projecttopool.poolprojectid=str(idnum) projecttopool.put() self.redirect("/admin") application = webapp.WSGIApplication([('/addtopool', AddToPool)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import string global category global project global fields global name global ids flag=False class MainPage(webapp.RequestHandler,db.Model): global category global project global fields global name global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global ids global category global project global fields ids=self.request.get("ids") category=[] project=[[],[],[],[],[],[]] fields=[] c1=db.GqlQuery("SELECT * FROM projectDetails") for i in c1: if i.projectid==ids: self.response.out.write("Hello") cat=i.category c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: tmp=[] tmp.append(i.fieldname.replace(" ","_")) tmp.append(i.fieldname) category.append(tmp) c1=db.GqlQuery("SELECT * FROM projectCategory") for i in c1: if i.categoryid==cat: cat=i.categorytype c1=db.GqlQuery("SELECT * FROM projectPool where category='%s'" %cat) for i in c1: if i.lock != True: project[0].append(i.projectname.replace(" ","_")) project[1].append(i.fieldnames.replace(" ","_")) project[2].append(i.abstract) project[3].append(i.lock) project[4].append(i.poolprojectid) project[5].append(i.languages) path = os.path.join(os.path.dirname(__file__),'pool.html')#use template self.response.out.write(template.render(path,{"category":category},"field"))#using template def post(self): #This is the function which calls topic.html name is the variable being pased global category global project global fields global name global ids name=[] path = os.path.join(os.path.dirname(__file__),'topic.html')#use template for i in category: if self.request.get(i[0])=="yes": fields.append(i[0]) field_names=[] f=1 temp=[] if fields : q=-1 for j in project[1]: temp=[] q=q+1 field_names=j.split(',') e=0 for k in field_names: e=e+1 temp=[] if k in fields: flag=True else: flag=False break if len(fields)!=e: flag=False if flag: f=0 self.response.out.write(f) temp.append(project[0][q]) temp.append(project[2][q]) temp.append(project[0][q].replace("_"," ")) temp.append(project[5][q]) name.append(temp) self.response.out.write(project[5]) if f==0: self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids}))#using template if len(fields) == 0: f=0 for i in project[0]: temp=[] temp.append(i) temp.append(project[2][project[0].index(i)]) temp.append(i.replace("_"," ")) temp.append(project[5][project[0].index(i)]) name.append(temp) self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids})) if f : path = os.path.join(os.path.dirname(__file__),'rong.html')#use template self.response.out.write(template.render(path,{"wro":"wrong","ids":ids}))#,"language":lang}))#using template del field_names[:] del fields[:] class SelectPage(webapp.RequestHandler,db.Model): global category global project global fields global name global ids def get(self): f=0 global category global project global fields global name global ids field_names=[] f='' pro=db.GqlQuery("SELECT * FROM projectDetails ") for j in project[0]: if self.request.get(j)=="Submit": for k in pro: if k.projectid==ids: k.projectname=j.replace("_"," ") prof=db.GqlQuery("SELECT * FROM projectFields") project[1][project[0].index(j)]=project[1][project[0].index(j)].replace("_"," ") field_names=project[1][project[0].index(j)].split(',') for i in prof: if i.fieldname in field_names: if(f!=''): f=f+","+i.fieldid else: f=i.fieldid k.fieldnames=f f='' k.abstract=project[2][project[0].index(j)] lang=project[5][project[0].index(j)].split(',') prol=db.GqlQuery("SELECT * FROM languages") for i in prol: if i.language in lang: if(f!=''): f=f+","+i.languageid else: f=i.languageid k.languages=f k.confirmed=True k.put() c1=db.GqlQuery("SELECT * FROM teamDetails") for i in c1: if i.teamid==k.teamid: team=i.teammember.split(",") c1=db.GqlQuery("SELECT * FROM userDetails") for i in c1: if i.admissionnumber in team: if i.projectids==None: i.projectids=ids else: i.projectids=i.projectids+','+ids i.put() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: j=j.replace("_"," ") if i.projectname==j: f=1 i.lock=True i.put() if f: del category[:] del project[0][:] del project[1][:] del project[2][:] del name[:] self.redirect("/user") application = webapp.WSGIApplication([('/pool', MainPage),('/sel', SelectPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from models import * cat=db.GqlQuery("SELECT * FROM projectCategory") for i in cat: i.delete() cat=db.GqlQuery("SELECT * FROM projectDetails") for i in cat: i.delete() u1=projectCategory(categoryid="CSHPC",maxmembers=100,categorytype="HPC New",categorylead="mahesh") u1.put() u2=projectCategory(categoryid="CSMini",maxmembers=3,categorytype="Mini Project",categorylead="mahesh") u2.put() u3=projectCategory(categoryid="CSMain",maxmembers=3,categorytype="Main Project",categorylead="Mase") u3.put() p1=projectDetails(projectid="KF01") p1.put() p2=projectDetails(projectid="KF02") p2.put() p3=projectDetails(projectid="KF03") p3.put() print "hai"
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime class MainPage(webapp.RequestHandler,db.Model): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def post(self): user = users.get_current_user() details=models.userDetails() details.username=self.request.get("name") details.email=user.email() details.mobilenumber=self.request.get("phone") details.privilege="user" details.projecteamids="" details.admissionnumber=self.request.get("admno") details.userid=self.request.get("admno") details.branch=self.request.get("branch") details.approved=False details.put() self.redirect("/user") class Display(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: path = os.path.join(os.path.dirname(__file__),'home.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) class Home(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: return path = os.path.join(os.path.dirname(__file__),'landing.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) class Logout(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: self.redirect(users.create_logout_url("/")) else: self.redirect(users.create_login_url("/")) class Admin(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': self.redirect("/") return path = os.path.join(os.path.dirname(__file__),'admin.html')#use template self.response.out.write(template.render(path,{"email":"Administrator"}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) application = webapp.WSGIApplication([('/', MainPage),('/inser', Display),('/home', Home),('/logout', Logout),('/admin',Admin)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ProjectPool(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() projectpool=[] projectsinpool=db.GqlQuery("SELECT * FROM projectPool") for proj in projectsinpool: tmp=[] tmp.append(proj.projectname) tmp.append(proj.category) tmp.append(proj.languages) tmp.append(proj.fieldnames) projectpool.append(tmp) path = os.path.join(os.path.dirname(__file__),'projectpool.html')#use template self.response.out.write(template.render(path, {"projectpool":projectpool}))#using template application = webapp.WSGIApplication([('/projectpool', ProjectPool)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * global pcategory class MainPage(webapp.RequestHandler): global pcategory def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global pcategory c=db.GqlQuery("SELECT * FROM projectCategory") pcategory=[] self.response.out.write(c) for i in c: tmp=[] tmp.append(i.categorytype.replace(" ","_")) tmp.append(i.categorytype) tmp.append(i.categoryid) tmp.append(i.maxprojects) pcategory.append(tmp) path = os.path.join(os.path.dirname(__file__),'cat.html')#use template self.response.out.write(template.render(path,{"category":pcategory}))#using template def post(self): global pcategory k=projectDetails() k.category=self.request.get("category") for i in pcategory: if i[0]==k.category: break k.category=i[2] user = users.get_current_user() if user: try: userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='%s'" %(user.email())) for i in userdet: if(i.projectids==None): break projunderme=i.projectids.split(",") for pid in projunderme: projdets=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %pid) for j in projdets: if j.category==k.category: path = os.path.join(os.path.dirname(__file__),'categoryerror.html')#use template self.response.out.write(template.render(path,{}))#using template return key=k.put() ids=key.id() k.projectid=str(ids) k.put() del pcategory[:] self.redirect("/notification?%s=id" %ids) except: pass application=webapp.WSGIApplication([('/category',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ViewTeam(webapp.RequestHandler): def get(self): allteams=db.GqlQuery("SELECT * FROM teamDetails") tmp2=[] for team in allteams: teams=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %team.teamid) tmp1=[] for team in teams: tmp=[] for member in team.teammember: mem=member.split(',') membername = db.GqlQuery("SELECT username FROM userDetails WHERE userid='%s'" %mem) tmp.append(membername) tmp1.append(team.teamid) tmp1.append(tmp) for project in team.projectids: proj=project.split(',') projectname = db.GqlQuery("SELECT projectname FROM projectDetails WHERE projectid='%s'" %proj) tmp1.append(projectname) tmp2.append(tmp1) path = os.path.join(os.path.dirname(__file__),'viewteam.html')#use template self.response.out.write(template.render(path,{"team":tmp2}))#using template application = webapp.WSGIApplication([('/viewteam', ViewTeam)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from models import * u1=userDetails(username="kev",email="kev@gmail.com",userid="221",mobilenumber="111",admissionnumber="1",branch="CSE",projecteamids="",privilege="stud",timestamp="") u1.put() u2=userDetails(username="jozf",email="jozf@gmail.com",userid="222",mobilenumber="222",admissionnumber="2",branch="CSE",projecteamids="",privilege="stud",timestamp="") u2.put() u3=userDetails(username="jay",email="jay@gmail.com",userid="223",mobilenumber="333",admissionnumber="3",branch="CSE",projecteamids="",privilege="stud",timestamp="") u3.put() u4=userDetails(username="dp",email="dp@gmail.com",userid="224",mobilenumber="444",admissionnumber="4",branch="CSE",projecteamids="",privilege="stud",timestamp="") u4.put() u5=userDetails(username="chak",email="chak@gmail.com",userid="225",mobilenumber="555",admissionnumber="5",branch="CSE",projecteamids="",privilege="stud",timestamp="") u5.put() u6=userDetails(username="jerry",email="jerry@gmail.com",userid="226",mobilenumber="777",admissionnumber="6",branch="CSE",projecteamids="",privilege="stud",timestamp="") u6.put() print "hai"
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user = users.get_current_user() t_email=user.email() usrdtl=db.GqlQuery("SELECT * FROM userDetails") for k in usrdtl: if k.email==t_email: user_id=k.userid teamDetails=db.GqlQuery("SELECT * FROM teamDetails") projectDetails=db.GqlQuery("SELECT * FROM projectDetails") notif=db.GqlQuery("SELECT * FROM notificationDetails") tid=[] temp=[] fla=0 for i in teamDetails: stri=i.teammember b=stri.split(',') for j in b: if j==user_id: fla=1 tid.append(i.projectids) t=[] for i in notif : if i.userid==user_id: temp1=[i.notification,i.notificationid] t.append(temp1) for i in projectDetails: for j in tid: if i.projectid==j: temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed] tid.append(temp) path = os.path.join(os.path.dirname(__file__),'tab.html')#use template self.response.out.write(template.render(path,{"items":tid,"noti":t}))#using template def post(self): delid=self.request.get("delval") notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid)) for i in notif : i.delete() self.redirect("/") application=webapp.WSGIApplication([('/',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import random ids=["102","103","104","105","106","107","108","109","112","113","114","115","116","117","118","119"] field=["HPC","Machine Learning","Robotics","TOC","GAME","ANDROID","ELECTRONICS","WEB DEVELOPMENT"] name=["Compiler Design","Face Detection","QuadraCopter","Travelling Sales Man","Develop a open source","Android Media Player","Andrino Prog","HTML5 Website","Panda 3d Game","Android Battery monitor","Robotic Arm","Google Hacking","Coffee detection ROBOT","FB hacking"] abst=["qwertyuiop","poiuytrewwq","asdfghjkl","lkjhgfdsa","zxcvbnm","mnbvcxz","blsahahah","blahahaha","blsahahah","blahahaha","blsahahah","blahahaha"] lang=["pyhton","C","java","c++","perl"] class MainPage(webapp.RequestHandler,db.Model): def get(self): c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: i.delete() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: i.delete() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: self.response.out(i) for i in range(0,14): project=models.projectPool() project.poolprojectid=ids[i] project.fieldnames=field[random.randint(0,7)] for k in range(0,random.randint(0,2)): project.fieldnames=project.fieldnames+","+field[random.randint(0,7)] project.projectname=name[i] project.abstract=abst[random.randint(0,11)] project.languages=lang[random.randint(0,4)]+","+lang[random.randint(0,4)] project.put() self.response.out.write("Field : "+project.fieldnames+" ") self.response.out.write("Name : "+project.projectname+" ") self.response.out.write("Abstract : "+project.abstract+" <br>") for i in range(0,8): p1=models.projectFields() p1.fieldname=field[i] p1.put() self.response.out.write("Field : "+p1.fieldname+" ") """ self.response.out.write("category: "+self.request.get("category")+"<br>") self.response.out.write("Lan: ") c1=db.GqlQuery("SELECT * FROM languages") project.languages="" for i in c1: self.response.out.write(i.language+" : "+self.request.get(i.language)+"<br>") if self.request.get(i.language)=="yes": project.languages=project.languages+i.language+"," self.response.out.write("<br>category: "+self.request.get("abs")+"<br>") self.response.out.write("<br>projectname: "+self.request.get("projectname")+"<br>") project.categories=self.request.get("category") project.projectname=self.request.get("projectname") project.abstract=self.request.get("abs") project.confirmed=False project.put() """ application = webapp.WSGIApplication([('/', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class QAPage(webapp.RequestHandler): global questionid def post(self): global questionid answer=self.request.get("ans") question=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s'" %questionid) for qn in question: qn.answer=answer qn.put() self.redirect("/answerquestionmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global questionid questionid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): questionid=questionid+url[i] i=i+1 break question=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s' AND answer=NULL" %questionid) for qn in question: path = os.path.join(os.path.dirname(__file__),'qnans.html')#use template self.response.out.write(template.render(path,{"question":qn.question,"questionid":qn.questionid}))#using template class QAPageMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() unansweredqns=db.GqlQuery("SELECT * FROM questionanswer WHERE answer=NULL") ques=[] for question in unansweredqns: temp=[] temp.append(question.question) temp.append(question.questionid) ques.append(temp) path = os.path.join(os.path.dirname(__file__),'qnansmain.html')#use template self.response.out.write(template.render(path,{"question":ques}))#using template application = webapp.WSGIApplication([('/answerquestion', QAPage),('/answerquestionmain', QAPageMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class EditProject(webapp.RequestHandler): global projectid def post(self): global projectid is_confirm = self.request.get('confirm', None) is_delete = self.request.get('delete', None) is_cancel = self.request.get('cancel', None) if is_confirm: pname=self.request.get("projname") pabstract=self.request.get("projabstract") pteamid=self.request.get("projteamids") pcategory=self.request.get("catsel") planguages='' languages=db.GqlQuery("SELECT * FROM languages") for i in languages: if self.request.get("l"+i.languageid) == "l"+i.languageid: if not planguages: planguages=i.languageid else: planguages=planguages+","+i.languageid pfields='' fields=db.GqlQuery("SELECT * FROM projectFields") for i in fields: if self.request.get("f"+i.fieldid) == "f"+i.fieldid: if not pfields: pfields=i.fieldid else: pfields=pfields+","+i.fieldid previewdate=self.request.get("projreviewdate") previewdate=self.request.get("projmaxmem") project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)) for projdetails in project: projdetails.projectname=pname projdetails.category=pcategory projdetails.languages=planguages projdetails.abstract=pabstract projdetails.teamid=pteamid projdetails.reviewdate=previewdate projdetails.fieldnames=pfields projdetails.put() teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid) for mem in teammembers: notifymembers=mem.teammember.split(",") message="The project "+pname+" has been edited by the administrator" for member in notifymembers: newnote=notificationDetails(admissionnumber=member,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_delete: project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)) for projdetails in project: pname=projdetails.projectname pteamid=projdetails.teamid delfromteam=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid) for team in delfromteam: teamprojs=team.projectids.split(",") teamuser=team.teammember.split(",") for user in teamuser: delprojuser=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %user) for delproj in delprojuser: userprojects=delproj.projectids.split(",") for projs in userprojects: if(projs==projectid): userprojects.remove(projectid) for prjcts in userprojects: userprojs='' for prjcts in projs: if not userprojs: userprojs=prjcts else: userprojs=userprojs+","+prjcts delproj.projectids=userprojs delproj.put() for projid in teamprojs: if(projid==projectid): teamprojs.remove(projectid) teamprojs='' for projid in teamprojs: if not teamprojs: teamprojs=projid else: teamprojs=teamprojs+","+projid team.projectids=teamprojs team.put() projdetails.delete() teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %(pteamid)) for member in teammembers: notifymembers=member.teammember.split(",") message="The project '"+pname+"' has been deleted by the administrator" for singlemember in notifymembers: newnote=notificationDetails(admissionnumber=singlemember,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_cancel: self.redirect("/editprojectmain") else: raise Exception('no form action given') self.redirect("/editprojectmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global projectid projectid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): projectid=projectid+url[i] i=i+1 break projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid) path = os.path.join(os.path.dirname(__file__),'editproject.html')#use template tmp=[] for project in projects: categoryselected=[] fieldsselected=[] languageselected=[] categoryunselected=[] fieldsunselected=[] languageunselected=[] catdet=db.GqlQuery("SELECT * FROM projectCategory") for catg in catdet: if catg.categoryid==project.category: categoryselected.append(catg.categoryid) categoryselected.append(catg.categorytype) else: tmp=[] tmp.append(catg.categoryid) tmp.append(catg.categorytype) categoryunselected.append(tmp) langdet=db.GqlQuery("SELECT * FROM languages") for lang in langdet: selflag=0 for sellang in project.languages: if lang.languageid==sellang: tmp=[] tmp.append(lang.languageid) tmp.append(lang.language) languageselected.append(tmp) selflag=1 break if selflag==0: tmp=[] tmp.append(lang.languageid) tmp.append(lang.language) languageunselected.append(tmp) fielddet=db.GqlQuery("SELECT * FROM projectFields") for fld in fielddet: selflag=0 for indfield in project.fieldnames: if fld.fieldid==indfield: tmp=[] tmp.append(fld.fieldid) tmp.append(fld.fieldname) fieldsselected.append(tmp) selflag=1 break if selflag==0: tmp=[] tmp.append(fld.fieldid) tmp.append(fld.fieldname) fieldsunselected.append(tmp) self.response.out.write(template.render(path,{"pname":project.projectname,"abstract":project.abstract,"teamid":project.teamid,"categoryunselected":categoryunselected,"categoryselected":categoryselected,"languageunselected":languageunselected,"languageselected":languageselected,"fieldsunselected":fieldsunselected,"fieldsselected":fieldsselected,"reviewdate":project.reviewdate,"maxmembers":project.maxmembers}))#using template class EditProjectMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() confirmed=db.GqlQuery("SELECT * FROM projectDetails") path = os.path.join(os.path.dirname(__file__),'editprojectmain.html')#use template tmp=[] for project in confirmed: tmp1=[] tmp1.append(project.projectname) tmp1.append(project.projectid) tmp.append(tmp1) self.response.out.write(template.render(path,{"projects":tmp}))#using template application = webapp.WSGIApplication([('/editproject', EditProject),('/editprojectmain', EditProjectMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class NextReviewMain(webapp.RequestHandler): def post(self): pteams='' date=self.request.get("date") allteams=db.GqlQuery("SELECT * FROM teamDetails") for team in allteams: if(self.request.get(team.teamid)=='teams'): if(pteams!=''): pteams=pteams+","+team.teammember else: pteams=team.teammember notemembers=pteams.split(",") message="Your team has a review on '%s'" %date for memberid in notemembers: newnote=notificationDetails(admissionnumber=memberid,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() self.redirect("/nextreview") class NextReview(webapp.RequestHandler): def post(self): selcategory=self.request.get("category") catid=str(selcategory) projects=db.GqlQuery("SELECT * FROM projectDetails WHERE category='%s'" %catid) details=[] #self.response.out.write(projects) for project in projects: teamid=project.teamid pname=project.projectname members=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %teamid) mem=members for i in mem: listmembers=i.teammember members=listmembers.split(",") membernames='' for member in members: indmember=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %member) for mem in indmember: membernames=membernames+mem.username tmp=[] tmp.append(teamid) tmp.append(pname) tmp.append(membernames) details.append(tmp) path = os.path.join(os.path.dirname(__file__),'nextreviewmain.html') self.response.out.write(template.render(path,{"members":details})) def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) path = os.path.join(os.path.dirname(__file__),'nextreview.html')#use template self.response.out.write(template.render(path,{"category":category}))#using template application = webapp.WSGIApplication([('/nextreview', NextReview),('/nextreviewmain', NextReviewMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ConfirmUser(webapp.RequestHandler): global admissionnumber def post(self): global admissionnumber is_confirm = self.request.get('confirm', None) is_cancel = self.request.get('cancel', None) if is_confirm: users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) for user in users: user.approved=True user.put() message="Your details have been verified and accepted by the administrator" newnote=notificationDetails(admissionnumber=admissionnumber,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_cancel: users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) for user in users: user.delete() else: raise Exception('no form action given') self.redirect("/confirmusermain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global admissionnumber admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s' AND approved=False" %admissionnumber) tmp=[] for user in users: tmp1=[] tmp1.append(user.username) tmp1.append(user.email) tmp1.append(user.mobilenumber) tmp1.append(user.admissionnumber) tmp1.append(user.branch) tmp1.append(user.privilege) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'confirmuser.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template class ConfirmUserMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() allusers=db.GqlQuery("SELECT * FROM userDetails WHERE approved=False") tmp=[] path = os.path.join(os.path.dirname(__file__),'confirmusermain.html')#use template for user in allusers: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp.append(tmp1) self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/confirmuser', ConfirmUser),('/confirmusermain', ConfirmUserMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import cgi from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user = users.get_current_user() template_values = { } path = os.path.join(os.path.dirname(__file__), 'question.html') self.response.out.write(template.render(path, template_values)) def post(self): x=self.request.get("t1") user = users.get_current_user() t_email=user.email() usrdtl=db.GqlQuery("SELECT * FROM userDetails") for j in usrdtl: if j.email==t_email: user_ano=j.admissionnumber self.response.out.write(user_ano) tempvar=questionanswer(admissionnumber=str(user_ano),question=x) key=tempvar.put() tempvar.questionid=str(key.id()) tempvar.put() self.redirect('/user') application = webapp.WSGIApplication([('/question', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class AdminLogout(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user=users.get_current_user() if user: self.redirect(users.create_logout_url("/")) else: self.redirect(users.create_logout_url("/")) class MainAdminPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() path = os.path.join(os.path.dirname(__file__),'admin.html')#use template self.response.out.write(template.render(path,{}))#using template application = webapp.WSGIApplication([ ('/admin', MainAdminPage),('/adminlogout', AdminLogout)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import string class MainPage(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() ids='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): ids=ids+str(url[i]) i=i+1 break ids=str(ids) self.response.out.write(str(ids)) path = os.path.join(os.path.dirname(__file__),'choice.html')#use template self.response.out.write(template.render(path,{"ids":ids}))#using template application = webapp.WSGIApplication([('/choice', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class UserError(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__),'usererror.html')#use template self.response.out.write(template.render(path,{}))#using template application = webapp.WSGIApplication([('/usererror', UserError)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class Field(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() fieldnames=[] allfields=db.GqlQuery("SELECT * FROM projectFields") for fieldname in allfields: tmp=[] tmp.append(fieldname.fieldid) tmp.append(fieldname.fieldname) fieldnames.append(tmp) path = os.path.join(os.path.dirname(__file__),'field.html') self.response.out.write(template.render(path,{"fieldname":fieldnames})) def post(self): field=db.GqlQuery("SELECT * FROM projectFields") for i in field: if self.request.get(i.fieldid) != i.fieldid: i.delete() fieldentry=self.request.get("addfield") fieldentrylist=fieldentry.split(',') for i in fieldentrylist: if i: pf=projectFields(fieldname=str(i)) key=pf.put() idnum=key.id() pf.fieldid=str(idnum) pf.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatefield', Field)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime class Category(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) path = os.path.join(os.path.dirname(__file__),'category.html') self.response.out.write(template.render(path,{"category":category})) def post(self): category=db.GqlQuery("SELECT * FROM projectCategory") for i in category: if self.request.get(i.categoryid) != i.categoryid: i.delete() categoryentry=self.request.get("addcategory") categoryentrylist=categoryentry.split(',') maximum=self.request.get("maximum") maximum=maximum.split(',') maxprojs=self.request.get("maxprojects") maxprojs=maxprojs.split(',') for i in range(0,len(categoryentrylist)): if categoryentrylist[i]: pf=models.projectCategory(categorytype=str(categoryentrylist[i]),maxmembers=int(maximum[i]),maxprojects=int(maxprojs[i])) key=pf.put() idnum=key.id() pf.categoryid=str(idnum) pf.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatecategory', Category)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class MeetMe(webapp.RequestHandler): def post(self): userdetails=db.GqlQuery("SELECT * FROM userDetails") details=[] for i in userdetails: temp=[] temp.append(i.admissionnumber) temp.append(i.username) details.append(temp) date=self.request.get("date") note="Administrator says: come and meet me on '%s'" %date for i in details : if self.request.get(i[0])=="yes": newnote=notificationDetails(admissionnumber=i[0],notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() self.redirect("/meetme") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.pathi.admissionnumber.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() userdetails=db.GqlQuery("SELECT * FROM userDetails") details=[] for i in userdetails: temp=[] temp.append(i.admissionnumber) temp.append(i.username) details.append(temp) path = os.path.join(os.path.dirname(__file__),'meetme.html')#use template self.response.out.write(template.render(path,{"details":details}))#using template application = webapp.WSGIApplication([('/meetme', MeetMe)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
# This is Python example on how to use Mongoose embeddable web server, # http://code.google.com/p/mongoose # # Before using the mongoose module, make sure that Mongoose shared library is # built and present in the current (or system library) directory import mongoose import sys # Handle /show and /form URIs. def EventHandler(event, conn): info = conn.info if event == mongoose.HTTP_ERROR: conn.write('HTTP/1.0 200 OK\r\n') conn.write('Content-Type: text/plain\r\n\r\n') return True elif event == mongoose.NEW_REQUEST and info.uri == '/show': conn.write('HTTP/1.0 200 OK\r\n') conn.write('Content-Type: text/plain\r\n\r\n') conn.write('[%s] [%s] [%s]\n' % (info.request_method, info.uri, info.query_string)) if info.request_method == 'POST': content_len = conn.get_header('Content-Length') post_data = conn.read(int(content_len)) my_var = conn.get_var(post_data, 'my_var') else: my_var = conn.get_var(info.query_string, 'my_var') conn.write('my_var: %s\n' % (my_var or '<not set>')) conn.write('HEADERS: \n') for header in info.http_headers[:info.num_headers]: conn.write(' %s: %s\n' % (header.name, header.value)) return True elif event == mongoose.NEW_REQUEST and info.uri == '/form': conn.write('HTTP/1.0 200 OK\r\n' 'Content-Type: text/html\r\n\r\n' 'Use GET: <a href="/show?my_var=hello">link</a>' '<form action="/show" method="POST">' 'Use POST: type text and submit: ' '<input type="text" name="my_var"/>' '<input type="submit"/>' '</form>') return True elif event == mongoose.NEW_REQUEST and info.uri == '/secret': conn.send_file('/etc/passwd') return True else: return False # Create mongoose object, and register '/foo' URI handler # List of options may be specified in the contructor server = mongoose.Mongoose(EventHandler, document_root='/tmp', listening_ports='8080') print ('Mongoose started on port %s, press enter to quit' % server.get_option('listening_ports')) sys.stdin.read(1) # Deleting server object stops all serving threads print 'Stopping server.' del server
Python
# Copyright (c) 2004-2009 Sergey Lyubka # # 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. # # $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $ """ This module provides python binding for the Mongoose web server. There are two classes defined: Connection: - wraps all functions that accept struct mg_connection pointer as first argument. Mongoose: wraps all functions that accept struct mg_context pointer as first argument. Creating Mongoose object automatically starts server, deleting object automatically stops it. There is no need to call mg_start() or mg_stop(). """ import ctypes import os NEW_REQUEST = 0 REQUEST_COMPLETE = 1 HTTP_ERROR = 2 EVENT_LOG = 3 INIT_SSL = 4 WEBSOCKET_CONNECT = 5 WEBSOCKET_READY = 6 WEBSOCKET_MESSAGE = 7 WEBSOCKET_CLOSE = 8 OPEN_FILE = 9 INIT_LUA = 10 class mg_header(ctypes.Structure): """A wrapper for struct mg_header.""" _fields_ = [ ('name', ctypes.c_char_p), ('value', ctypes.c_char_p), ] class mg_request_info(ctypes.Structure): """A wrapper for struct mg_request_info.""" _fields_ = [ ('request_method', ctypes.c_char_p), ('uri', ctypes.c_char_p), ('http_version', ctypes.c_char_p), ('query_string', ctypes.c_char_p), ('remote_user', ctypes.c_char_p), ('remote_ip', ctypes.c_long), ('remote_port', ctypes.c_int), ('is_ssl', ctypes.c_int), ('num_headers', ctypes.c_int), ('http_headers', mg_header * 64), ('user_data', ctypes.c_void_p), ('ev_data', ctypes.c_void_p), ] mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p) class Connection(object): """A wrapper class for all functions that take struct mg_connection * as the first argument.""" def __init__(self, mongoose, connection): self.m = mongoose self.conn = ctypes.c_void_p(connection) self.info = self.m.dll.mg_get_request_info(self.conn).contents def get_header(self, name): val = self.m.dll.mg_get_header(self.conn, name) return ctypes.c_char_p(val).value def get_var(self, data, name): size = data and len(data) or 0 buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_get_var(data, size, name, buf, size) return n >= 0 and buf or None def printf(self, fmt, *args): val = self.m.dll.mg_printf(self.conn, fmt, *args) return ctypes.c_int(val).value def write(self, data): val = self.m.dll.mg_write(self.conn, data, len(data)) return ctypes.c_int(val).value def read(self, size): buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_read(self.conn, buf, size) return n <= 0 and None or buf[:n] def send_file(self, path): self.m.dll.mg_send_file(self.conn, path) class Mongoose(object): """A wrapper class for Mongoose shared library.""" def __init__(self, callback, **kwargs): if os.name == 'nt': self.dll = ctypes.WinDLL('mongoose.dll') else: self.dll = ctypes.CDLL('libmongoose.so') self.dll.mg_start.restype = ctypes.c_void_p self.dll.mg_modify_passwords_file.restype = ctypes.c_int self.dll.mg_read.restype = ctypes.c_int self.dll.mg_write.restype = ctypes.c_int self.dll.mg_printf.restype = ctypes.c_int self.dll.mg_get_header.restype = ctypes.c_char_p self.dll.mg_get_var.restype = ctypes.c_int self.dll.mg_get_cookie.restype = ctypes.c_int self.dll.mg_get_option.restype = ctypes.c_char_p self.dll.mg_get_request_info.restype = ctypes.POINTER(mg_request_info) if callback: # Create a closure that will be called by the shared library. def func(event, connection): # Wrap connection pointer into the connection # object and call Python callback conn = Connection(self, connection) return callback(event, conn) and 1 or 0 # Convert the closure into C callable object self.callback = mg_callback_t(func) self.callback.restype = ctypes.c_char_p else: self.callback = ctypes.c_void_p(0) args = [y for x in kwargs.items() for y in x] + [None] options = (ctypes.c_char_p * len(args))(*args) ret = self.dll.mg_start(self.callback, 0, options) self.ctx = ctypes.c_void_p(ret) def __del__(self): """Destructor, stop Mongoose instance.""" self.dll.mg_stop(self.ctx) def get_option(self, name): return self.dll.mg_get_option(self.ctx, name)
Python
#!/usr/bin/env python import itertools import numpy import baker from fitpy.utils import iterables from fitpy.optimize import optimize import benchmarks as bm import fitpy.algorithms.algorithm_names def decode_names(names, module): iterable_names = iterables.make_iterable(names) return [getattr(module, name) for name in iterable_names] def run_benchmark(algorithm_name, benchmark, num_runs): evaluation_counts = [] costs = [] for i in xrange(num_runs): full_results = optimize(benchmark.cost_function, algorithm_name=algorithm_name, **benchmark.kwargs) evaluation_counts.append(len(full_results['evaluation_cache'])) costs.append(full_results['best_cost']) return {'num_evaluations_average': numpy.average(evaluation_counts), 'num_evaluations_std': numpy.std(evaluation_counts), 'cost_average': numpy.average(costs), 'cost_std': numpy.std(costs)} def run_benchmarks(algorithm_names, benchmarks, num_runs): results = [] for algorithm_name, benchmark in itertools.product(algorithm_names, benchmarks): results.append(run_benchmark(algorithm_name, benchmark, num_runs)) return results def display_benchmark_results(results): for result in results: print result['num_evaluations_average'], result['num_evaluations_std'] print result['cost_average'], result['cost_std'] # print len(result['evaluation_cache']) # print result['best_parameters'] # print result['best_cost'] #@baker.command #def algorithm(algorithm_name, benchmark_names=None, num_runs=1): # """ # :param algorithm_name: Name of the algorithm to benchmark. # :param benchmarks: Which benchmarks to run (default = all). # :param num_runs: How many times to perform each benchmark. # """ # if benchmark_names is None: # # Get list of all benchmarks # benchmarks = bm.all_benchmarks # else: # benchmarks = decode_names(benchmark_names, bm) # # results = run_benchmarks([algorithm_name], benchmarks) # # display_benchmark_results(results) # #@baker.command #def benchmark(benchmark_name, algorithms=None, num_runs=1): # print 'benchmark', benchmark_name @baker.command(default=True) def all(num_runs=50): benchmarks = bm.all_benchmarks algorithm_names = fitpy.algorithms.algorithm_names.algorithm_names results = run_benchmarks(algorithm_names, benchmarks, num_runs) display_benchmark_results(results) baker.run()
Python
import math def schaffer_f6(a, b): t1 = math.sin(math.sqrt(a*a + b*b)) t2 = 1 + 0.001*(a*a + b*b) score = 0.5 + (t1*t1 - 0.5)/(t2*t2) return score
Python
import schaffer_f6_standard all_benchmarks = [schaffer_f6_standard]
Python
from .functions import schaffer_f6 cost_function = schaffer_f6.schaffer_f6 kwargs = {'parameter_constraints': [[-10.0, 10.0], [-10.0, 10.0]], 'target_cost': 0.001, 'max_evaluations': None, 'num_points':10000}
Python
#!/usr/bin/env python import itertools import numpy import baker from fitpy.utils import iterables from fitpy.optimize import optimize import benchmarks as bm import fitpy.algorithms.algorithm_names def decode_names(names, module): iterable_names = iterables.make_iterable(names) return [getattr(module, name) for name in iterable_names] def run_benchmark(algorithm_name, benchmark, num_runs): evaluation_counts = [] costs = [] for i in xrange(num_runs): full_results = optimize(benchmark.cost_function, algorithm_name=algorithm_name, **benchmark.kwargs) evaluation_counts.append(len(full_results['evaluation_cache'])) costs.append(full_results['best_cost']) return {'num_evaluations_average': numpy.average(evaluation_counts), 'num_evaluations_std': numpy.std(evaluation_counts), 'cost_average': numpy.average(costs), 'cost_std': numpy.std(costs)} def run_benchmarks(algorithm_names, benchmarks, num_runs): results = [] for algorithm_name, benchmark in itertools.product(algorithm_names, benchmarks): results.append(run_benchmark(algorithm_name, benchmark, num_runs)) return results def display_benchmark_results(results): for result in results: print result['num_evaluations_average'], result['num_evaluations_std'] print result['cost_average'], result['cost_std'] # print len(result['evaluation_cache']) # print result['best_parameters'] # print result['best_cost'] #@baker.command #def algorithm(algorithm_name, benchmark_names=None, num_runs=1): # """ # :param algorithm_name: Name of the algorithm to benchmark. # :param benchmarks: Which benchmarks to run (default = all). # :param num_runs: How many times to perform each benchmark. # """ # if benchmark_names is None: # # Get list of all benchmarks # benchmarks = bm.all_benchmarks # else: # benchmarks = decode_names(benchmark_names, bm) # # results = run_benchmarks([algorithm_name], benchmarks) # # display_benchmark_results(results) # #@baker.command #def benchmark(benchmark_name, algorithms=None, num_runs=1): # print 'benchmark', benchmark_name @baker.command(default=True) def all(num_runs=50): benchmarks = bm.all_benchmarks algorithm_names = fitpy.algorithms.algorithm_names.algorithm_names results = run_benchmarks(algorithm_names, benchmarks, num_runs) display_benchmark_results(results) baker.run()
Python
import numpy import random import fitpy # Here's the functional form we will fit def functional_form(x, a, b, c): """ par is a sequence of parameters (a chromosome in the fitting algorithm) x is where to evaluate the function """ return a * numpy.exp(b * x) + c # Generate some noisy data to fit target_parameters = (3.16, -0.478, 2.105) data_size = 1000 xmin = 0 xmax = 25 x = numpy.linspace(xmin, xmax, data_size) data = functional_form(x, *target_parameters) + (numpy.random.random(data_size) - 0.5) # Perform the fit fit_results = fitpy.residual_fit(functional_form, x, data, parameter_constraints= {'a':(-5, 5), 'b':(-5, 5), 'c':(-5, 5)}, verbosity=10, # FIXME remove after testing... generation_size=500, max_evaluations=2000) fit_parameters = fit_results['best_parameters'] chi_squared = fit_results['evaluation_cache'][fit_parameters] # Show the result of the fit print 'Chi-squared per datum:', chi_squared/data_size print 'Percent errors for the fit parameters:' percent_errors = [('% 0.3f' % (100*(f - t)/t)) for f, t in zip(fit_parameters, target_parameters)] print ' '.join(percent_errors) try: # in case the users don't have matplotlib installed on the system. import pylab pylab.plot(x, data, linewidth = 2, color='black', label='Data') pylab.plot(x, functional_form(x, *fit_parameters), color='red', label='Fit') pylab.legend() pylab.title("Least squares fitting example.") pylab.xlabel('x') pylab.ylabel('y') pylab.show() except ImportError: pass
Python
import numpy import fitpy from fitpy.helpers import chi_squared, count_zero_crossings # Here's the functional form we will fit def functional_form(par, x): """ par is a sequence of parameters (a chromosome in the fitting algorithm) x is where to evaluate the function """ return par[0] * numpy.exp(par[1] * x * numpy.sin(par[2] * x)) + par[3] # Generate some noisy data to fit. target_parameters = (1.5, 2.73, 5.15, 0.3) data_size = 500 xmin = 0 xmax = 10 xmesh = numpy.linspace(xmin, xmax, data_size) fit_data = functional_form(target_parameters, xmesh)\ + numpy.random.normal(size=data_size) fit_czc = count_zero_crossings(fit_data - 1) # Here is a fitness function that evaluates individuals using multiple objectives delta = 1e-15 def fitness_function(chromosome): """ Returns a tuple of fitnesses for the given chromosome. The objectives used are: overall least-squares fit. number of times crossing the line y = 1 intial value y(x=0) """ ymesh = functional_form(chromosome, xmesh) residual = chi_squared(ymesh, fit_data) zero_crossings = count_zero_crossings(ymesh - 1) return (1.0/(delta + residual), 1.0/(delta + (zero_crossings - fit_czc)**2), 1.0/(delta + (ymesh[0] - fit_data[0])**2)) # Set constraints on parameters (alleles in genetic algorithm vocabulary). allele_constraints = [(0.1, 10), (0.1, 10), (0.1, 10), (0, 1000)] fit_parameters, fitnesses = fitpy.multiple_objective(fitness_function, allele_constraints) # Show the result of the fit print 'Final fitnesses:', fitnesses print 'Percent errors for the fit parameters:' print [(f - t)/t for f, t in zip(fit_parameters, target_parameters)]
Python
from itertools import izip import numpy import fitpy # Here's the functional form we will fit def functional_form(par, x): """ par is a sequence of parameters (a chromosome in the fitting algorithm) x is where to evaluate the function """ return par[0] * numpy.exp(par[1] * x) + par[2] # Generate some noisy data to fit target_parameters = (3.16, -0.478, 2.105) data_size = 1000 xmin = 0 xmax = 25 x = numpy.linspace(xmin, xmax, data_size) perfect_data = functional_form(target_parameters, x) std_deviations = numpy.random.uniform(0.01, 0.3, data_size) *\ perfect_data fit_data = numpy.array(p + scipy.random.normal(scale=s) for p, s in izip(perfect_data, std_deviations)) # Perform the fit fit_parameters, chisquared = fitpy.least_squares(functional_form, x, fit_data, error_estimates=std_deviations) # Show the result of the fit print 'Normalized chi-squared per datum:', chisquared/data_size print 'Percent errors for the fit parameters:' print [(f - t)/t for f, t in zip(fit_parameters, target_parameters)]
Python
import datetime RESIDUAL_NAME = 'chi_squared' MAX_EVALUATIONS = 10000 MAX_RUNTIME = datetime.timedelta(minutes=5) ALGORITHM_NAME = 'continuous_genetic'
Python
DEFAULT_INITIAL_POPULATION_SIZE=500 DEFAULT_CROSSOVER_RATE = 0.1 DEFAULT_MUTATION_RATE = 0.3 DEFAULT_PERTURBATION_RATE = 0.4 DEFAULT_NUMBER_SAMPLE_POINTS = 1000
Python
import math from . import strategies from . import reproduction from ..common.parameter_queue import MultiObjectiveParameterQueue, SingleObjectiveParameterQueue from .settings import * from fitpy.utils import meshes, iterables __all__ = ['make_algorithm'] def make_algorithm(cost_func, parameter_constraint_list, end_conditions, population=None, **kwargs): reproduction_object = make_default_reproduction(parameter_constraint_list, **kwargs) if population is None: test_individual = reproduction_object.random_set(1) test_individual = test_individual[0] test_cost = cost_func(*test_individual) if iterables.isiterable(test_cost): population = MultiObjectiveParameterQueue(**kwargs) else: population = SingleObjectiveParameterQueue(**kwargs) population.add(test_individual, test_cost) return strategies.GeneticAlgorithm(cost_func, population, reproduction_object, end_conditions, **kwargs) def make_default_reproduction(parameter_constraint_list, crossover_rate=DEFAULT_CROSSOVER_RATE, mutation_rate=DEFAULT_MUTATION_RATE, perturbation_rate=DEFAULT_PERTURBATION_RATE, num_points=DEFAULT_NUMBER_SAMPLE_POINTS, **kwargs): """ Inputs: parameter_constraint_list : A list of tuples which give bounds on parameters --kwargs-- crossover_rate : how likely the reproduction swaps gene sequences (see glossary) mutation_rate : how likely any individual parameter will take on a completely random value purterbation_rate : how likely any idividual parameter will slightly change. num_points : Number of values chosen between bounds for each parameter. Returns: reproduction_object """ allowed_parameter_values = [] # determine the allowed parameter values for lower, upper in parameter_constraint_list: # figure out the mesh details if math.log(upper-lower, 10) > 3.0: # if the constraints vary over more than 3 orders... mesh = meshes.logmesh(lower, upper, num_points) else: mesh = meshes.linmesh(lower,upper, num_points) allowed_parameter_values.append(mesh) # return basic constrained reproduction return reproduction.DiscreteStandard(allowed_parameter_values, crossover_rate, mutation_rate, perturbation_rate)
Python
from fitpy.utils import logutils from ..common.evaluation_cache import EvaluationCache from .settings import DEFAULT_INITIAL_POPULATION_SIZE logger = logutils.getLogger(__file__) __all__ = ['GeneticAlgorithm'] class GeneticAlgorithm(object): def __init__(self, cost_func, population, reproduce, end, **kwargs): self.cost_func = cost_func self.population = population self.reproduce = reproduce self.end = end def run(self, initial_guess_list, initial_population_size=DEFAULT_INITIAL_POPULATION_SIZE, **kwargs): # Initialze the run initial_parameters_set = self.reproduce.random_set(initial_population_size, initial_guess_list) evaluation_cache = EvaluationCache() for p in self.population: evaluation_cache[p.parameters] = p.cost num_evaluations = len(evaluation_cache) logger.debug('Evaluating initial generation.') for parameters in initial_parameters_set: cost = self.cost_func(*parameters) evaluation_cache[parameters] = cost self.population.add(parameters, cost) num_evaluations += 1 best_parameters = self.population[0].parameters best_cost = self.population[0].cost for e in self.end: e.reset() ec_locals = locals() while not any(e(ec_locals) for e in self.end): # Generate children child = self.reproduce.generate_child(self.population, evaluation_cache) cost = self.cost_func(*child) evaluation_cache[child] = cost self.population.add(child, cost) # Progress tracking best_parameters = self.population[0].parameters best_cost = self.population[0].cost num_evaluations += 1 ec_locals = locals() # Return return {'evaluation_cache': evaluation_cache, 'best_parameters': best_parameters, 'best_cost': best_cost}
Python
from . import factories from . import strategies
Python
import copy import random from fitpy.utils import logutils from ..common import choice logger = logutils.getLogger(__file__) class DiscreteStandard(object): def __init__(self, allowed_parameter_values, crossover_rate, mutation_rate, perturbation_rate): self.allowed_parameter_values = allowed_parameter_values self.crossover_rate = crossover_rate self.mutation_rate = mutation_rate self.perturbation_rate = perturbation_rate def generate_child(self, population, cache): """ Generates a child. """ child = None while not child: parent1, parent2 = choice.choose_two(population, choice.weighted_choice) child, unloved_child = binary_crossover(parent1.parameters, parent2.parameters, self.crossover_rate) child = discrete_mutation(child, self.mutation_rate, self.allowed_parameter_values) child = discrete_perturbation(child, self.perturbation_rate, self.allowed_parameter_values) # Allow hashing of child for use in dicts/sets. child = tuple(child) if child in cache or child in population: logger.debug('Created non-unique child, %s from parents: %s, %s.' % (str(child), str(parent1), str(parent2))) child = None return child def random_set(self, size, guess=None): """ Generate a legal random population of 'generation_size'. """ if guess: size -= 1 generated = [tuple(random.choice(self.allowed_parameter_values[i]) for i in xrange(len(self.allowed_parameter_values))) for n in xrange(size)] if guess: return [guess] + generated return generated def binary_crossover(a, b, rate): """ Performs a normal crossover between a and b, generating 2 children. """ c1 = [] c2 = [] switched = False for ai, bi in zip(a,b): if random.random() < rate: switched = not switched if switched: c1.append(bi) c2.append(ai) else: c1.append(ai) c2.append(bi) return c1, c2 def discrete_mutation(c, rate, allowed_values): """ Performs mutation on c given self.mutation_rate. Uses a uniform distribution to pick new allel values. """ m = copy.copy(c) for i in xrange(len(c)): if random.random() < rate: m[i] = random.choice(allowed_values[i]) return m def discrete_perturbation(individual, rate, allowed_values): """ Randomly vary parameters to neighboring values given rate. """ ind = copy.copy(individual) for par_index, par_value in enumerate(ind): r = random.random() if r < rate: value_index = allowed_values[par_index].index(par_value) if 0 == value_index: ind[par_index] = allowed_values[par_index][1] elif len(allowed_values[par_index]) - 1 == value_index: ind[par_index] = allowed_values[par_index][-2] else: if r < rate/2: ind[par_index] = allowed_values[par_index][value_index - 1] else: ind[par_index] = allowed_values[par_index][value_index + 1] return ind
Python
import os from . import common # Generate list of legal algorithm names. _ignored_strings = ['.', 'common'] _dirname = os.path.dirname(__file__) algorithm_names = [] for file in os.listdir(_dirname): if not any(s in file for s in _ignored_strings): algorithm_names.append(file) del _ignored_strings del _dirname del os
Python
from . import common from .algorithm_names import algorithm_names from fitpy.utils.cost_function_wrapper import CostFunctionWrapper from fitpy.utils.funcutils import get_parameter_names def make_residual_cost_function(target_function, x_values, y_values, y_errors, residual_name, **kwargs): residual_function = common.residuals.residual_functions[ residual_name.lower()] def residual_cost_function(*parameters): return residual_function(x_values, y_values, y_errors, target_function(x_values, *parameters), **kwargs) parameter_names = get_parameter_names(target_function) # Throw away 'x' part of target_function arguments parameter_names = parameter_names[1:] return CostFunctionWrapper(residual_cost_function, parameter_names) def make_simple_end_conditions(max_evaluations, max_runtime, target_cost, **kwargs): ecs = [] if max_evaluations is not None: ecs.append(common.end_conditions.MaxEvaluations(max_evaluations)) if max_runtime is not None: ecs.append(common.end_conditions.MaxRuntime(max_runtime)) if target_cost is not None: ecs.append(common.end_conditions.MinimumCost(target_cost)) return ecs def make_algorithm(cost_func, parameter_constraint_list, end_conditions, algorithm_name, **kwargs): if not algorithm_name in algorithm_names: raise RuntimeError('Illegal algorithm name, %s. Must be one of: %s' % (algorithm_name, str(algorithm_names))) # Import the algorithm module, and instantiate the algorithm. exec('import ' + algorithm_name) module = eval(algorithm_name) return module.factories.make_algorithm(cost_func, parameter_constraint_list, end_conditions, **kwargs)
Python
DEFAULT_MAX_RANKING_LENGTH=500
Python
try: from collections import OrderedDict except ImportError: try: from ordereddict import OrderedDict except ImportError: raise ImportError("Couldn't find an ordered dictionary class to import, either install ordereddict from pypi or upgrade to Python 2.7 or newer.") class EvaluationCache(OrderedDict): """ Base class to keep track of all cost function evaluations and the parameter set used. """ def get_cost(self, i): return self[i] @property def num_evaluations(self): return len(self)
Python
from itertools import izip __all__ = ['chi_squared', 'residual_functions'] def chi_squared(x_values, y_values, y_stds, y_calculated, **kwargs): if y_stds: return sum([((y1-y2)/ys)**2 for y1, y2, ys in izip(y_values, y_calculated, y_stds)]) else: return sum([(y1-y2)**2 for y1, y2 in izip(y_values, y_calculated)]) residual_functions = {'chi_squared': chi_squared}
Python
import datetime import time import unittest from fitpy.algorithms.common import end_conditions class TestCounter(unittest.TestCase): def testNormal(self): c = end_conditions.Counter(50) self.assertFalse(any(c(None) for i in xrange(49))) self.assertTrue(c(None)) self.assertTrue(c(None)) c.reset() self.assertFalse(any(c(None) for i in xrange(49))) self.assertTrue(c(None)) self.assertTrue(c(None)) c.reset() self.assertFalse(any(c(None) for i in xrange(20))) c.reset() self.assertFalse(any(c(None) for i in xrange(49))) self.assertTrue(c(None)) self.assertTrue(c(None)) class TestTimer(unittest.TestCase): def testNormal(self): delta = datetime.timedelta(milliseconds=5) # Offset the count by one, or miss due to loop run time. count = 1 t = end_conditions.Timer(delta) while not t(None): time.sleep(1e-3) if not t(None): count += 1 self.assertEqual(5, count) count = 1 t.reset() while not t(None): time.sleep(1e-3) if not t(None): count += 1 self.assertEqual(5, count) class TestStoppedImproving(unittest.TestCase): def testIncreasing(self): increasing = end_conditions.StoppedImproving(3) values = [1, 2, 3, 3, 3, 4, 3, 5, 5, 5, 5, 6, 6, 7, 8, 9] for i, v in enumerate(values): result = increasing(v) if 10 <= i: self.assertTrue(result) else: self.assertFalse(result) increasing.reset() for i, v in enumerate(values): result = increasing(v) if 10 <= i: self.assertTrue(result) else: self.assertFalse(result) def testDecreasing(self): decreasing = end_conditions.StoppedImproving(3) values = [9, 9, 9, 8, 7, 7, 6, 6, 6, 6, 5, 4, 3, 2, 2] for i, v in enumerate(values): result = decreasing(v) if 9 <= i: self.assertTrue(result) else: self.assertFalse(result) decreasing.reset() for i, v in enumerate(values): result = decreasing(v) if 9 <= i: self.assertTrue(result) else: self.assertFalse(result) if '__main__' == __name__: unittest.main()
Python
import datetime from fitpy.utils import logutils logger = logutils.getLogger(__file__) __all__ = ['MaxIterations', 'MaxRuntime', 'StoppedImproving', 'FitTolerance'] class EndCondition(object): def __call__(self, variables): check_result = self.check(variables) if check_result: logger.info('Met end condition: %s' % self ) return check_result def check(self, variables): raise NotImplementedError() def __str__(self): return "Undifferentiated EndCondition" class Counter(EndCondition): def __init__(self, max_count): self.max_count = max_count self.remaining = max_count def reset(self): self.remaining = self.max_count def __str__(self): return "%s: %d" %(type(self).__name__, self.max_count) class MaxIterations(Counter): def check(self, variables): self.remaining -= 1 return 0 >= self.remaining class MaxEvaluations(Counter): def check(self, variables): return variables['num_evaluations'] >= self.max_count class MinimumCost(EndCondition): ''' End condition to specify a minimum residual or cost function. ''' def __init__(self, target_cost): self.target_cost = target_cost def check(self, variables): return variables['best_cost'] < self.target_cost def reset(self): pass def __str__(self): return "%s: %f" % (type(self).__name__, self.target_cost) class MaxRuntime(EndCondition): """ End condition to specify a maximum amount of time to run (approximate). """ def __init__(self, run_duration): """ run_duration is the amount of time to run the simulation. Must be either a datetime.timedelta() object, or a number of seconds. """ try: self.run_duration = datetime.timedelta(seconds=run_duration) except TypeError: self.run_duration = run_duration self.finish_time = datetime.datetime.now() + run_duration def check(self, variables): return self.finish_time < datetime.datetime.now() def reset(self): self.finish_time = datetime.datetime.now() + self.run_duration def __str__(self): return "%s: %s" % (type(self).__name__, str(self.run_duration)) class StoppedImproving(EndCondition): """ Specify a maximum number of generations to go without improving the most fit individual. """ def __init__(self, static_generations): self.static_generations = static_generations self.unchanged = 0 self.last_cost = None self.finished = False def check(self, variables): best_cost = variables['best_cost'] if not self.finished: if best_cost == self.last_cost: self.unchanged += 1 else: self.unchanged = 0 self.last_cost = best_cost if self.unchanged >= self.static_generations: self.finished = True return True return False def reset(self): self.last_cost = None self.unchanged = 0 self.finished = False def __str__(self): return "%s: allowed static generations = %d" % (type(self).__name__, self.static_generations)
Python
from . import residuals from . import end_conditions from . import choice
Python
import bisect from itertools import izip from collections import namedtuple from .settings import * MORankingProperties = namedtuple('MORankingProperties', 'trails trumps age cost parameters') SORankingProperties = namedtuple('SORankingProperties', 'cost parameters') class SingleObjectiveParameterQueue(list): def __init__(self, max_length=DEFAULT_MAX_RANKING_LENGTH, **kwargs): self.max_length = max_length def append(self, item): raise NotImplementedError( "Cannot append elements to this container. Try 'add' instead.") def add(self, new_parameters, new_cost): try: if new_cost < self[-1].cost: pass except IndexError: pass bisect.insort_left(self, SORankingProperties(new_cost, new_parameters)) if(len(self) > self.max_length): self.pop() class MultiObjectiveParameterQueue(list): ''' A ranked list of parameter batches, ranked based on their evaluation cost. If the cost function returns multiple values then multi-objective ranking is used. Parameter batches are ranked as they are added. ''' def __init__(self, max_length=DEFAULT_MAX_RANKING_LENGTH, **kwargs): self._current_age = 0 self.max_length def append(self, item): raise NotImplementedError( "Cannot append elements to this container. Try 'add' instead.") def add(self, new_parameters, new_cost): try: if trails(new_cost, self[-1].cost): return except IndexError: pass num_trumps = 0 num_trails = 0 for i, rp in enumerate(self): if trumps(new_cost, rp.cost): num_trumps += 1 rp.trails += 1 elif trails(new_cost, rp.cost): num_trails += 1 rp.trumps += 1 self._current_age -= 1 new_rp = MORankingProperties(num_trails, num_trumps, self._current_age, new_cost, new_parameters) bisect.insort_left(self, new_rp) if(len(self) > self.max_length): self.pop() def pop(self): dead_rp = list.pop(self) running_trails = 0 for i, good_rp in enumerate(self): if trumps(good_rp.cost, dead_rp.cost): running_trails += 1 good_rp.trumps -= 1 if running_trails == dead_rp.trails: break return dead_rp def trumps(cost1, cost2): return all(f1 > f2 for f1, f2 in izip(cost1, cost2)) def trails(cost1, cost2): return all(f1 < f2 for f1, f2 in izip(cost1, cost2))
Python
import random def choose_two(sequence, select_function): """ Picks 2 unique items from the sequence. """ p1 = select_function(sequence) p2 = p1 while p1 == p2: p2 = select_function(sequence) return p1, p2 def weighted_choice(sequence, width=None): """ Choose a random element from sequence, weighted toward the front of the list. """ if not width: width = float(len(sequence))/2 j = len(sequence) while j >= len(sequence): j = abs(int(random.normalvariate(0, width))) return sequence[j]
Python
import inspect import itertools import collections import logging from .utils import logutils from .utils.parameters import format_as_list from .utils import funcutils from .algorithms import factories import default_settings as ds logger = logutils.getLogger(__file__) def optimize(cost_function, parameter_constraints=None, initial_guess=None, max_evaluations=ds.MAX_EVALUATIONS, max_runtime=ds.MAX_RUNTIME, target_cost=None, verbosity=None, algorithm_name=ds.ALGORITHM_NAME, **kwargs): ''' Convenience function that finds a reasonable fit to x, y data using 'target_function' ''' # Function overview # ------------------------------------------------------------------- # setup logging (using verbosity) # clean up input # verify target function is callable # make sure x values and y values have same length # construct parameters - figure out how many, and what constraints # construct algorithm # build end_conditions objects # build algorithm object # perform fit # cleanup # reset logging state if set by verbosity # Setup logging (using verbosity) # ------------------------------------------------------------------- if verbosity: # find out the logging level of highest level logger and remember it. fplog = logging.getLogger('fitpy') old_logging_level = fplog.getEffectiveLevel() # this setting will percolate down to lower level loggers. fplog.setLevel(verbosity) # Clean up input # ------------------------------------------------------------------- logger.debug('Verifying input.') # Verify cost function is callable if not isinstance(cost_function, collections.Callable): logger.critical( 'cost_function must be a function or object with a __call__ method.') raise TypeError('cost_function is not callable.') # Consolodate parameter information # ------------------------------------------------------------------- # Get names of the target_function's parameters. logger.debug('Determining number and names of parameters.') parameter_names = funcutils.get_parameter_names(cost_function) num_parameters = len(parameter_names) logger.info('Found %d parameter(s) in target function.' % num_parameters) # Accept parameter constrains as either a dictionary or list. parameter_constraint_list = format_as_list( parameter_constraints, parameter_names) # Accept initial guess as either a dictionary or a list. initial_guess_list = format_as_list(initial_guess, parameter_names) # Construct algorithm # ------------------------------------------------------------------- # Build end_conditions objects logger.debug('Building end conditions.') ecs = factories.make_simple_end_conditions(max_evaluations, max_runtime, target_cost, **kwargs) # Build algorithm object logger.debug('Building algorithm object.') fitting_algorithm = factories.make_algorithm(cost_function, parameter_constraint_list, ecs, algorithm_name, **kwargs) # Perform fit # ------------------------------------------------------------------- logger.info('Beginning fit.') result = fitting_algorithm.run(initial_guess_list, **kwargs) best_parameters = result['best_parameters'] logger.info('Fit complete: best cost %f.' % result['evaluation_cache'][best_parameters]) for name, value in itertools.izip(parameter_names, best_parameters): logger.info('%s = % f' % (name, value)) # Cleanup # ------------------------------------------------------------------- # Reset logging state if set by verbosity if verbosity: fplog.setLevel(old_logging_level) return result
Python