Example #1
0
def main():
	print "Content-type: text/html\n"
	try:
		import set_sid_qs_worker
	except:
		print "<!-- --><hr><h1>Oops.  An error occurred.</h1>"
	cgi.print_exception()
Example #2
0
	def run_as_cgi(self):
		"Carry out the job of yarrow run as a CGI script."

		original_stdout = sys.stdout
		try:
			self.fly = sys.stdout = fly.webfly()

			self.decide_tasks()
			self.connect()
			self.begin_tasks()
			self.print_headers()
			self.finish_tasks()
			self.print_footers()

			self.fly.print_to(original_stdout,
					  'gzip' in maybe_environ('HTTP_ACCEPT_ENCODING'),
					  maybe_environ('HTTP_IF_NONE_MATCH'))
		except:
			# last-ditch error handler
			sys.stdout = original_stdout
			print "Content-Type: text/html"
			print
			print "<h1>Something went wrong there.</h1>"
			cgi.print_exception()
			try:
				self.maybe_print_logs()
			except:
				pass # Oh well.
			print '<p><b>Please send email to '+\
			      '<a href="mailto:[email protected]">' +\
			      '[email protected]</a>, '+\
			      'quoting the text above.</b> Thanks!</p>'
Example #3
0
def run():
    try:
        http_headers()
        print '''
                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                <title>Quest</title>
                <style type="text/css">
                    #query {
                        width: 800px;
                        height: 45px;
                    }
                </style>

                <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
                <script type="text/javascript">
                    $(document).ready(function(){
                        $('#theForm').submit(function(e){
                            e.preventDefault();
                            $.get('navigator.py',
                                {query: $('#query').val()},
                                function(data, textStatus, xhr){
                                    $('#mySearch').html(data);
                                });
                        });
                    });
                </script>
                </head>
                <body>

                <table>
                    <h1 align="center">QUEST</h1>
                    <tr>
                        <form id="theForm">
                        <br/>
                        <p align="center">
                            Enter your Query
                            <input id="query" name="query" size=48 />
                            <input id="submit" type="submit" value="Submit" />
                        </p>
                        </form>
                    </tr>

                    <tr id="mySearch">
                        <hr></hr>
                    </tr>
                </table>
                </body>
                </html>
         '''.strip()
    except:
        http_headers()
        print "<h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
Example #4
0
def htmlTail():
    print("""</body>
             </html>""")

# main program
    if __name_== "__main__":
        try:
            htmlTop()
            print("Hello world!")
            htmlTail()
        except:
            cgi.print_exception()
Example #5
0
def crawl(form):
        print("<html>")
        print("<head><title>Classified Crawler</title><link rel=\"stylesheet\" type=\"text/css\" href=\"/6speed/style.css\"></head>")
        print("<body>")
        #BEGIN PAGE BODY

        if "crawl_url" not in form:
                try:
                        print("<form action=\"/cgi-bin/6speed.py\" method=\"GET\">URL to Crawl: <input type=\"text\" name=\"crawl_url\" size=\"100\"><br /><input type=\"hidden\" name=\"do\" value=\"crawl\"><input type=\"submit\" value=\"Submit\" /></form>")


                except:
                        cgi.print_exception()

        else:
                try:
                        url = form["crawl_url"].value
                        content = get_data(url)

                        print("Here is the data you are about to import into the database.<br />")
                        print("<div class=\"container\">")
                        print("<table class=\"display_out\">")


                        print("<tr><th>YEAR</th><th>MAKE</th><th>MODEL</th><th>MILEAGE</th><th>PRICE</th><th>LOCATION</th><th>POST ID</th><th>URL</th><th>DESCRIPTION</th></tr>")

                        print("<tr><td>",content['year'],"</td><td>",content['make'],"</td><td>",content['model'],"</td><td>",content['mileage'],"</td><td>",content['price'],"</td><td>",content['loc'],"</td><td>",content['post'],"</td><td><a href=\"",url,"\">LINK</a></td><td>",content['title'],"</td></tr>")

                        print("</table></div>")
                        print("Do you wish to continue?<br />")
                        print("<form action=\"/cgi-bin/6speed.py\" method=\"GET\" enctype=\"multipart/form-data\">\n"
                        "<input type=\"hidden\" name=\"do\" value=\"insert\">\n"
                        "<input type=\"hidden\" name=\"year\" value=",content['year'],">\n"
                        "<input type=\"hidden\" name=\"make\" value=",content['make'],">\n"
                        "<input type=\"hidden\" name=\"model\" value=",content['model'],">\n"
                        "<input type=\"hidden\" name=\"price\" value=",content['price'],">\n"
                        "<input type=\"hidden\" name=\"mileage\" value=",content['mileage'],">\n"
                        "<input type=\"hidden\" name=\"loc\" value=",content['loc'],">\n"
                        "<input type=\"hidden\" name=\"post\" value=",content['post'],">\n"
                        "<input type=\"hidden\" name=\"title\" value=\"",content['title'],"\">\n"
                        "<input type=\"hidden\" name=\"url\" value=",url,">\n"
                        #"<input type=\"hidden\" name=\"crawl_url\" value=",url,">\n"
                        "<input type=\"submit\" value=\"Submit\" /> </form>\n")

                except:
                        cgi.print_exception()

        #END PAGE BODY
        print("</body>")
        print("</html>")

        return
def test2():
    try:
        http_headers()
        
        s = "This will be a very long string.This will be a very long string.This will be a very long string.This will be a very long string.This will be a very long string.This will be a very long string.This will be a very long string."
        form = cgi.FieldStorage()
        
        html = ['''
                <html>
                <body>
                
                <table border="1">
                <tr>
                <td>
                ''']
        
        if form.has_key("readmore"):
            x = 0
            y = 41
            while x < len(s):
                html += [s[x:y], "<br \>"]
                x+=41
                y += 41
            
            html += [ '''
                <form method = "post" action = "">
                <input type="submit" name = "readless" value="Read Less"  />
                </form></td>''']
        else:
            if len(s) > 15:
                html += [s[0:15], "..."]
            else:
                html += [s]
            
            html += ['''
                     <form method = "post" action = "">
                     <input type="submit" name = "readmore" value="Read More"  />
                     </form></td>''']

        html += ['''
                 
                <td>Row 1, cell 2</td>
                </tr>
                </table>
                </body>
                </html>
                ''']
        print "\n".join(html)    
    except:
        http_headers()
        print "<!-- --> <hr><h1>Oops... an error occurred.</h1>"
        cgi.print_exception()
def run():
    try:
        html = []
        includes()
        html += [
            '<form name="input" action="createAccount.py" method="post">',
            'User Name: <input type="text" name="UserName" align="right" /><br />',
            'Password: <input type="password" name="Password"/><br />',
            "<br />",
            'First name: <input type="text" name="FirstName"/><br />',
            'Last name: <input type="text" name="LastName"/><br />',
            'Phone Number: <input type="text" name="PhoneNumber"/><br />',
            'Billing Address: <input type="text" name="BillingAddress"/><br />',
            'Shipping Address: <input type="text" name="ShippingAddress"/><br />',
            'Credit Card Number: <input type="text" name="CreditCard"/><br />',
            '<input type="submit" value="Submit" name = "Submit" />',
            "</form> ",
        ]
        # print '\n'.join(html)
        form = cgi.FieldStorage()
        if form.has_key("CreditCard"):
            credit_card = form["CreditCard"].value

            try:
                int(credit_card)
                if is_luhn_valid(credit_card):

                    html += [
                        "Your account has been made. You will be redirected to the main page",
                        "or you can click HERE",
                    ]
                else:
                    html += [
                        "You entered an invalid credit card number. Click",
                        "<A HREF='javascript:javascript:history.go(-1)'>HERE</A> to try again.",
                    ]
            except:
                html += [
                    "Please make sure that the credit card number you entered is an actual number. Click",
                    "<A HREF='javascript:javascript:history.go(-1)'>HERE</A> to try again.",
                ]
        else:
            html += [""]
        http_headers()
        print "\n".join(html)
    except:
        http_headers()
        print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
Example #8
0
def serve_one_page():

    emit_header()

    try:
        global form
        form = cgi.FieldStorage()

        handlers = { 'fullsearch':  do_fullsearch,
                     'titlesearch': do_titlesearch,
                     'edit':        do_edit,
                     'viewsource':  do_viewsource,
                     'viewunmodifiedsource':  do_viewunmodifiedsource,
                     'savepage':    do_savepage,
                     'unmodified':  do_unmodified,
                     'deletelocal': do_deletelocal,
                     'removepage':  do_removepage}

        for cmd in handlers.keys():
            if form.has_key(cmd):
                apply(handlers[cmd], (form[cmd].value.decode('utf8'),))
                break
        else:
            path_info = environ.get('PATH_INFO', '')

            if form.has_key('goto'):
                query = form['goto'].value.decode('utf8')
            elif len(path_info) and path_info[0] == '/':
                query = path_info[1:] or 'FrontPage'
            else:
                query = environ.get('QUERY_STRING', '') or 'FrontPage'

            #word_match = re.match(word_re_str, query)
            word_match = re.match(versioned_page_re_str, query)
            #sys.stderr.write("query: %s [%s]\n" % (repr(query),
            #                                       repr(word_match)))
            if word_match:
                word = word_match.group('wikiword')
                if not word_match.group('version') is None:
                    word = "%s_%s" % (word, word_match.group('version'))
                Page(word).send_page()
            else:
                print "<p>Can't work out query \"<pre>" + query + "</pre>\""

    except:
        cgi.print_exception()

    sys.stdout.flush()
def main():
	# fileFound = True
	# open the file representing the sensor.
	# fileobj = open(devicefile,'r')
	# lines = fileobj.readlines()
	# fileobj.close()
	# cgitb.enable()
	# form = cgi.FieldStorage()
	#first_name = form.getvalue('first_name')
	#last_name  = form.getvalue('last_name')
	# tempstr = lines[1][-6:-1]
	# tempvalue = float(tempstr)/1000*5/3+32

    temp = getDataFromDB()
    print"Content-type: text/html\n\n"
    print temp
    cgi.print_exception()      # catch and print errors
Example #10
0
def run():
    try:
        http_headers()
        buttons = cgi.FieldStorage()
        query = buttons.getvalue('query')
    except:
        http_headers()
        print "<hr><h1>Oops! A Quest-related error occurred.</h1>"
        cgi.print_exception()
    else:
        # Handle errors raised by Quest separately
        try:
            print str(handle_user_input(query)).strip()
        except:
            http_headers()
            print "<hr><h1>Oops! Quest couldn't handle your input.</h1>"
            cgi.print_exception()
Example #11
0
def safe_render(pagename):
	print "Content-Type: text/html\n"
	try:
		from locus import render_a_page
		render_a_page(pagename)
	except:
		print "<html><head><title>Server-Side Error</title></head>\n<body>"
		print "<!-- --><h1>Sorry, An Error Occurred</h1>\n"
		print "Please try back in a few minutes; we are working hard to fix this problem.\n"
		print "<br>&nbsp;\n"
		print "<br>&nbsp;\n"
		print "<br>&nbsp;\n"
		print "<h1 style=\"color:#999999;\">Error Specifics</h1>\n<span style=\"color:#996666;\">"
		
		#Print our error in a safe way
		cgi.print_exception()
		
		print "</span></body></html>"
Example #12
0
def get_threads():
        page = urllib.request.urlopen(homepage)
        soup = BeautifulSoup(page,"html5lib")
        threads = soup.findAll('a', id=re.compile('^thread_title_'))
        threads = threads[3:]
        post = [0] * len(threads)
        href = [0] * len(threads)
        try:
                for index in range(len(threads)):
                        href[index] = threads[index].get('href')
                        post[index] = threads[index].get('id').lstrip('thread_title')
                        threads[index] = threads[index].decode().encode('ascii','ignore')
                        threads[index] = threads[index].decode()

        except:
                cgi.print_exception()

        return(threads,href,post)
Example #13
0
def getData():
    formData = cgi.FieldStorage()
    word = formData.getvalue('word')
    if len(word) > 7:
    return word


def main():
    htmlTop()

    htmlTail()
    


if __name__ == "__main__":
    try:
        main()
    except:
        cgi.print_exception()
def run():
    try:
        html = []
        http_headers()
        print """

        <frameset rows="20%,80%" frameborder="NO" border ="0" id="Frame1">
          <frame src="search_frames.py" name ="Frame_search"/>
          <frameset cols="20%,80%" id="Frame2">
            <frame src="leftframe.py" id="Frame_links" name = "Frame_links"/>
            <frame src="mainframe.py" id="Frame_body" name = "Frame_body"/>
          </frameset>
        </frameset>
    
        """
        
    except:
        http_headers()
        print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
Example #15
0
def insert_data(form):
        try:
                cnx = mysql.connector.connect(**config)
                cur = cnx.cursor()
                query = "INSERT IGNORE INTO classified (year,make,model,price,mileage,loc,post,pageurl,title) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                args = (form["year"], form["make"], form["model"], form["price"], form["mileage"], form["loc"], form["post"], form["url"], form["title"])
                cur.execute(query,args)
                cur.close()
                success = 1

        except:
                cgi.print_exception()

        if(success):
                print("")
                success=0
                cnx.commit()
                cnx.close()

        return
Example #16
0
def sendXmlString(xml, nbi_url):

  buf = cStringIO.StringIO()
  c=pycurl.Curl()
  c.setopt(c.FAILONERROR, True)
  c.setopt(c.HTTPHEADER, ['Accept: text/xml', 'Accept-Charset: UTF-8'])
  c.setopt(pycurl.SSL_VERIFYPEER, False) 
  c.setopt(c.POSTFIELDS,xml)
  c.setopt(c.WRITEFUNCTION, buf.write)
  try:
	c.setopt(c.URL, nbi_url)
	c.setopt(c.POSTFIELDS, xml)
	c.setopt(c.VERBOSE,True)
	c.perform()
  except:
	cgi.print_exception()
      
  response = buf.getvalue()
  buf.close  

  return response 
def updateCustomer():
    try:
        html = []
        
        html += ['''
                <html>
                <body>
                Do you want to create or update a customer's account?
                 
                <form name="input" action="updateCustomer.py" method="post">
                <input type="radio" name="change" value="create" /> Create<br />
                <input type="radio" name="change" value="update" /> Update<br />
                <input type="submit" value="Submit" />
                </form> 
                </body>
                ''']
        form = cgi.FieldStorage()

        if form.has_key("change"):
            if form["change"].value == "create":
                html += ["This will go to the Create Page (we already made this)"]
            else:
                html += ['''This will update the account
                         <form name="input" action="updateCustomer.py" method="post">
                         Customer ID: <input type = "text" name = "custID" />
                         <input type="submit" value="Submit" />
                         </form>
                         ''']
        
        if form.has_key("custID"):
            html += ["Bring up customer's info (Go to database)"]
            

        http_headers()
        print "\n".join(html)    
    except:
        http_headers()
        print "<!-- --> <hr><h1>Oops... an error occurred.</h1>"
        cgi.print_exception()
Example #18
0
def display():
        try:
                cnx = mysql.connector.connect(**config)

                cur = cnx.cursor()
                query = "SELECT * from classified"
                cur.execute(query)


                print("<html>")
                print("<head><title>Classified Output</title><link rel=\"stylesheet\" type=\"text/css\" href=\"../6speed/style.css\"><script src=\"../6speed/js/sorttable.js\"></script></head>")

                print("<body>")
                #BEGIN PAGE BODY
                print("<div class=\"navigation\"><ul><li><a href=\"?do=display\">Display</a></li><li><a href=\"?do=crawl\">Crawl</a></li></ul></div>\n")

                print("<div class=\"head\"><h2>Output of 6speedOnline Classifieds</h2>As seen <a href=\"http://www.6speedonline.com/forums/automobiles-sale-29/\">here</a></div>")

                print("<div class=\"container datagrid\">")
                print("<table class=\"display_out sortable\">")
                print("<thead><tr><th>ID</th><th>DATE ADDED</th><th>STATUS</th><th>DESCRIPTION</th><th>POST URL</th><th>POST ID</th><th>YEAR</th><th>MAKE</th><th>MODEL</th><th>PRICE</th><th>MILES</th><th>LOCATION</th></tr></thead>")
                print("<tbody>")
                x=1
                for row in cur.fetchall():
                        if (x % 2): trclass="alt"
                        print("<tr class=\"",trclass,"\"><td>",row[0],"</td><td>",row[1].strftime('%b %d'),"</td><td>",row[2],"</td><td>",row[11],"</td><td><a href=\"",row[3],"\">LINK</a></td><td>",row[4],"</td><td>",row[5],"</td><td>",row[6],"</td><td>",row[7],"</td><td>",row[8],"</td><td>",row[9],"</td><td>",row[10],"</td></tr>")
                        trclass=""
                        x=x+1
                print("</tbody></table></div>")

                #END PAGE BODY
                print("</body>")
                print("</html>")

        except:
                cgi.print_exception()

        cnx.close()
        return
Example #19
0
def new_crawl():
        print("<body>")
        print("<div class=\"navigation\"><ul><li><a href=\"?do=display\">Display</a></li><li><a href=\"?do=crawl\">Crawl</a></li></ul></div>\n")
        print("Crawling URL: ",homepage,"<br /><br />")
        print("Found these threads, begin crawling...<br />")
        time.sleep(2)

        (threads,crawl_url,post) = get_threads()
        for row in threads: print(row,"<br />")

        print("Finished getting threads.<br />")

        try:
                for row in crawl_url:
                        form,failflag = get_data(row)
                        if not failflag:
                                insert_data(form)
        except:
                cgi.print_exception()
        print("Finished crawling.</body>")

        return
Example #20
0
def get_data(url):
        try:
                post_data = []
                page = urllib.request.urlopen(url)
                soup = BeautifulSoup(page,"html5lib")

                year = soup.body.div.find(text=re.compile('Year:')).next_element.strip()
                make = soup.body.div.find(text=re.compile('Make:')).next_element.strip()
                model = soup.body.div.find(text=re.compile('Model:')).next_element.strip()
                price = soup.body.div.find(text=re.compile('Price:')).next_element.strip().lstrip("$")
                mileage = soup.body.div.find(text=re.compile('Mileage:')).next_element.strip()
                loc = soup.body.div.find(text=re.compile('\(State\):')).next_element.strip()
                post = soup.find('input', {'name':'t'}).get('value').strip()
                title = soup.body.div.h1.next_element.strip().encode('ascii','ignore')
                title = title.decode('ascii')

                post_data = {
                        'year': year,
                        'make': make,
                        'model': model,
                        'price': price,
                        'mileage': mileage,
                        'loc': loc,
                        'post': post,
                        'title': title,
                        'url': url,
                }

        except AttributeError:
                print("Found error at thread: ",url,"<br />")
                print("Some values not found, skipping...<br />")
                return 0,1

        except:
                cgi.print_exception()
                return 0,1

        return(post_data,0)
Example #21
0
def main():
    if 'REQUEST_METHOD' not in os.environ:
        sys.stderr.write("error: this program is meant to be used as a cgi\n")
        sys.exit(1)
    print("Content-type: text/html\n\n")
    try:
        username = os.environ.get("REMOTE_USER")
        method = os.environ.get("REQUEST_METHOD")
        if not username or method != "POST":
            show()
        else:
            useremail = config.get("users", username)
            if not useremail:
                raise CgiError(
                    "Your email was not found. Contact the administrator!")
            submit_packages(useremail)
    except CgiError as e:
        show(str(e), error=1)
    except Error as e:
        error = str(e)
        show(error[0].upper() + error[1:], error=1)
    except:
        cgi.print_exception()
Example #22
0
#! /usr/local/bin/python
"""FAQ wizard bootstrap."""
# This is a longer version of the bootstrap script given at the end of
# faqwin.py; it prints timing statistics at the end of the regular CGI
# script's output (so you can monitor how it is doing).
# This script should be placed in your cgi-bin directory and made
# executable.
# You need to edit the first line and the lines that define FAQDIR and
# SRCDIR, below: change /usr/local/bin/python to where your Python
# interpreter lives, change the value for FAQDIR to where your FAQ
# lives, and change the value for SRCDIR to where your faqwiz.py
# module lives.  The faqconf.py and faqcust.py files live there, too.
import os
t1 = os.times()  # If this doesn't work, just get rid of the timing code!
try:
    FAQDIR = "/usr/people/guido/python/FAQ"
    SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz"
    import os, sys, time, operator
    os.chdir(FAQDIR)
    sys.path.insert(0, SRCDIR)
    import faqwiz
except SystemExit, n:
    sys.exit(n)
except:
    t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
    print
    import cgi
    cgi.print_exception(t, v, tb)
t2 = os.times()  # If this doesn't work, get rid of this and what follows!
fmt = "<BR>(times: user %.3g, sys %.3g, ch-user %.3g, ch-sys %.3g, real %.3g)"
Example #23
0
        higher_level = ''
    container = container.format(name=name,
                                 level=spell['level'],
                                 school=spell['school'],
                                 classes=spell['dnd_class'],
                                 archetypes=spell['archetype'],
                                 range=spell['range'],
                                 duration=spell['duration'],
                                 components=spell_components,
                                 concentration=spell['concentration'],
                                 ritual=spell['ritual'],
                                 spelldesc=spell['desc'],
                                 higher_level=higher_level,
                                 source=spell['page'],
                                 license=spell['document__license_url'])
    return container


def main():
    spell = spell_html_format()
    page = 'Content-type:text/html\n\n' + codecs.open(
        'dependencies/index/index.html', 'r', 'utf-8').read().format(
            title='homepage', body=spell)
    print(page)


try:
    main()
except:
    print(cgi.print_exception())
Example #24
0
    numStr1 = form.getfirst("x",
                            "0")  # get the form value associated with form
    # name 'x'.  Use default "0" if there is none.
    numStr2 = form.getfirst("y", "0")  # similarly for name 'y'
    contents = processInput(numStr1, numStr2)  # process input into a page
    print(contents)


def processInput(numStr1, numStr2):
    '''Process input parameters and return the final page as a string.'''
    num1 = int(numStr1)  # transform input to output data
    num2 = int(numStr2)
    total = num1 + num2
    return fileToStr('additionTemplate.html').format(**locals())


# standard code for future cgi scripts from here on
def fileToStr(fileName):
    """Return a string containing the contents of the named file."""
    fin = open(fileName)
    contents = fin.read()
    fin.close()
    return contents


try:  # NEW
    print("Content-type: text/html\n\n")  # say generating html
    main()
except:
    cgi.print_exception()  # catch and print errors
Example #25
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0,
         cgi.print_exception(self.input(0), self.input(1), self.input(2),
                             self.input(3)))
Example #26
0
print "Content-Type: text/html"
print ""

import cgi

def head():
	print '''<html>
				<head>
					<title> Exp </title>
				</head>
				<body>'''
				
def tail():
	print '''</body>
			</html>'''
			
if __name__=="__main__":
	try:
		head()
		print ''' <h2> Department menu </h2> <br>
					<h3>
						<a href='dept_form.py'> Register new department </a> <br> <br>
						<a href='dept_edit.py'> Edit a department </a> <br> <br>
						<a href='dept_del.py'> Delete a department </a> <br> <br> <br> <br> <br> <br>
						<a href='home.py'> Go to home </a>
					</h3> '''
		tail()
	except:
		cgi.print_exception()
   elif action == 'info': 
      print info(wn)
   elif action == 'meta': 
      print meta(wn)
   else: print '<p>Unknown action: %s</p>' % action

def run(argv=None): 
   if argv is None: 
      argv = sys.argv[1:]

   if argv: 
      if argv[0] in ('-h', '--help'): 
         print __doc__.lstrip()
      else: 
         if argv[0] in ('-w', '--wikify'): 
            func = wikify
         elif argv[0] in ('-p', '--parse'): 
            func = wikiParse

         if len(argv) > 1: 
            import urllib
            s = urllib.urlopen(argv[1]).read()
         else: s = sys.stdin.read()
         sys.stdout.write(func(s))

if __name__=='__main__': 
   if os.environ.has_key('SCRIPT_NAME'): 
      try: main()
      except: cgi.print_exception()
   else: run()
Example #28
0
# This is a longer version of the bootstrap script given at the end of
# faqwin.py; it prints timing statistics at the end of the regular CGI
# script's output (so you can monitor how it is doing).

# This script should be placed in your cgi-bin directory and made
# executable.

# You need to edit the first line and the lines that define FAQDIR and
# SRCDIR, below: change /usr/local/bin/python to where your Python
# interpreter lives, change the value for FAQDIR to where your FAQ
# lives, and change the value for SRCDIR to where your faqwiz.py
# module lives.  The faqconf.py and faqcust.py files live there, too.

import os
t1 = os.times()  # If this doesn't work, just get rid of the timing code!
try:
    FAQDIR = "/usr/people/guido/python/FAQ"
    SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz"
    import os, sys
    os.chdir(FAQDIR)
    sys.path.insert(0, SRCDIR)
    import faqwiz
except SystemExit, n:
    sys.exit(n)
except:
    t, v, tb = sys.exc_info()
    print
    import cgi
    cgi.print_exception(t, v, tb)
Example #29
0
	i=0
	file=open("Part1.txt")
	html_string = file.read()
	file.close()
	for sig_name in sorted(sig_list, key=str.lower):
		signale+="{ sig_sel: '%s'}," %(sig_name) 
#		print(sig_name)
	html_string+=signale[:-1]
#	print(html_string)
	file2=open("Part2.txt")
	html_string+=file2.read()
	file2.close()
	file=open("htmltext.html",'w')
	file.write(html_string)
	file.close()
	return html_string
			

#Muss später ins Hauptprogramm kopiert werden
try:   # NEW
	cgitb.enable()
	print("Content-Type: text/html;charset:UTF-8")   # say generating html
	print("\n\n")
	msg_list=dbc_main()
	filename=os.path.join('/home/pi/datalogger/loggerconfigs/','testdump.txt')
	with open(filename, 'wb') as file:
		pickle.dump(msg_list, file)
except:
    cgi.print_exception()  # catch and print errors
	
Example #30
0
#! /usr/local/bin/python
"""FAQ wizard bootstrap."""
# This is a longer version of the bootstrap script given at the end of
# faqwin.py; it prints timing statistics at the end of the regular CGI
# script's output (so you can monitor how it is doing).
# This script should be placed in your cgi-bin directory and made
# executable.
# You need to edit the first line and the lines that define FAQDIR and
# SRCDIR, below: change /usr/local/bin/python to where your Python
# interpreter lives, change the value for FAQDIR to where your FAQ
# lives, and change the value for SRCDIR to where your faqwiz.py
# module lives.  The faqconf.py and faqcust.py files live there, too.
import os
t1 = os.times() # If this doesn't work, just get rid of the timing code!
try:
    FAQDIR = "/usr/people/guido/python/FAQ"
    SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz"
    import os, sys, time, operator
    os.chdir(FAQDIR)
    sys.path.insert(0, SRCDIR)
    import faqwiz
except SystemExit, n:
    sys.exit(n)
except:
    t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
    print
    import cgi
    cgi.print_exception(t, v, tb)
t2 = os.times() # If this doesn't work, get rid of this and what follows!
fmt = "<BR>(times: user %.3g, sys %.3g, ch-user %.3g, ch-sys %.3g, real %.3g)"
def insertMovie():
    try:
        html = ['''
                <html>
                <body>
                <form>
                Insert a movie into the Movie Database. <br />
                Note: TMDb's API will handle populating the movie's fields. <br /><br />
                Movie Title: <input type = "text" name = "movie" id="movietitle"/> 
                <input id="searchmovieTitle" type = "button" value = "Submit" onclick="loadXMLDoc(this)" />
                </form>
                ''']
        http_headers()
        print "\n".join(html)           
        
        form = cgi.FieldStorage()
        
        if form.has_key("movieID"):
            movieAPI = tmdb.getMovieInfo(form["movieID"].value)
            movie = movieObject.Movie(movieAPI['name'])
            
            try:
                year_released = movieAPI['released']
                year_released2 = year_released.split('-', 1 ) #show only the year, not whole date
                year_released = year_released2[0]
                movie.setYear(year_released)
            except:
                movie.setYear("Unavailable")
                
            try:
                photo_url = movieAPI['images'].posters[0]['cover']
                movie.setPhoto(photo_url)
            except:
                #Image Unavailable" picture is copyright of Town Of Warner(tm)
                movie.setPhoto("http://www.townofwarner.com/images/businesses/notavailable.gif")
            
            if form.has_key("trailerURL"):
                movie.setTrailer(form["trailerURL"].value)
            else:
                movie.setTrailer("Unavailable")
            
            try:
                genres = movieAPI['categories']['genre']
                movie.setGenre(genres.keys()[0])
            except:
                movie.setGenre("Unavailable")
        
            try:
                directors = movieAPI['cast']['director']
                
                directors_first = []
                directors_last = []
                
                for director in directors:
                    directors_name = director['name'].partition(' ')
                    directors_first.append(directors_name[0])
                    directors_last.append(directors_name[2])
                    
                movie.setDirectorsFirst(directors_first)
                movie.setDirectorsLast(directors_last)
                
            except:
                movie.setDirectorsFirst([])
                movie.setDirectorsLast([])

            try:
                actors = movieAPI['cast']['actor']
                
                actors_first = []
                actors_last = []
                
                for actor in actors:
                    actor_name = actor['name'].partition(' ')
                    actors_first.append(actor_name[0])
                    actors_last.append(actor_name[2])
                    
                movie.setCastFirst(actors_first)
                movie.setCastLast(actors_last)
                
            except:
                movie.setCastFirst([])
                movie.setCastLast([])
                
            try:
                summary = movieAPI['overview']
                movie.setSummary(summary)
            except:
                movie.setSummary("Unavailable")
                
            displayMovieInfo(movie)
            
            
        elif form.has_key("movie"):
            results = tmdb.search(form["movie"].value)
            
            try:
                results[0] #this checks if the movie list isn't empty
                
                html = ['''
                <br \><p><strong>Based on the list provided below, submit the
                    proper ID number in order to insert the movie.</strong></p>
                <p><i>Unfortunately, TMDb API does not supply trailer links. <strong>If applicable</strong>,
                    please also supply a URL for the movie's trailer.</i></p> 
                <form name = "movie_input">
                Movie ID: <input type = "text" name = "movieID"  id="mid"/> <br />
                Trailer URL: <input type = "text" name = "trailerURL" id="turl" /> <br />
                <input type = "button" value = "Submit" onclick="loadXMLDoc(this)" id="fulldetail" /><br \> <br \>
                <strong>LIST OF MOVIES</strong> <br />
                     ''']
                print "\n".join(html)
                
                #This prints out all of the possible movies based on the movie title the employee writes.
                #It prints the movie's ID, title, and year released (if provided in API).
                for searchResult in results:
                    print tmdb.getMovieInfo(searchResult['id'])['id'] + ": "
                    print tmdb.getMovieInfo(searchResult['id'])['name']
                    
                    year_released = tmdb.getMovieInfo(searchResult['id'])['released']
                    if year_released != None:
                            year_released = year_released.split('-', 1 ) #show only the year, not whole date
                            print "(%s)" %year_released[0]
                    html = ["<br />"]
                    print "\n".join(html)
            except:
                print "The movie could not be found in the API."  
                
                #Sometimes this will show at the end of the list even though
                #movies have been found. Try typing Transformers; the last
                #item in the list will show this. I think it's an ascii error.
    
        html = ['''
                </body>
                </html>
                ''']
        print "\n".join(html)
    
    except:
        http_headers()
        print "<!-- --> <hr><h1>Oops... an error occurred.</h1>"
        cgi.print_exception()
Example #32
0
            # In case we preview instead of save
            response = post(name)
            if response:
                print response
                return
        print get(name)
    elif action == 'edit':
        print edit(name)
    elif action == 'remove':
        print remove(name)
    elif action == 'info':
        print info(name)
    elif action == 'meta':
        print meta(name)
    elif action == 'diff':
        print diff(name)
    else:
        print notfound(action)
    return

def handle_cmd():
    print "This is a CGI application. It only runs inside a web server."
    return

if __name__=='__main__': 
    if env.has_key('SCRIPT_NAME'): 
        try: main()
        except: cgi.print_exception()
    else:
        sys.exit(handle_cmd())
def run():
    try:

        info=cgi.FieldStorage()
        cust_id=info.getvalue('cust_id')

        query="""select first_name,last_name from customer where cust_id=%s"""%cust_id
        
        db = MySQLdb.connect("localhost","root","pass1","assign3")
        c = db.cursor()
        c.execute(query)
        data=c.fetchall()
        firstname=data[0][0]
        lastname=data[0][1]


        query="""select phone_num from phone where cust_id=%s"""%cust_id
        c.execute(query)
        data=c.fetchall()
        phonenum=data[0][0]


        query="""select * from creditcard where cust_id=%s"""%cust_id
        c.execute(query)
        data=c.fetchall()
        
        ccn=data[0][0]
        bill_addr=data[0][2]
        ship_addr=data[0][3]
        username=data[0][4]
        password=data[0][5]










        http_headers()
        print """
			<html>
			<head>
			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
			<script src="http://code.jquery.com/jquery-latest.js"></script>
			<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
			<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
			<script type="text/javascript">
			jQuery.validator.setDefaults({
				debug: true,
				success: "valid"
			});;
			</script>

			  <script>
			  $(document).ready(function(){
				$("#signin").validate({
			  rules: {
				field: {
				  required: true,
				  creditcard: true
				}
			  }
			});
			  });
			  </script>
			<script type="text/javascript"> 
			$(document).ready(function(){
			$(".flip").click(function(){
				$(".panel").slideToggle("slow");
			  });
			});
			</script>
			 
			<style type="text/css"> 
			div.panel,p.flip
			{
			margin:0px;
			padding:5px;
			text-align:center;
			background:#e5eecc;
			border:solid 1px #c3c3c3;
			}
			div.panel
			{
			height:400px;
			display:none;
			}
			
			</style>
			</head>
			 
			<body>
			 
			<div class="panel">
			<fieldset id="signin_menu">
					<form method="post" id="signin">
					  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					  <label for="cust_id">Customer Id</label>
					  <input id="cust_id" name="cust_id" value="%s" title="cust_id" type="text" readonly="readonly">
					
					  </p>
					  <label for="username">Username</label>
					  <input id="username" name="username" value="%s" title="username" type="text" readonly="readonly">

					  </p>
					  <p>
						<label for="password">Password</label>

						<input id="password" name="password" value="%s" title="password" tabindex="5" type="password">
					  </p>
					  
					  <p>
						<label for="firstname">FirstName</label>

						<input id="firstname" name="firstname" value="%s" title="firstname" tabindex="5" type="firstname">
					  </p>
					  
					  <p>
						<label for="lastname">LastName</label>

						<input id="lastname" name="lastname" value="%s" title="lastname" tabindex="5" type="lastname">
					  </p>
					  
					  <p>
						<label for="phonenum">Phone Num</label>

						<input id="phonenum" name="phonenum" value="%s" title="phonenum" tabindex="5" type="phonenum">
					  </p>
					  
					  <p>
						<label for="billadd">Billing Addr</label>

						<input id="billadd" name="billadd" value="%s" title="billadd" tabindex="5" type="billadd">
					  </p>
					  
					  <p>
						<label for="shipadd">Shipping Addr</label>

						<input id="shipadd" name="shipadd" value="%s" title="shipadd" tabindex="5" type="shipadd">
					  </p>
					  
					  <p>
						<label for="field">Credit Card #</label>
						
						<input class="left" id="field" name="field" value="%s">
					  </p>
					  
					  <p class="remember">
						<input id="signin_submit" value="Update" tabindex="6" type="button" onclick="loadXMLDoc(this)">
					  </p>


					</form>
				  </fieldset>
				</div>
				 
				<p class="flip"><button id="1" type="button" onclick="flipper()">Update User Info</p>
				 
				</body>
				</html>
				"""%(cust_id,username,password,firstname,lastname,phonenum,bill_addr,ship_addr,ccn)
        
    except:
        http_headers()
        print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
Example #34
0
# This is a longer version of the bootstrap script given at the end of
# faqwin.py; it prints timing statistics at the end of the regular CGI
# script's output (so you can monitor how it is doing).

# This script should be placed in your cgi-bin directory and made
# executable.

# You need to edit the first line and the lines that define FAQDIR and
# SRCDIR, below: change /usr/local/bin/python to where your Python
# interpreter lives, change the value for FAQDIR to where your FAQ
# lives, and change the value for SRCDIR to where your faqwiz.py
# module lives.  The faqconf.py and faqcust.py files live there, too.

import os
t1 = os.times() # If this doesn't work, just get rid of the timing code!
try:
    FAQDIR = "/usr/people/guido/python/FAQ"
    SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz"
    import os, sys
    os.chdir(FAQDIR)
    sys.path.insert(0, SRCDIR)
    import faqwiz
except SystemExit as n:
    sys.exit(n)
except:
    t, v, tb = sys.exc_info()
    print()
    import cgi
    cgi.print_exception(t, v, tb)
Example #35
0
def main():

    try:
        print("Content-type: text/html\n")
        print("<html>")
        print("<body style='background-color:lightblue'>")
        print("<h1 style='color:green'>Welcome to Black Jack!</h1>")
        print("<form method='post' action='BlackJack.py'>")

        form = cgi.FieldStorage()

        currentCard = 1
        if (form.getvalue("currentCard")):
            currentCard = int(form.getvalue("currentCard"))

        if (currentCard == 1):
            getDeck()
            currentCard = 2
            lastPlayerCard = 2
        else:
            lastPlayerCard = int(form.getvalue("lastPlayerCard"))
        print("<input id='cval' type='hidden' name='currentCard' value='" +
              str(currentCard + 1) + "'>")
        print("<input id='lval' type='hidden' name='lastPlayerCard' value='" +
              str(lastPlayerCard) + "'>")

        playerHandValue = 0
        aceCount = 0
        gameOver = False

        for num in range(1, lastPlayerCard + 1):
            playerHandValue += getCardFaceVal(num)
            if (getCardFaceVal(currentCard) == 1):
                playerHandValue += 10
                aceCount += 1
            while (playerHandValue > 21 and aceCount > 0):
                playerHandValue -= 10
                aceCount -= 1
        print("<h2>Player Hand: " + str(playerHandValue) + "</h2>")

        for num in range(1, lastPlayerCard + 1):
            print("<img src='/cards/" + getCardImage(num) + "'>")

        if (playerHandValue == 21):
            gameOver = True
            print("<h2>Black Jack!!! You win !!!</h2>")
        elif (playerHandValue > 21):
            gameOver = True
            print("<h2>Busted!!! You lose !!!</h2>")
        elif (lastPlayerCard == currentCard):
            print("<h2>Do you want a hit? </h2>")
            print("<button onclick='document.getElementById(\"lval\").value=" +
                  str(lastPlayerCard + 1) +
                  "; this.form.submit();'>yes</button>")
            print("<button onclick='this.form.submit();'>no</button>")

        if (lastPlayerCard < currentCard and not gameOver):
            dealerHandValue = 0
            aceCount = 0
            done = False
            num = lastPlayerCard

            while (not done):
                num += 1
                currentCard += 1
                dealerHandValue += getCardFaceVal(num)
                if (getCardFaceVal(num) == 1):
                    dealerHandValue += 10
                    aceCount += 1
                while (dealerHandValue > 21 and aceCount > 0):
                    dealerHandValue -= 10
                    aceCount -= 1
                if (playerHandValue <= dealerHandValue <= 21):
                    done = True
                elif (dealerHandValue > 21):
                    done = True

            print("<h2>Dealer Hand: " + str(dealerHandValue) + "</h2>")

            for num in range(lastPlayerCard + 1, currentCard):
                print("<img src='/cards/" + getCardImage(num) + "'>")

            if (dealerHandValue <= 21):
                print("<h2>Dealer Wins</h2>")
            else:
                print("<h2>Dealer Busted!!!Player Wins!!!</h2>")
            gameOver = True

        if (gameOver):
            print(
                "<button onclick='document.getElementById(\"cval\").value=1; this.form.submit();'>Play Again?</button>"
            )
    except:
        print("<!-- --><hr><h1>Oops  An error occurred.</h1>")
        cgi.print_exception()  # Prints traceback, safely

    print("</form>")
    print("</body></html>")
Example #36
0
 def __init__(self):
  action=None
  command=None
  path=None
  print 'Content-type: text/html\n'
  print '<!DOCTYPE HTML>\n\
  <html>\n\
  <head>\n\
   <link rel="stylesheet" type="text/css" href="/css/vlc.css" />\n\
   <meta name="HandheldFriendly" content="true" />\n\
   <meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />\n\
   <title>vlc</title>\n\
  </head>\n\
  <body>\n\
   <p><div class="header">VLC</div></p>\n\
   <p>\n\
   <a href="vlc.py?action=babyeinstein">babyeinstein</a><br>\n\
   <a href="vlc.py?action=control">control</a><br>\n\
   <a href="vlc.py?action=fullscreen">fullscreen</a><br>\n\
   <a href="vlc.py?action=playlist">playlist</a><br>\n\
   <a href="vlc.py?action=process">process</a><br>\n\
   <a href="vlc.py?action=volume">volume</a><br>\n\
   <a href="vlc.py?action=vratio">vratio</a><br>\n\
  </p>\n\
  <p><a href="..">up</a></p>\n\
  <div class="result">\n'
  try:
   self.logger=Logger(os.environ['SCRIPT_NAME'])
   l=self.logger
   l.debug('main - gettingFields')
   form = cgi.FieldStorage() # parse query
   if form.has_key("action") and form["action"] != "":
    self.vlc=Vlc(self.logger)
    v=self.vlc
    v.connect()
    action=form["action"].value
    l.debug('Executing action '+action)
    if form.has_key("command") and form["command"] != "": 
     command=form["command"].value
     l.debug('command '+command)
    if form.has_key("path") and form["path"] != "": 
     path=form["path"].value
     l.debug('path='+path)
    if action == "add": 
     if path is None: self.add_action(command)
     else: self.add_action(command,path)
    else:
     try:
      f=getattr(self,action+'_action')
      f(command)
     #except AttributeError:
     # print 'Invalid action<br>\n'
     finally:
      pass
    print action+' - done<br>\n' 
   else:
    print 'Select an action'
  except:
   print 'Oops. An error ocurred.<br>\n'
   cgi.print_exception() # Print traceback,safely
  finally:
   if self.vlc is not None:
    self.vlc.disconnect()
  print '</div></body>\n</html>'
def run():
    try:
        http_headers()
        print """
			<html>
			<head>
			
			<title>Create New Employee</title>

			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
			<script src="http://code.jquery.com/jquery-latest.js"></script>
			
			<script type="text/javascript"> 
			$(document).ready(function(){
			$(".flip").click(function(){
				$(".panel").slideToggle("slow");
			  });
			});
			</script>
			 
			<style type="text/css"> 
			div.panel,p.flip
			{
			margin:0px;
			padding:5px;
			text-align:center;
			background:#e5eecc;
			border:solid 1px #c3c3c3;
			}
			div.panel
			{
			height:500px;
			display:none;
			}
			
			</style>
			</head>
			 
			<body>
			 
			<div class="panel">
			<fieldset id="signin_menu">
					<form>
					  <label for="username">Username (E-mail Address)</label>
					  <input id="username" name="username" value="" title="username" type="text">

					  </p>
					  <p>
						<label for="password">Password</label>

						<input id="password" name="password" value="" title="password" tabindex="5" type="password">
					  </p>
					  
					  <p>
						<label for="firstname">FirstName</label>

						<input id="firstname" name="firstname" value="" title="firstname" tabindex="5" type="text">
					  </p>
					  
					  <p>
						<label for="lastname">LastName</label>

						<input id="lastname" name="lastname" value="" title="lastname" tabindex="5" type="text">
					  </p>
					  
					  <p>
						<label for="phonenum">Phone Num</label>

						<input id="phonenum" name="phonenum" value="" title="phonenum" tabindex="5" type="text">
					  </p>
					  
					  <p>
						<label for="address">Address</label>

						<input id="address" name="address" value="" title="address" tabindex="5" type="text">
					  </p>
					  
					  <p>
						<label for="zipcodeid">Zipcode ID</label>

						<input id="zipcodeid" name="zipcodeid" value="" title="zipcodeid" tabindex="5" type="text">
					  </p>
					  
					  
					  <p class="remember">
						<input id="empaccount" value="Create Employee" tabindex="6" type="button" onclick="loadXMLDoc(this)">
					  </p>"""



        db = MySQLdb.connect("localhost","root","pass1","assign3")
        c = db.cursor()
        c.execute("select zipcode_id,city_name,state_name,zipcode from city,state,zipcode where zipcode.city_id=city.city_id and city.state_id=state.state_id order by zipcode_id asc")
        data=c.fetchall()
        db.close()
        i=0

        print """<table border="1"><tr><th>ZIPCODE ID</th><th>CITY</th><th>STATE</th><th>ZIPCODE</th></tr>""" 

        while i<len(data):
        
            


            print """<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"""%(data[i][0],data[i][1],data[i][2],data[i][3])

            i=i+1


        print "</table>"
        print """				</form>
				  </fieldset>
				</div>
				 
				<p class="flip"><button id="1" type="button" onclick="flipper()">Expand/Contract Tool Bar</p>
				 
				</body>
				</html>
				"""
        
    except:
        http_headers()
        print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
Example #38
0
def login():
    try:
        http_headers()
        
        
	
        print """
        <html>
        <head>
        <link rel="stylesheet" href="/htdocs/others/mystyle.css">
        <title>Login Screen </title>"""

        atts=cgi.FieldStorage()
        username=atts.getvalue('username')
        password=atts.getvalue('password')
        login_employee=0
        login_customer=0

        if username!=None and password!=None:



            db = MySQLdb.connect("localhost","root","pass1","assign3")
            c = db.cursor()
            c.execute("select * from creditcard where username='******' and password='******'"%(username,password))
            data=c.fetchall()

            if len(data)>0:
                login_customer=1

            else:
                c.execute("select * from employee where email='%s' and password='******'"%(username,password))
                data=c.fetchall()
    
                if len(data)>0:
                    login_employee=1

            db.close()
            
            if login_customer==1:
                print """<script type="text/javascript">alert('You have been logged in as customer');
                          document.write('Logged in as: %s');

                          document.cookie = "cooks=" + escape("c"+"%s");

                          
                          document.write('<a href="login.py" onclick="destroyCookie()"> Sign Out</a>');  

                          function destroyCookie(){

                            var cookie_date =new Date();  // current date & time
                            cookie_date.setTime(cookie_date.getTime()-1);
                            document.cookie = "cooks" + "=; expires=" + cookie_date.toGMTString();

                          }

                            
                          </script>"""%(data[0][4],data[0][4])
            elif login_employee==1:
                print """<script type="text/javascript">alert('You have been logged in as employee');
                          document.write('Logged in as: %s');
                          
                          document.cookie = "cooks=" + escape("e"+"%s");

                          
                          document.write('<a href="login.py" onclick="destroyCookie()"> Sign Out</a>');  

                          function destroyCookie(){

                            var cookie_date =new Date();  // current date & time
                            cookie_date.setTime(cookie_date.getTime()-1);
                            document.cookie = "cooks" + "=; expires=" + cookie_date.toGMTString();

                          }
  


                          </script>"""%(data[0][6],data[0][6])
            else:
                print """<script type="text/javascript">alert('Cannot log you in!!!')</script>"""
        

        
        print """
        </head>
        <body>

                
        <form action="login.py" method="post">
        <br>
        <center>
        Username: <input type="text" name="username" style="background:#bfbfbf;color:#212121;border-color:#212121;" onFocus="this.style.background = '#ffffff';" onBlur="this.style.background = #bfbfbf;">
        <br>
        Password: <input type="password" name="password" style="background:#bfbfbf;color:#212121;border-color:#212121;" onFocus="this.style.background = '#ffffff';" onBlur="this.style.background = '#bfbfbf';">
        <br>
        <input type="submit" value="Login" onClick="Login(this.form);" style="background:#bfbfbf;color:#000000;border-color:#212121;" onMouseOver="this.style.color = '#404040';" onMouseOut="this.style.color = '#000000';" onFocusr="******" onBlur="this.style.color = '#000000';">
        <br><a href="createAccount.py" >Are you a new User?</a>

        </center>
        </form>
        </body>
        </html>
        """

        
    except:
        http_headers()
        print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
        cgi.print_exception()
import cgi


def htmlTop():
    print '''Content-type:text/html\n\n
    <!DOCTYPE html>
    <html lang="en-US">
        <head>
            <meta charset="utf-8" >
            <title>My first server-side script. </title>
        </head>
        <body>'''


def htmlTail():
    print '''</body>
        </html>'''


def main():
    htmlTop()
    htmlTail()


if __name__ == '__main__':
    try:
        main()
    except:
        cgi.print_exception()
def run():
    try:
        http_headers()

        atts=cgi.FieldStorage()

        cust_id=atts.getvalue('cust_id')
        
        print '''
		
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
		<html xmlns="http://www.w3.org/1999/xhtml"> 
		<head> 
                
		<title>Janet's Video Store</title>
		<style type="text/css"> 

		#navbar ul { 
				margin: 0; 
				padding: 5px; 
				list-style-type: none; 
				text-align: center; 
				background-color: #000; 
				} 
		 
		#navbar ul li {  
				display: inline; 
				} 
		 
		#navbar ul li a { 
				text-decoration: none; 
				padding: .2em 1em; 
				color: #fff; 
				background-color: #000; 
				} 
		 
		#navbar ul li a:hover { 
				color: #000; 
				background-color: #fff; 
				}

                		
		 
		</style>

		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	  <script type="text/javascript" src="http://plugins.learningjquery.com/expander/jquery.expander.js"></script>
		<script type="text/javascript"> 
			function flipper(){
			$(".flip").click(function(){
				$(".panel").slideToggle("slow");
			  });
			}
			</script>
	    <script type="text/javascript">

             function testing(obj){
			  
			  $("div.expandable p").expander({
				slicePoint:       40,  // default is 100
				collapseTimer:    15000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
				userCollapseText: '[^]'  // default is '[collapse expanded text]'
			  });

			  obj.onclick=null;
			  
		    
                        }

            function luhn_check(card_number)
{
	
	cc_array = card_number.split( "" )
	cc_array.reverse()
	digit_string = ""
	
	for ( counter=0; counter < cc_array.length; counter++ )
	{
		current_digit = parseInt( cc_array[counter] )
		
		if (counter%%2 != 0)
		{
			cc_array[counter] *= 2
		}
		
		digit_string += cc_array[counter]
	
	}
	
	digit_sum = 0
	
	for ( counter=0; counter<digit_string.length; counter++ )
	{
		current_digit = parseInt( digit_string.charAt(counter) )
		digit_sum += current_digit
	}
	
	if ( digit_sum %% 10 == 0 )
	{
		return true
	}
	else
	{
		return false
	}

}


                        
	  
            function ifLoggedIn(){

            var results = document.cookie.match ( '(^|;) ?' + "cooks" + '=([^;]*)(;|$)' );


                        
                        if(results){

                        document.getElementById('4').innerHTML="LOG-OUT"
                        
                        }

        


            }

	    function loadXMLDoc(obj)

	    
		{
		if (window.XMLHttpRequest)
		  {
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
		  {
		  if(xmlhttp.readyState==4)
			{
                                
                        document.getElementById("mySearch").innerHTML=xmlhttp.responseText;

                        
			}
		  }

                if(obj.id==1){
		
		xmlhttp.open("GET","newReleases1.py",true);
		xmlhttp.send();}

                else if(obj.id==2){

                xmlhttp.open("GET","newAdditions1.py",true);
		xmlhttp.send(); }


		else if(obj.id==3){

                    xmlhttp.open("GET","assign3_q61.py",true);
		    xmlhttp.send();}



            else if(obj.id==5){
                

                    
                    var results = document.cookie.match ( '(^|;) ?' + "cooks" + '=([^;]*)(;|$)' );

                    if(results){
                        xmlhttp.open("GET","updatecust.py?cust_id="+%s,true);
		        xmlhttp.send();}

		    else{
                        alert('You have to login');
		    }

                }    
            






                else if(obj.id==6){
                
                    
                    var results = document.cookie.match ( '(^|;) ?' + "cooks" + '=([^;]*)(;|$)' );

                    if(results){
                        xmlhttp.open("GET","cust_history.py?cust_id="+%s,true);
		        xmlhttp.send();}

		    else{
                        alert('You have to login');
		    }

                }    
            


		else if(obj.id=="genre"){

                        xmlhttp.open("GET","searchByGenre.py?choice="+obj.value,true);
                        xmlhttp.send();}


                else if(obj.id=="signin_submit"){


                cc=document.getElementById('field').value
                pass=document.getElementById('password').value
                firstname=document.getElementById('firstname').value
                lastname=document.getElementById('lastname').value
                phonenum=document.getElementById('phonenum').value
                billadd=document.getElementById('billadd').value
                shipadd=document.getElementById('shipadd').value
                          
                if(luhn_check(cc)==false)
                    alert('Enter a proper card number')

                 else{

                      
                    xmlhttp.open("GET","insertupdatecustomer.py?cust_id="+%s+"&ccn="+cc+"&password="******"&firstname="+firstname+"&lastname="+lastname+"&bill_addr="+billadd+"&ship_addr="+shipadd+"&phonenum="+phonenum,true)
                    //+"&ccn="+cc+"&password="******"&firstname="+firstname+"&lastname="+lastname+"&bill_addr="+billadd+"&ship_addr="+shipadd+"&phonenum="+phonenum,true);

                   
                    xmlhttp.send();
                    alert('entered')


                 }
                    
                    



                }



                else if(obj.id=="submit"){

                        

                        val1=document.getElementById("Search").value;

                        
                        val2=document.getElementById("category").value;

                        

                        xmlhttp.open("GET","assign3_start1.py?submit="+val1+"&category="+val2,true);
                        xmlhttp.send();


                }

                else if(obj.id==4 && obj.innerHTML=="LOG-IN"){

                    window.location.replace("final_login.py");

                }

                else if(obj.id==4 && obj.innerHTML=="LOG-OUT"){

                    window.location.replace("navbar_ver1.py");
                    destroyCookie();

                }


            

                else if(obj.id=="xaction"){        

                        
        	
                        var pass="******";

                        var x1=document.getElementById('table').rows.length;
                        
                        for(i=1;i<x1;i++){
                        var x=document.getElementById('table').rows[i].cells;
                        z=document.getElementById(""+(i-1));
                        if(z.checked){
                        pass+=x[0].innerHTML+"_";}
                        }

                        var results = document.cookie.match ( '(^|;) ?' + "cooks" + '=([^;]*)(;|$)' );


                        
                        if(results){
                        xmlhttp.open("GET","renting.py?"+pass,true);
                        xmlhttp.send();
                        }
                        else{
                        alert('you have to log-in');
                        

                        }
                        }

           
                    }


                      function destroyCookie(){

                            var cookie_date =new Date();  // current date & time
                            cookie_date.setTime(cookie_date.getTime()-1);
                            document.cookie = "cooks" + "=; expires=" + cookie_date.toGMTString();

                          }

		</script>

		

		<link rel="stylesheet" href="/htdocs/others/mystyle.css">
		</head> 
		<body onload="ifLoggedIn()">

		<form>
              
		<div id="navbar"> 
		  <ul> 
                                
				<li><button id="1" type="button" onclick="loadXMLDoc(this)">NEW RELEASES</button></li> 
				<li><button id="2" type="button" onclick="loadXMLDoc(this)">NEW ADDITIONS</button></li> 
				<li><button id="3" type="button" onclick="loadXMLDoc(this)">MOST POPULAR</button></li>
                                <li><button id="4" type="button" onclick="loadXMLDoc(this)">LOG-IN</button></li>
                                <li><button id="5" type="button" onclick="loadXMLDoc(this)">ACCOUNT UPDATE</button></li>
				<li><button id="6" type="button" onclick="loadXMLDoc(this)">MY TRANSACTIONS</button></li> 
                                <li> <form>            
                                <select name="choice" id="genre" onclick="loadXMLDoc(this)">
                                <option value="action">Action</option>
                                <option value="adventure">Adventure</option>
                                <option value="drama">Drama</option>
                                <option value="documentary">Documentary</option>
                                </select> </form> </li> 
				
            
            
				
		  </ul> 
		</div> 
                </form>

		<table>
		

		<p align="center">Janet's Video Store</p>

		<!--insert the picture-->
		<tr>
		<h2 align="center">
			<input style="WIDTH: 221px; HEIGHT: 181px" src="/htdocs/others/movie_clipboard.gif" size=12 
			  type=image name=clip> </h2>

		</tr>

		<!--search bar-->

		<tr>

				<form><br/>      		
					<p align="center"><input type="text" style="WIDTH: 200px; HEIGHT: 15px" size=28 id="Search">&nbsp;
			  
			  
					<select id="category" style="WIDTH: 89px" size=1>
					<option selected value="movie">Movie</option>
					<option value="actor">Actor</option> 
					<option value="director">Director</option></select> 

			  <input id="submit" value="Search" type="button" onclick="loadXMLDoc(this)"> </p>


			</form>
		</tr>
                    
		<tr>
		
		<hr>
		<div id="mySearch"><b>RESULTS WILL BE DISPLAYED HERE</b></div>
		</hr>
		</tr>
		</table>

                
                
		</body> 
		</html>

		'''%(cust_id,cust_id,cust_id)
    except:
            http_headers()
            print "<!-- --><hr><h1>Oops...an error occurred.</h1>"
            cgi.print_exception()