def main():
    cgitb.enable()
    print("Content-Type: text/html;charset=utf-8\r\n\r\n")
    print(header)
    resultsv4, resultsv6 = fetchResults()
    parseResults(resultsv4, resultsv6)
    print(footer)
def cgiHandler(environ, config='./tilestache.cfg', debug=False):
    """ Read environment PATH_INFO, load up configuration, talk to stdout by CGI.
    
        This function is documented as part of TileStache's public API:
            http://tilestache.org/doc/#cgi
    
        Calls requestHandler().
        
        Config parameter can be a file path string for a JSON configuration file
        or a configuration object with 'cache', 'layers', and 'dirpath' properties.
    """
    if debug:
        import cgitb
        cgitb.enable()
    
    path_info = environ.get('PATH_INFO', None)
    query_string = environ.get('QUERY_STRING', None)
    script_name = environ.get('SCRIPT_NAME', None)
    
    status_code, headers, content = requestHandler2(config, path_info, query_string, script_name)
    
    headers.setdefault('Content-Length', str(len(content)))

    # output the status code as a header
    stdout.write('Status: %d\n' % status_code)

    # output gathered headers
    for k, v in headers.items():
        stdout.write('%s: %s\n' % (k, v))

    stdout.write('\n')
    stdout.write(content)
Beispiel #3
0
def main():

    cgitb.enable()

    # get options that may have been passed to this script
    option=get_option()

    if option is None:
        option = str(24)

    # print the HTTP header
    printHTTPheader()

    
    # start printing the page
    print "<html>"
    # print the head section including the table
    # used by the javascript for the chart
    printHTMLHead("Raspberry Pi Temperature Logger", table)

    # print the page body
    print "<body>"
    print "<h1>Raspberry Pi Temperature Logger</h1>"
    print "<hr>"
    show_stats(option)
#    print_graph_temp(rowstrcurrtmp)
    show_graph()
    print_graph_temp(rowstrcurrtmp,rowstrcurrhum)
    print "</body>"
    print "</html>"

    sys.stdout.flush()
Beispiel #4
0
def main(argv):
  cgitb.enable() 
  print('Content-type: text/html;\r\n')
  form = cgi.FieldStorage()
  service, flags = sample_tools.init(
      argv, 'webmasters', 'v3', __doc__, __file__, parents=[],
      scope='https://www.googleapis.com/auth/webmasters.readonly')
  print_row_array = []
  row2 = []
  request = __get_request(form)
  threads = []
  if isinstance(form['property_uri[]'], list):
    property_uri_list = form['property_uri[]']
    for uri in property_uri_list:
      if isinstance(request, list):
        for requestdata in request:
          thread(threads, service, uri.value, requestdata, form, print_row_array)
      else:
        thread(threads, service, uri.value, request, form, print_row_array)
  else:
    if isinstance(request, list):
      for requestdata in request:
        thread(threads, service, form['property_uri[]'].value, requestdata, form, print_row_array)
    else:
      thread(threads, service, form['property_uri[]'].value, request, form, print_row_array)
  write_rows(print_row_array)
  print("done")
def handle_request():
    server = os.environ["SERVER_NAME"].split(":")[0]
    path = os.environ["REQUEST_URI"]

    # Acquire lockfile
    lock = '/tmp/%s' % sha_constructor(path).hexdigest()
    if os.path.isfile(lock):
        doRedirect(path)
        return 
    
    with lock_file(lock):
        if DEBUG:
            import cgitb
            cgitb.enable()

        try:
            url_parts = process_url(path, server)
        except Http404, e:
            do404(e.message, DEBUG)
            return

        new_file = Transmogrify(url_parts['original_file'], url_parts['actions'])
        new_file.save()

        doRedirect(path)
def launch_api_server(test_id, listen_ip, listen_port, http_server_port,
                      admin_port, conf_sections):
    args_str = ""
    args_str = args_str + "--listen_ip_addr %s " % (listen_ip)
    args_str = args_str + "--listen_port %s " % (listen_port)
    args_str = args_str + "--http_server_port %s " % (http_server_port)
    args_str = args_str + "--admin_port %s " % (admin_port)
    args_str = args_str + "--cassandra_server_list 0.0.0.0:9160 "
    args_str = args_str + "--log_local "
    args_str = args_str + "--log_file api_server_%s.log " %(test_id)

    import cgitb
    cgitb.enable(format='text')

    with tempfile.NamedTemporaryFile() as conf, tempfile.NamedTemporaryFile() as logconf:
        cfg_parser = generate_conf_file_contents(conf_sections)
        cfg_parser.write(conf)
        conf.flush()

        cfg_parser = generate_logconf_file_contents()
        cfg_parser.write(logconf)
        logconf.flush()

        args_str = args_str + "--conf_file %s " %(conf.name)
        args_str = args_str + "--logging_conf %s " %(logconf.name)
        vnc_cfg_api_server.main(args_str)
Beispiel #7
0
def main() :

	hostname , port = defaultHostname , defaultPort
	if os.environ.has_key( 'QUERY_STRING' ) :
		if enableCgiTb : import cgitb; cgitb.enable()

		if allowCgiParameters :
			form = cgi.FormContentDict()
			hostname = form.get( 'host' , [ defaultHostname ] )[ 0 ]
			try :
				port = int( form.get( 'port' , [ defaultPort ] )[ 0 ] )
			except :
				pass
	else :
		import getopt
		options , parameters = getopt.getopt( sys.argv[ 1 : ] , 'h' , ( 'help' , ) )

		for option , argument in options :
			if option in [ '-h' , '--help' ] :
				usage()
				sys.exit( 0 )

		if len( parameters ) > 2 :
			usage()
			sys.exit( 0 )
		if 1 <= len( parameters ) <= 2 :
			hostname = parameters[ 0 ]
		if len( parameters ) == 2 :
			port = int( parameters[ 1 ] )

	getAndPrintStat( hostname , port )
Beispiel #8
0
	def __init__(self, opts):
		self._response['debug'] = {}
		if self._options['debug']:
			self._time = time.time()
			t = datetime.fromtimestamp(self._time)
			self._today = time.mktime(datetime(t.year, t.month, t.day).timetuple())
			self._yesterday = self._today - 86400
			import cgitb
			cgitb.enable()

		for opt in opts:
			self._options[opt] = opts.get(opt)

		self._options['URL'] = self._options['URL'].rstrip('/')
		self._options['root'] = self._options['root'].rstrip(os.sep)
		self.__debug('URL', self._options['URL'])
		self.__debug('root', self._options['root'])

		for cmd in self._options['disabled']:
			if cmd in self._commands:
				del self._commands[cmd]

		if self._options['tmbDir']:
			self._options['tmbDir'] = os.path.join(self._options['root'], self._options['tmbDir'])
			if not os.path.exists(self._options['tmbDir']):
				self._options['tmbDir'] = False
Beispiel #9
0
def start_application(environ, start_response):
    """ WSGIアプリケーションを開始します。

    WSGIアプリケーションではprintが使えないので、StringIOに出力する文字列を書きこんでいく.
    """
    #for debug.
    cgitb.enable()

    #IOを設定.
    io = StringIO.StringIO()

    #標準出力でunicodeを取り扱う.
    #sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

    #環境の初期化.
    app = application.CApplication(environ, start_response, io)
    app_config = config.MainConfig(app)
    controller = post_controller.CPostController(app)

    #WEBアプリケーションを開始する.
    app.run(app_config, controller)

    #for debug
    #io.write("<br />スクリプトEND")

    return io.getvalue()
Beispiel #10
0
def main():
#    cgitb.enable(display=0, logdir="/finder_debug")
    
    reload(sys)
    sys.setdefaultencoding('utf-8')
    cgitb.enable()

    print """
    <h1>Etymology Helper</h1>
    """

    keep = """  
<table>
<tr><td>
<form action="morph.py" method="post">
<input type="submit" class="button" name="qtype" value="Syllable" />
</td><td>
<input type="submit" class="button" name="qtype" value="Morphemes" />
</tr></td>
</form>
</table>
"""

    try:
        one_page()
    except():
#        err_msg = traceback.format_exc()
        output_error("Unexpected error" )
Beispiel #11
0
def main():
   import cgi
   import cgitb
   cgitb.enable()

#   opt['planet_subdir'] = 'wfs'

   global Form
   Form = cgi.FieldStorage()

   from planet import Planet
   planet = Planet(direc=opt['planet_subdir'])

   ## Handle form input
   if Form.has_key('PlanetName'):
      orig_pass = planet.password
      planet = update_config(planet)

      if Form.getvalue('Timestamp') != str(planet.last_config_change):
         err("Admin page has expired!  Perhaps somebody else is " +
             "editing this planet at the same time as you?  Please " +
             "reload this page and try again.")
         #if debug: err("%s != %s" % (Form.getvalue('Timestamp'), planet.last_config_change))
      elif Form.getvalue('Pass','') == '':
         err("Please enter your password at the bottom of the page.")
      elif Form.getvalue('Pass') != orig_pass:
         err("Invalid password")
      else:
         planet.save(update_config_timestamp=True)

   ## Template
   from templates import Admin
   print "Content-type: text/html\n\n"
   a = Admin(template_vars(planet, Form)).render()
   sys.stdout.write(a)
Beispiel #12
0
    def __init__(self, kernel_legend, benchmarks, test_group,
                     site_benchmark_metrics, tko_server,
                     jobs_selector, no_antag):
        self.kernel_legend = kernel_legend
        self.benchmarks = benchmarks
        self.test_group = test_group
        self.tko_server = tko_server
        self.jobs_selector = jobs_selector
        self.no_antag = no_antag

        cgitb.enable()
        test, antagonists = self.parse_most_cgi_args()

        perf.init(tko_server=tko_server)
        for b in site_benchmark_metrics:
            perf.add_benchmark_main_metric(b, site_benchmark_metrics[b])

        self.test_runs = {}     # kernel --> (platform --> list of test runs)
        self.job_table = {}     # kernel id --> list of job idxs
        self.kernel_dates = {}  # kernel id --> date of nightly test

        vary = self.cgiform.getlist('vary')
        if vary:
            platform = self.platforms_filter[0]
            self.analyze_variants_all_tests_1_platform(platform, vary)
        elif test:
            self.analyze_1_test(test, antagonists)
        else:
            self.overview_page_all_tests(self.benchmarks, antagonists)
Beispiel #13
0
    def receive_message(self):
        import cgi
        import cgitb
        cgitb.enable()

        if 'CONTENT_LENGTH' in os.environ:
            # POST
            content_length = int(os.environ['CONTENT_LENGTH'])
            request_json = sys.stdin.read(content_length)
            request_json = urlparse.unquote(request_json)
        else:
            # GET
            fields = cgi.FieldStorage()
            jsonrpc = fields.getfirst("jsonrpc")
            id = fields.getfirst("id")
            method = fields.getfirst("method")
            params = fields.getfirst("params")
            # Create request string
            request_json = json.dumps({
                'jsonrpc': jsonrpc,
                'id': id,
                'method': method,
                'params': params
            })
        return None, request_json
Beispiel #14
0
def mainProcess(aProcessRequestProc):
    global processRequestProc
    processRequestProc = aProcessRequestProc
    import os
    if os.environ.has_key('SERVER_SOFTWARE'):
        import cgi
        import cgitb
        cgitb.enable()

        form = cgi.FieldStorage()
        if os.environ.has_key('PATH_INFO'):
	        pathInfo = os.environ['PATH_INFO']
        else:
	        pathInfo = ""
        if pathInfo[:1] == "/":
            pathInfo = pathInfo[1:]

        query = {}
        list = form.list
        for item in list:
            query[item.name] = unicode(item.value, "utf-8")

        response = _processRequestProc(pathInfo, query, HTTPResponse(False))
        if response.handled:
            print "Content-Type: " + response.mimeFormat + ";charset=utf-8"   # HTML is following
            print                                           # blank line, end of headers
            print response.htmlData.encode('utf-8')
        else:
            print "doProcessRequest Error"

    else:
        app = ServerApplication(urls, globals())
        app.run(port = 4567) #PORT_NUMBER)
Beispiel #15
0
def server_normal(environ, start_response):
    """ WSGIアプリケーションを開始します。

    WSGIアプリケーションではprintが使えないので、StringIOに出力する文字列を書きこんでいく.
    """
    #for debug.
    cgitb.enable()

    #IOを設定.
    io = StringIO.StringIO()

    #標準出力でunicodeを取り扱う.
    sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

    #output content type
    #start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')])

    #環境の初期化.
    environ['DOCUMENT_ROOT'] = path.abspath(path.dirname(__file__) + os.sep + '..' + os.sep + '..' + os.sep)
    app = application.CApplication(environ, start_response, io)
    app_config = config.MainConfig(app)
    controller = post_controller.CPostController(app)

    #WEBアプリケーションを開始する.
    app.run(app_config, controller)

    print environ['DOCUMENT_ROOT']

    #IOの先頭にシーク.(これをしないとIOに書き込んだ文字列が出力されない.)
    io.seek(0)

    return io
Beispiel #16
0
def main():
	cgitb.enable() #This will show any errors on your webpage

	
	pyFunctions.printBootstrapDocHeading("../../cosc2328/bootstrap.css", "Collegiate Classification")
	print("<div class = 'container'><div class='row page-header'><h1>Collegiate Classification</h1></div></div>")
	postRecieved = cgi.FieldStorage()
	if postRecieved:
		name = postRecieved.getfirst('name', '')
		hours = postRecieved.getfirst('hours', '')
		showClass = True
		error = ''
		if(len(name) == 0):
			error += "<h3>You must enter your name.</h3>"
			showClass = False
		if(len(hours) == 0):
			error += "<h3>You must enter a number of credit hours.</h3>"
			showClass = False
		if(showClass):
			generateClassification(name, int(hours))
		else:
			print("<div class='container'><div class='row'>" + error + "</div></div>")
			showForm(name, hours)
	else: 
		showForm('', '')
	pyFunctions.printBootstrapDocFooter()
Beispiel #17
0
def CGI_Main(morph_id):
    """main() when run as a CGI script.
    """
    ## shut off mmLib and tlsmd console output
    ConsoleOutput.disable()
    console.disable()
    
    ## enable CGI exception catching
    cgitb.enable()

    ## don't let an attacker be tricky
    assert morph_id.find("/") == -1 and morph_id.find("..") == -1 and len(morph_id) < 20
    morph = MorphLocations(morph_id)

    struct_filename, struct_path = morph.source_path()
    if os.path.exists(struct_path):
        pid = os.fork()
        if pid == 0:
            LaunchSubProcess(morph)
        else:
            CGIProcess(morph)
    else:
        CGIResponse(
            SimpleTemplateReplace(INVALIDID_HTML_TEMPLATE,
                                  morph_id = morph_id,
                                  struct_path = struct_path,
                                  stylesheet_url = STYLESHEET_URL))
def cgiHandler(environ, config='./tilestache.cfg', debug=False):
    """ Read environment PATH_INFO, load up configuration, talk to stdout by CGI.
    
        Calls requestHandler().
        
        Config parameter can be a file path string for a JSON configuration file
        or a configuration object with 'cache', 'layers', and 'dirpath' properties.
    """
    if debug:
        import cgitb
        cgitb.enable()
    
    path_info = environ.get('PATH_INFO', None)
    query_string = environ.get('QUERY_STRING', None)
    
    try:
        mimetype, content = requestHandler(config, path_info, query_string)
    
    except Core.TheTileIsInAnotherCastle, e:
        other_uri = environ['SCRIPT_NAME'] + e.path_info
        
        if query_string:
            other_uri += '?' + query_string

        print >> stdout, 'Status: 302 Found'
        print >> stdout, 'Location:', other_uri
        print >> stdout, 'Content-Type: text/plain\n'
        print >> stdout, 'You are being redirected to', other_uri
        return
Beispiel #19
0
def main():
    import cgitb
    cgitb.enable(format='text')
    logging.basicConfig(level=logging.DEBUG)
    import pickle

    frames = []
    def read(frame):
        print frame
        frames.append(frame)

    adapter = open(
        bitrate='500',
        # flags = FLAG_QUEUE_REPLACE | FLAG_TIMESTAMP | FLAG_BLOCK
        callback=read,
    )

    fname = 'pycanusb.%s.log' % time.strftime('%Y-%m-%d.%H.%M.%S')
    try:
        while 1:
            # msg = adapter.read()
            # frame = Frame(msg)
            # frames.append(frame)
            # print frame
            s = adapter.status()
            print 'Status:', adapter.statusText(s)
            time.sleep(1)
            pass

    except KeyboardInterrupt:
        print('Writing log %s' % fname)
        pickle.dump(frames, file(fname, 'wb'), -1)
Beispiel #20
0
def main():
    '''CGI entry point.'''

    config = ConfigParser.ConfigParser()
    config.read('/etc/edeploy.conf')

    def config_get(section, name, default):
        'Secured config getter.'
        try:
            return config.get(section, name)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            return default

    cfg_dir = os.path.normpath(config_get('SERVER', 'HEALTHDIR', os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'health'))) + '/'

    # parse hw file given in argument or passed to cgi script
    if len(sys.argv) == 3 and sys.argv[1] == '-f':
        hw_file = open(sys.argv[2])
    else:
        cgitb.enable()

        form = cgi.FieldStorage()

        if not 'file' in form:
            fatal_error('No file passed to the CGI')

        fileitem = form['file']
        hw_file = fileitem.file

    try:
        hw_items = eval(hw_file.read(-1))
    except Exception, excpt:
        fatal_error("'Invalid hardware file: %s'" % str(excpt))
Beispiel #21
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-u', '--url', metavar='URL',
                      help='Service URL (default: %s)' % DEFAULT_URL,
                      default=DEFAULT_URL)
    opts, args = parser.parse_args()

    url = urlparse.urlparse(opts.url)
    hostname = url.hostname
    port = url.port or 80

    server = BaseHTTPServer.HTTPServer
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    server_address = (hostname, port)
    service_dir = os.path.dirname(os.path.abspath(__file__))

    os.chdir(service_dir)
    handler.cgi_directories = ['/', '']

    print('JSON-RPC echo server')
    print('Serving %s to http://%s:%s' % (service_dir, hostname, port))
    print('API at %s' % (opts.url,))
    print('-------------------------------------------')

    signal.signal(signal.SIGINT, signal.SIG_DFL) ## Silence Ctrl-C
    cgitb.enable()  ## Enables CGI error reporting
    httpd = server(server_address, handler)
    httpd.serve_forever()
def main():

    cgitb.enable()
    form = cgi.FieldStorage()
    printHead()
    body()
    sys.stdout.flush()
Beispiel #23
0
def get():
    cgitb.enable()
    form = cgi.FieldStorage()

    print 'Content-type: text/html'
    print
    interleave(int(os.environ["PATH_INFO"][1:]))
Beispiel #24
0
def server_main():
    import cgitb
    cgitb.enable(format='text')
    cfg.CONF()
    srv = BankRPC()
    launcher = service.launch(cfg.CONF, srv)
    launcher.wait()
Beispiel #25
0
 def test(self):
     self.send_header("Content-type", "text/html")
     self.end_headers()
     
     cgitb.enable()
     form = cgi.FieldStorage()
     stuff = form.getfirst("stuff", "Unknown")
     name = form.getfirst("name", "Name")
     
     print "<html><head>\n"
     print "<title>Test script for %s</title>\n" % self.path
     print "</head><body>\n"
     print "<h2>Test script for for %s</h2>\n" % self.path
     print '''
     <form action="test" method="POST">
         <input type=text name="stuff" value="%s"><br>
         <input type=text name="name" value="%s"><br>
         <input type=submit name="done" value="OK">
     </form>
     <p>
     <a href="test?name=Joe">Click here to set name to Joe.</a><br>
     Contents:
     ''' % (stuff, name)
     print 'Stuff is %s<br>Name is %s\n' % (stuff, name)
         
     print "</body></html>\n"
Beispiel #26
0
def main():
    global option
    cgitb.enable()
    # get options that may have been passed to this script
    option = get_option()

    if option is None:
        option = max(dat)

    # print the HTTP header
    printHTTPheader()

    if len(option) != 0:
        # convert the data into a table
         table=check(option)
    else:
        print "No data found"
        return

    # start printing the page
    print "<html>"
    # print the head section including the table
    # used by the javascript for the chart
    printHTMLHead("RPi Temp-Logger", table, option)

    # print the page body
    print "<body>"
    print_time_selector(option)
    show_graph()
    show_log(option)
    copyright()
    print "</body>"
    print "</html>"
    sys.stdout.flush()
Beispiel #27
0
    def run(self):
        cgitb.enable()
        form = cgi.FieldStorage()

        dbinit()

        self.page = 'main'
        if form.has_key('page'):
            self.page = form['page'].value

        chars = self.__getattribute__(self.page)(form)

        contentsxml = ''
        for node in chars:
            if isinstance(chars[node], Entity):
                contentsxml += '    %s' % repr(chars[node])
            elif isinstance(chars[node], str):
                contentsxml += '    %s' % chars[node]
            elif chars[node] is None:
                contentsxml += '    <%s>None</%s>' % (node, node)
            else:
                contentsxml += '<%s>' % node
                contentsxml += ''.join([repr(item) for item in chars[node]])
                contentsxml += '</%s>' % node

        contents = file(self.page + '.xml').read()
        contents = contents.replace('__CONTENTS__', contentsxml)

        print 'Content-Type: text/xml\n'
        print contents
Beispiel #28
0
def start(port_number):
    '''Start server running at port_number.  If configuration file value
    FIRST_PAGE is an actual file then the server will automatically serve that
    page, otherwise, the server will sleep for a second and then serve the
    page assumed to be a CGI script.'''

    from http.server import HTTPServer, CGIHTTPRequestHandler
    import cgitb
    import subprocess
    import webbrowser

    create_read_me_file(port_number)

    ###########################################################################
    # Browse to FIRST_PAGE.  Unscalable past 1 due to likely port # collision.
    ###########################################################################

    if os.path.isfile(FIRST_PAGE):
        webbrowser.open('file://' + os.path.realpath(FIRST_PAGE))
    else:
        # Delayed browse of page served by this script
        webcommand = 'sleep 1 && python -m webbrowser "http://localhost:'
        webcommand += str(port_number) + '/' + FIRST_PAGE + '"'
        proc = subprocess.Popen(webcommand, shell=True)
        print('Delayed browse command pid =', str(proc.pid))

    cgi_handler = CGIHTTPRequestHandler
    cgi_handler.cgi_directories = ['/']

    cgitb.enable()

    # TODO: detect/prevent reuse of port_number in case of 2 dirsites...
    httpd = HTTPServer(("", port_number), cgi_handler)
    print("Serving at port", port_number)
    httpd.serve_forever()
Beispiel #29
0
def main():
    global dbfile

    #enable debugging
    cgitb.enable()

    succeeded = False
    dbfile = get_dbfile()
    timestamp = get_timestamp()
    if timestamp != None:
        deviceid = get_tdevice()
        if deviceid != None:
            temperature = get_temperature()
            if temperature != None:
                dbwrite(dbfile, timestamp, deviceid, temperature)
                succeeded = True
    # get the newest row to verify what was written, and so the poster can know what to post next
    timestamp, deviceid, temperature = get_newest_row()

    # print the HTTP header
    print u"Content-type: text/html\n\n"
    # print the page body
    print u"<body>"
    print u"<h1>tlogupdate data</h1>"
    info = u'dbfile="{0}", timestamp="{1}", deviceid="{2}", temperature="{3}"'.format(dbfile, timestamp, deviceid,
                                                                                      temperature)
    print info
    print u"</body>"
    print u"</html>"
    sys.stdout.flush()
Beispiel #30
0
 def __init__(self,debug = False):
     self.debug = debug
     self.img_outcome = '' #image str indicating success/failure
     if ( self.debug ):
         # debugging tips
         import cgitb
         cgitb.enable()
     
     self.form = cgi.FieldStorage()
     try:
         program = self.form.getvalue('prog')
     except Exception as e:
         print "could not load the program from GET method, exception "+str(e)
     finally:
         if ( not program ):
             program = "printf(\"You can write Tamil programs from your browser!\")"
     
     try:
         if ( os.environ.get("HTTP_USER_AGENT","").lower().find("chrome") >= 0 ):
             print "<B> code works only in Chrome </B>"
             program = chrome_url_fixup( program )
     except Exception as e:
         print "chrome url fixup routine failed"
         raise e
             
     if ( self.debug ):
         print(str(program))
 
     self.do_ezhil_execute( program )
Beispiel #31
0
#!/usr/bin/env python

import cgitb; cgitb.enable()

import cgi
import datetime
import itertools
import mwclient
import re
import sys
import urllib

DEFAULT_MAX_PAGES = 50
MAXIMUM_MAX_PAGES = 10000
TITLES_PER_REQUEST = 50
EN_WP = "en.wikipedia.org"
USER_AGENT = "RM Stats. Run by User:APerson. Using mwclient 0.8.1"

SIGNATURE_REGEX = r"(?:(?:\{\{unsigned.*?\}\})|(?:class=\"autosigned\")|(?:\[\[User.*?\]\].*?\(UTC\)))"
VOTE = re.compile(r"'''(.*?)'''.*?" + SIGNATURE_REGEX,
                   flags=re.IGNORECASE)
USERNAME = re.compile(r"\[\[User.*?:(.*?)(?:\||(?:\]\]))",
                  flags=re.IGNORECASE)
TIMESTAMP = re.compile(r"\d{2}:\d{2}, \d{1,2} [A-Za-z]* \d{4} \(UTC\)")
RESULT = re.compile("The\s+result\s+of\s+the\s+move\s+request\s+was(?:.*?)'''(.*?)'''.*?", flags=re.IGNORECASE)

NON_DISPLAYED_VOTES = ("note", "comment", "question")

def main():
    print_header()
    form = cgi.FieldStorage()
Beispiel #32
0
#!/usr/bin/python2
print "content-type: text/html"
print
"""This demonstrates a minimal http upload cgi.
This allows a user to upload up to three files at once.
It is trivial to change the number of files uploaded.

This script has security risks. A user could attempt to fill
a disk partition with endless uploads. 
If you have a system open to the public you would obviously want
to limit the size and number of files written to the disk.
"""
import cgi
import cgitb
cgitb.enable()
import os, sys

upload_dir = "/ff"
commands.getoutput("chmod -R 777 /ff ")

form = cgi.FieldStorage()
print form
print "<br>"
name = form["file_1"]
#print name.filename
name1 = name.filename
#print "<br>"
#print dir(name)
#name.make_file("/ff/",)

fout = file(os.path.join(upload_dir, name1), 'wb')
Beispiel #33
0
import BaseHTTPServer
import CGIHTTPServer
import cgitb
cgitb.enable()  ## This line enables CGI error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = ["/"]

httpd = server(server_address, handler)
httpd.serve_forever()
Beispiel #34
0
#!/usr/local/bin/python3

from os import environ
from shelve import DbfilenameShelf
from http.cookies import SimpleCookie

from cgitb import enable
enable()

print('Content-Type: text/html')
print()

script = ''
result = """<section>
       <strong>You are not logged in.</strong>
       <p>Please log in or create an account to play.</p>
       <p>
           <a href="login.py">Login</a> &vert; <a href="accounts/register.py">Register</a>
       </p>
   </section>
   <section>
        <p>
            You can play the first level without an account as a guest.
        </p>
        <p>
            Your scores will not get added to the leaderboard.
        </p>
        <p>
            <a href="guest.html">Play as a Guest!</a>
        </p>
   </section>"""
#You may also wish to expand upon this script to have it
#write out your entire Google maps Javascript.  That's what
#I did and it's what I recommend to you.  Of course, you can
#always just type in the storm reports by hand if have
#nothing better to do with your time...
#
#Please see the comments throughout this script.
#
#Christopher M. Godfrey						   12 July 2010
#Modified 5 May 2011
###########################################################
#Import a bunch of stuff that you may or may not need
import sys,urllib2,os,cgi,time,glob,math,string,re
import datetime
#If you decide to make this script interact with a Web browser, uncomment the next lines
import cgitb; cgitb.enable()		#Gives nicely-formatted error messages
print "Content-type: text/html\n"  #Required first line to send to client for debugging
#This is the file that you want to read:
reports='110427_rpts.csv'
###########################################################
#YOUR TURN (1 of 3):
#It's possible to have this script write out your entire Javascript code!
#Then you can include that script as an external file by placing the
#following in your HTML <head> section, along with any other HTML in
#that section:
#<head>
#  <script type="text/javascript" src="your_javascript.js"></script>
#</head>
#Open your external Javascript file for writing
java=open("myjavascript.js","w")
#Write the first part of your Javascript here.  Enclose
def server_main():
    import cgitb
    cgitb.enable(format='text')

    main()
using the business layer API.

Author: Diego Chillon Pino
"""

#------------------------------------------------------------------------------

# Add the bl sub-directory to the module path
# and the directory above to import the config file
import sys
sys.path.insert(0, "../bl/")
sys.path.insert(0, "../")

import cgi
import cgitb
cgitb.enable()
cgitb.enable(display=0, logdir="/path/to/logdir")
form = cgi.FieldStorage()
# radio = form.getvalue("radio")
# query = form.getvalue("query")

import html_utils
from blapi import *
from config import *

#------------------------------------------------------------------------------

print("Content-Type: text/html\n")

html = html_utils.header()
Beispiel #38
0
#!/web/s0092179/public_html/cgi-bin/cinemap/bin/python

import cgitb
import cx_Oracle

cgitb.enable(format='text')
import cgi
from jinja2 import Environment, FileSystemLoader
import folium
from folium import plugins
import os
import json
from branca.colormap import linear
import branca.colormap as cm
import random
from datetime import time

# Customised modules and functions
import parking as park
import restaurants as rest
import shops
import facilities as fac
import buses
import films
import districts as hoods

form = cgi.FieldStorage()
edinburgh_coords = [55.937495, -3.220226]

polycolours = linear.GnBu_06.scale(0, 120)
polycolours.caption = 'Areas of Edinburgh'
Beispiel #39
0
                                 '').replace('\r',
                                             '').replace('\t',
                                                         '').encode('utf8'),
                "minutes":
                row.find("td", class_="inMinColumn").get_text()
            }
            server_stops.append(stop)

    data["stops"] = server_stops
    data["station"] = server_station
    data["time"] = server_time
    return data


def main():
    print "Content-Type: application/json;charset=utf-8"
    print "Access-Control-Allow-Origin: *"
    print

    form = cgi.FieldStorage()
    station = form.getvalue("station", default="Petuelring")
    station = station.decode("utf-8").encode("windows-1252")

    data = get_stop(station)
    print json.dumps(data)


# enable debugging
cgitb.enable(display=0, logdir="logs")
main()
Beispiel #40
0
    for x in varNames:
        if x not in form:
            print('Content-Type: text/html')
            print()
            print('You missed a setting: {}'.format(x))
            return
    if '@' not in form['.edu Address'].value or '.edu' != form['.edu Address'].value[-4:]:
        print('Content-Type: text/html')
        print()
        print('Invalid email')
        return
    stud = Student.Student(form['.edu Address'].value.split('@')[0], form['Password'].value, form['FirstName'].value+' '+form['LastName'].value, int(form['ProblemSolver'].value), int(form['Focus'].value), int(form['Social'].value), int(form['Noise'].value))
    print('Set-Cookie:unityId = {}'.format(stud.unity_id))
    print('Set-Cookie:password = {}'.format(stud.password))
    print('Set-Cookie:prob = {}'.format(stud.avg_problemSolver))
    print('Set-Cookie:noise = {}'.format(stud.avg_noise))
    print('Set-Cookie:foc = {}'.format(stud.avg_focus))
    print('Set-Cookie:soc = {}'.format(stud.avg_social))
    print('Set-Cookie:name = {}'.format(stud.name))
    print("Content-Type: text/html")
    print()
    print('<!DOCTYPE html>')
    print('<html><head>')
    print('<meta http-equiv="Refresh" content="0; url=/study.html">')
    print('</head></html>')
    return

cgitb.enable(display=0, logdir="/home/jacob/Code/HackNC2018/logs/")

main()
Beispiel #41
0
                        continue
                    path = QPainterPath()
                    path.moveTo(p.x, p.y)
                    path.lineTo(pc.x, pc.y)
                    painter.save()
                    painter.setPen(p.lineColor)
                    painter.drawPath(path)
                    painter.restore()

            # 画圆
            painter.save()
            painter.setPen(Qt.NoPen)
            painter.setBrush(p.circleColor)
            painter.drawRoundedRect(QRectF(
                p.x - p.radius, p.y - p.radius, 2 * p.radius, 2 * p.radius), p.radius, p.radius)
            painter.restore()

            # 开启动画
            p.initAnimation()


if __name__ == '__main__':
    import sys
    import cgitb
    sys.excepthook = cgitb.enable(1, None, 5, '')
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())
Beispiel #42
0
#! /usr/bin/env python3
import cgitb, cgi
from libs import tags
from controllers.models.user import User

cgitb.enable(display=0, logdir="./")

DISPLAY_FLEX_CENTER = "display: flex;align-items: center;justify-content: center;flex-direction: column;"

tags.enc_print(
    tags.init_html(inside=tags.head(
        inside="<meta http-equiv='X-UA-Compatible' content='IE=edge'>" +
        "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>"
        +
        "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
        + "<!-- HTML 4 -->" +
        "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" +
        "<!-- HTML5 -->" + "<meta charset='UTF-8'/>" + """
      <style>
        table, td, th {
          border: 1px solid black;
        }

        table {
          width: 100%;
          border-collapse: collapse;
        }
      </style>
      """,
        title="Index") + tags.body(
            inside=tags.button(inside="Apagar todos os registros",
import datetime
import json
import requests
import sys
import io
import os
import cgi
import cgitb
cgitb.enable(display=1)


def main01():
    # おまじない
    print('Content-type: application/json; charset=UTF-8')
    print("\r\n\r\n")

    with open("log.txt", encoding="utf-8", mode="w") as f:
        f.write(str(datetime.datetime.now()) + ":START\n")

        # POSTデータの判定
        if (os.environ['REQUEST_METHOD'] != "POST"):
            f.write(str(datetime.datetime.now()) + ":METHOD不正\n")
        else:
            f.write(str(datetime.datetime.now()) + ":METHOD=POST\n")

        # データ取得
        form = cgi.FieldStorage()

        f.write(str(datetime.datetime.now()) + ":DATA取得\n")
        f.write(str(form) + "\n")
Beispiel #44
0
#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 5
# This program requires Python 2.7 or any later version

import os
import cgi
import argparse
import BaseHTTPServer
import CGIHTTPServer
import cgitb
cgitb.enable()  ## enable CGI error reporting


def web_server(port):
    server = BaseHTTPServer.HTTPServer
    handler = CGIHTTPServer.CGIHTTPRequestHandler  #RequestsHandler
    server_address = ("", port)
    handler.cgi_directories = [
        "/cgi-bin",
    ]
    httpd = server(server_address, handler)
    print "Starting web server with CGI support on port: %s ..." % port
    httpd.serve_forever()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='CGI Server Example')
    parser.add_argument('--port',
                        action="store",
                        dest="port",
                        type=int,
Beispiel #45
0
#! C:\Python38-32\python.exe -u

# Use this page as an example of how to create the Account page

import cgi, cgitb

cgitb.enable()  # used for debugging

# Ensures that the code that is printed is treated as HTML code
print(
    "Content-Type: text/html\n"  # should have a blank line after the Content-Type is printed
)

print("<!DOCTYPE html>")
print('<html lang="en">')
print("  <head>")
print("    <title>Example Python HTML Page</title>")
print("  </head>")
print("  <body>")
print("    <h1>Heading</h1>")
print("    <p>Text</p>")
print("  </body>")
print("</html>")
Beispiel #46
0
    db.commit()  # saves changes


def update_salt(salt, accid):
    """
    Updates the salt value that is used to encrypt data using the prepare statement
    """
    # Prepare UPDATE statement
    prep_update = "UPDATE salt SET salt = %s WHERE accId = %s"

    cursor.execute(prep_update, (str(salt), accid))

    db.commit()  # saves changes


cgitb.enable()  # for debugging

# Connects to the database
db = connect_db()

cursor = db.cursor(prepared=True)  # allows the prepare statement to be used

errctr = 0  # keeps track of all the errors that were found

# Intializes an empty list of error messages
errmsgs = []

form = cgi.FieldStorage()

# Name Validation
if "fname" in form:
#
# Author: Ken B
#
# Note : The three values that follow can be anything, but an empty password is not allowed.
#        Since this is web facing, please use adequate user/pass complexity and reuse principles 

listenport = 28080
username = "******"
password = ""

if not password:
    print("Empty password is not allowed!")
    exit(1)

import CGIHTTPServer_root
import cgitb; cgitb.enable()  ## This line enables CGI error reporting
import os, sys

def excepthook(etype,ex,tb):
    sys.stdout.flush()

sys.excepthook = excepthook
 
server = CGIHTTPServer_root.HTTPServer
handler = CGIHTTPServer_root.CGIHTTPRequestHandler
server_address = ("", listenport)
lspitools = os.getenv("SYNCHRONIZED_LIGHTS_HOME") + "/web/microweb"
os.chdir(lspitools)
handler.cgi_directories = ["/cgi-bin"]
handler.user = username
handler.password = password
Beispiel #48
0
def structure_main(user, admin, mode, **kwargs):

	scriptpath = os.path.dirname(os.path.realpath(__file__)) + os.sep
	userdir = scriptpath + "users" + os.sep
	theform = kwargs

	cgitb.enable()

	###GRAPHICAL PARAMETERS###
	top_spacing = 20
	layer_spacing = 60

	config = ConfigObj(userdir + 'config.ini')
	templatedir = scriptpath + config['controltemplates'].replace("/",os.sep)

	template = "main_header.html"
	header = readfile(templatedir+template)
	header = header.replace("**page_title**","Structure editor")
	header = header.replace("**user**",user)

	cpout = ""
	if mode == "server":
		cpout += "Content-Type: text/html\n\n\n"
		header = header.replace("**logout_control**",'(<a href="logout.py">log out</a>)')
	else:
		header = header.replace("**logout_control**",'')
	cpout += header

	if "current_doc" in theform:
		current_doc = theform["current_doc"]
		current_project = theform["current_project"]
		current_guidelines = get_guidelines_url(current_project)
	else:
		current_doc = ""
		current_project = ""
		current_guidelines = ""

	UTF8Writer = codecs.getwriter('utf8')
	sys.stdout = UTF8Writer(sys.stdout)


	edit_bar = "edit_bar.html"
	edit_bar = readfile(templatedir+edit_bar)
	edit_bar = edit_bar.replace("**doc**",current_doc)
	edit_bar = edit_bar.replace("**project**",current_project)
	edit_bar = edit_bar.replace("**structure_disabled**",'disabled="disabled"')
	edit_bar = edit_bar.replace("**segment_disabled**",'')
	edit_bar = edit_bar.replace("**relations_disabled**",'')
	edit_bar = edit_bar.replace("**screenshot_disabled**",'')
	edit_bar = edit_bar.replace("**quickexp_disabled**",'')
	edit_bar = edit_bar.replace("**current_guidelines**",current_guidelines)
	if mode == "server":
		edit_bar = edit_bar.replace("**submit_target**",'structure.py')
	else:
		edit_bar = edit_bar.replace("**submit_target**",'structure')
	edit_bar = edit_bar.replace("**action_type**",'action')
	edit_bar = edit_bar.replace("**serve_mode**",mode)
	edit_bar = edit_bar.replace("**open_disabled**",'')
	edit_bar = edit_bar.replace('id="nav_edit" class="nav_button"','id="nav_edit" class="nav_button nav_button_inset"')

	if admin == "3":
		edit_bar = edit_bar.replace("**admin_disabled**",'')
	else:
		edit_bar = edit_bar.replace("**admin_disabled**",'disabled="disabled"')

	cpout += edit_bar

	help = "help.html"
	help = readfile(templatedir+help)
	help_match = re.search(r'(<div id="help_edit".*?</div>)',help,re.MULTILINE|re.DOTALL)
	help = help_match.group(1)
	if sys.version_info[0] == 2:
		cpout += help.decode("utf-8")
	else:
		cpout += help

	about = "about.html"
	about = readfile(templatedir+about)
	about = about.replace("**version**", _version.__version__)
	cpout += about

	if current_guidelines != "":
		cpout += '<script>enable_guidelines();</script>'

	if current_doc =="":
		cpout += '<p class="warn">No file found - please select a file to open</p>'
		return cpout

	cpout += '''
          <div id="container" class="container">
            <button id="show-all-signals">
              Show All Signal Tokens
            </button>
            <div class="signal-drawer">
              <div id="signal-list"> </div>

			  <div class="signal-drawer__row">
			    <button id="new-signal" class="signal-drawer__create-new-button">
  			      <i class="fa fa-plus" title="New Signal"> </i>
			      New Signal
			    </button>
			  </div>
			  <div class="signal-drawer__row" style="text-align: center;padding-top:20px;">
  		        <button id="save-signals" class="signal-drawer__save-button">
  		          <i class="fa fa-check"> </i>
  		          Save Changes
  		        </button>
  		        <button id="cancel-signals" class="signal-drawer__cancel-button">
  		          <i class="fa fa-ban"> </i>
  		          Cancel
  		        </button>
  		      </div>
            </div>
    '''

	cpout += '''<div id="canvas" class="canvas">'''
	cpout += '\t<p id="document_name">Document: <b>'+current_doc+'</b> (project: <i>'+current_project+'</i>)</p>'
	cpout += '''<div id="inner_canvas">'''
	cpout += '<script src="/script/structure.js"></script>'

	# Remove floating non-terminal nodes if found
	# (e.g. due to browsing back and re-submitting old actions or other data corruption)
	clean_floating_nodes(current_doc, current_project, user)

	rels = get_rst_rels(current_doc, current_project)
	def_multirel = get_def_rel("multinuc",current_doc, current_project)
	def_rstrel = get_def_rel("rst",current_doc, current_project)
	multi_options =""
	rst_options =""
	rel_kinds = {}
	for rel in rels:
		if rel[1]=="multinuc":
			multi_options += "<option value='"+rel[0]+"'>"+rel[0].replace("_m","")+'</option>\n'
			rel_kinds[rel[0]] = "multinuc"
		else:
			rst_options += "<option value='"+rel[0]+"'>"+rel[0].replace("_r","")+'</option>\n'
			rel_kinds[rel[0]] = "rst"
	multi_options += "<option value='"+def_rstrel+"'>(satellite...)</option>\n"

	timestamp = ""
	if "timestamp" in theform:
		if len(theform["timestamp"]) > 1:
			timestamp = theform["timestamp"]

	refresh = check_refresh(user, timestamp)

	if "action" in theform and not refresh:
		if len(theform["action"]) > 1:
			action_log = theform["action"]
			if len(action_log) > 0:
				actions = action_log.split(";")
				set_timestamp(user,timestamp)
				for action in actions:
					action_type = action.split(":")[0]
					action_params = action.split(":")[1] if len(action.split(":")) > 1 else ""
					params = action_params.split(",")
					if action_type == "up":
						update_parent(params[0],params[1],current_doc,current_project,user)
					elif action_type == "sp":
						insert_parent(params[0],"span","span",current_doc,current_project,user)
					elif action_type == "mn":
						insert_parent(params[0],def_multirel,"multinuc",current_doc,current_project,user)
					elif action_type == "rl":
						update_rel(params[0],params[1],current_doc,current_project,user)
					elif action_type == "sg":
						update_signals(action.split(":")[1:], current_doc, current_project, user)
					else:
						cpout += '<script>alert("the action was: " + theform["action"]);</script>\n'

	if "logging" in theform and not refresh:
		if len(theform["logging"]) > 1:
			if get_setting("logging") == "on":
				logging = theform["logging"]
				if len(logging) > 0:
					update_log(current_doc,current_project,user,logging,"structure",str(datetime.datetime.now()))

	if "reset" in theform or user == "demo":
		if len(theform["reset"]) > 1 or user == "demo":
			reset_rst_doc(current_doc,current_project,user)

	nodes={}
	rows = get_rst_doc(current_doc,current_project,user)
	for row in rows:
		if row[7] in rel_kinds:
			relkind = rel_kinds[row[7]]
		else:
			relkind = "span"
		if row[5] == "edu":
			nodes[row[0]] = NODE(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],relkind)
		else:
			nodes[row[0]] = NODE(row[0],0,0,row[3],row[4],row[5],row[6],row[7],relkind)

	for key in nodes:
		node = nodes[key]
		get_depth(node,node,nodes)

	for key in nodes:
		if nodes[key].kind == "edu":
			get_left_right(key, nodes,0,0,rel_kinds)

	signals = {}
	for signal in get_signals(current_doc, current_project, user):
		s_id, s_type, subtype, tokens = signal
		if s_id not in signals:
			signals[s_id] = list()
		if tokens:
			tokens = list(map(int, tokens.split(",")))
		else:
			tokens = []
		signals[s_id].append({'type': s_type,
							  'subtype': subtype,
							  'tokens': tokens})
	cpout += '<script>'
	cpout += 'window.rstWebSignals = ' + json.dumps(signals) + ';'
	cpout += 'window.rstWebSignalTypes = ' + json.dumps(get_signal_types_dict(current_doc, current_project), sort_keys=True) + ';'
	cpout += 'window.rstWebDefaultSignalType = Object.keys(window.rstWebSignalTypes)[0];'
	cpout += 'window.rstWebDefaultSignalSubtype = window.rstWebSignalTypes[window.rstWebDefaultSignalType][0];'
	cpout += '</script>'

	anchors = {}
	pix_anchors = {}

	# Calculate anchor points for nodes
	# First get proportional position for anchor
	for key in sorted(nodes, key = lambda id: nodes[id].depth, reverse=True):
		node = nodes[key]
		if node.kind=="edu":
			anchors[node.id]= "0.5"
		if node.parent!="0":
			parent = nodes[node.parent]
			parent_wid = (parent.right- parent.left+1) * 100 - 4
			child_wid = (node.right- node.left+1) * 100 - 4
			if node.relname == "span":
				if node.id in anchors:
					anchors[parent.id] = str(((node.left - parent.left)*100)/parent_wid+float(anchors[node.id])*float(child_wid/parent_wid))
				else:
					anchors[parent.id] = str(((node.left - parent.left)*100)/parent_wid+(0.5*child_wid)/parent_wid)
			elif node.relkind=="multinuc" and parent.kind =="multinuc":
				# For multinucs, the anchor is in the middle between leftmost and rightmost of the multinuc children
				# (not including other rst children)
				lr = get_multinuc_children_lr(node.parent,current_doc,current_project,user)
				lr_wid = (lr[0] + lr[1]) /2
				lr_ids = get_multinuc_children_lr_ids(node.parent,lr[0],lr[1],current_doc,current_project,user)
				left_child = lr_ids[0]
				right_child = lr_ids[1]
				if left_child == right_child:
					anchors[parent.id] = "0.5"
				else:
					if left_child in anchors and right_child in anchors: #both leftmost and rightmost multinuc children have been found
						len_left = nodes[left_child].right-nodes[left_child].left+1
						len_right = nodes[right_child].right-nodes[right_child].left+1
						anchors[parent.id] = str(((float(anchors[left_child]) * len_left*100 + float(anchors[right_child]) * len_right * 100 + (nodes[right_child].left - parent.left) * 100)/2)/parent_wid)
					else:
						anchors[parent.id] = str((lr_wid - parent.left+1) / (parent.right - parent.left+1))

			else:
				if not parent.id in anchors:
					anchors[parent.id] = "0.5"

	# Place anchor element to center on proportional position relative to parent
	for key in nodes:
		node = nodes[key]
		pix_anchors[node.id] = str(int(3+node.left * 100 -100 - 39 + float(anchors[node.id])*((node.right- node.left+1) * 100 - 4)))

	# Check that span and multinuc buttons should be used (if the interface is not used for RST, they may be disabled)
	if int(get_schema()) > 2:
		use_span_buttons = True if get_setting("use_span_buttons") == "True" else False
		use_multinuc_buttons = True if get_setting("use_multinuc_buttons") == "True" else False
	else:
		use_span_buttons = True
		use_multinuc_buttons = True

	if sys.version_info[0] == 2:
		lambda_button = "Λ".decode("utf-8")
	else:
		lambda_button = "Λ"

	tok_count = 0
	for key in sorted(nodes.keys(), key=int):
		node = nodes[key]
		if node.kind != "edu":
			g_wid = str(int((node.right- node.left+1) *100 -4 ))
			cpout += '<div id="lg'+ node.id +'" class="group" style="left: ' +str(int(node.left*100 - 100))+ '; width: ' + g_wid + '; top:'+ str(int(top_spacing + layer_spacing+node.depth*layer_spacing)) +'px; z-index:1"><div id="wsk'+node.id+'" class="whisker" style="width:'+g_wid+';"></div></div>'
			cpout += '<div id="g'+ node.id +'" class="num_cont" style="position: absolute; left:' + pix_anchors[node.id] +'px; top:'+ str(int(4+ top_spacing + layer_spacing+node.depth*layer_spacing))+'px; z-index:'+str(int(200-(node.right-node.left)))+'"><table class="btn_tb"><tr><td rowspan="2"><button id="unlink_'+ node.id+'"  title="unlink this node" class="minibtn" onclick="act('+"'up:"+node.id+",0'"+');">X</button></td><td rowspan="2"><span class="num_id">'+str(int(node.left))+"-"+str(int(node.right))+'</span></td>'
			if use_span_buttons:
				cpout += '<td><button id="aspan_'+ node.id+'" title="add span above" class="minibtn" onclick="act('+"'sp:"+node.id+"'"+');">T</button></td>'
			cpout += '</tr>'
			if use_multinuc_buttons:
				cpout += '<tr><td><button id="amulti_'+ node.id+'" title="add multinuc above" class="minibtn" onclick="act('+"'mn:"+node.id+"'"+');">' + lambda_button + '</button></td></tr>'
			cpout += '</table></div><br/>'

		elif node.kind=="edu":
			cpout += '<div id="edu'+str(node.id)+'" class="edu" title="'+str(node.id)+'" style="left:'+str(int(node.id)*100 - 100) +'; top:'+str(int(top_spacing +layer_spacing+node.depth*layer_spacing))+'; width: 96px">'
			cpout += '<div id="wsk'+node.id+'" class="whisker" style="width:96px;"></div><div class="edu_num_cont"><table class="btn_tb"><tr><td rowspan="2"><button id="unlink_'+ node.id+'" title="unlink this node" class="minibtn" onclick="act('+"'up:"+node.id+",0'"+');">X</button></td><td rowspan="2"><span class="num_id">&nbsp;'+str(int(node.left))+'&nbsp;</span></td>'
			if use_span_buttons:
				cpout += '<td><button id="aspan_'+ node.id+'" title="add span above" class="minibtn" onclick="act('+"'sp:"+node.id+"'"+');">T</button></td>'
			cpout += '</tr>'
			if use_multinuc_buttons:
				cpout += '<tr><td><button id="amulti_'+ node.id+'" title="add multinuc above" class="minibtn" onclick="act('+"'mn:"+node.id+"'"+');">' + lambda_button + '</button></td></tr>'
			cpout += '</table></div>'

			for tok in node.text.split(" "):
				tok_count += 1
				cpout += '<span id="tok' + str(tok_count) + '" class="tok">' + tok + '</span> '

			cpout += '</div>'


	max_right = get_max_right(current_doc,current_project,user)

	# Serialize data in hidden input for JavaScript
	cpout += '<input id="data" name="data" type="hidden" '
	hidden_val=""
	for key in nodes:
		node = nodes[key]
		if node.relname:
			safe_relname = node.relname
		else:
			safe_relname = "none"
		if node.kind =="edu":
			hidden_val += "n" + node.id +",n" +node.parent+",e,"+ str(int(node.left)) + "," + safe_relname + "," + get_rel_type(node.relname,current_doc,current_project) + ";"
		elif node.kind =="span":
			hidden_val += "n" + node.id +",n" +node.parent+",s,0," + safe_relname + "," + get_rel_type(node.relname,current_doc,current_project) + ";"
		else:
			hidden_val += "n"+node.id +",n" +node.parent+",m,0," + safe_relname + "," + get_rel_type(node.relname,current_doc,current_project) + ";"
	hidden_val = hidden_val[0:len(hidden_val)-1]
	cpout += 'value="' + hidden_val + '"/>'


	cpout += '<input id="def_multi_rel" type="hidden" value="' + get_def_rel("multinuc",current_doc,current_project) +'"/>\n'
	cpout += '<input id="def_rst_rel" type="hidden" value="' + get_def_rel("rst",current_doc,current_project) +'"/>\n'
	cpout += '<input id="undo_log" type="hidden" value=""/>\n'
	cpout += '<input id="redo_log" type="hidden" value=""/>\n'
	cpout += '<input id="undo_state" type="hidden" value=""/>\n'
	cpout += '<input id="logging" type="hidden" value=""/>\n'
	cpout += '<input id="validations" type="hidden" value="'+get_project_validations(current_project)+'"/>\n'
	cpout += '<input id="use_span_buttons" type="hidden" value="'+str(use_span_buttons)+'"/>\n'
	cpout += '<input id="use_multinuc_buttons" type="hidden" value="'+str(use_multinuc_buttons)+'"/>\n'

	cpout += '''	<script src="/script/jquery.jsPlumb-1.7.5-min.js"></script>

			<script>
			'''

	cpout += 'function select_my_rel(options,my_rel){'
	cpout += 'var multi_options = `' + multi_options +'`;\n'
	cpout += 'var rst_options = `' + rst_options +'`;\n'
	cpout += 'if (options =="multi"){options = multi_options;} else {options=rst_options;}'
	cpout += '		return options.replace("<option value='+"'" +'"' + '+my_rel+'+'"' +"'"+'","<option selected='+"'"+'selected'+"'"+' value='+"'" +'"'+ '+my_rel+'+'"' +"'"+'");'
	cpout += '			}\n'
	cpout += '''function make_relchooser(id,option_type,rel){
	    var s = "<div id='seldiv"+id.replace("n","")+"' style='white-space:nowrap;'>";
	    s += make_signal_button(id);
	    s += "<select id='sel"+id.replace("n","")+"' class='rst_rel' onchange='crel(" + id.replace("n","") + ",this.options[this.selectedIndex].value);'>" + select_my_rel(option_type,rel) + "</select>";
	    return $(s);
	}'''
	# todo: make a flag that controls whether signals are on
	cpout += 'var signalsEnabled = ' + ('true;' if get_setting("signals") == "True" else 'false;')
	cpout += '''function make_signal_button(id) {
		if (signalsEnabled) {
			var text = window.rstWebSignals[id]
					? window.rstWebSignals[id].length
					: "S";
			var classes = window.rstWebSignals[id] && window.rstWebSignals[id].length > 0
					? "minibtn minibtn--with-signals"
					: "minibtn";
			return '<button title="add signals" class="' + classes + '" onclick="open_signal_drawer(\\'' + id.replace('n','') + '\\')">' + text + '</button>';
		} else {
			return '';
		}
	}'''
	cpout += '''
			jsPlumb.importDefaults({
			PaintStyle : {
				lineWidth:2,
				strokeStyle: 'rgba(0,0,0,0.5)'
			},
			Endpoints : [ [ "Dot", { radius:1 } ], [ "Dot", { radius:1 } ] ],
			  EndpointStyles : [{ fillStyle:"#000000" }, { fillStyle:"#000000" }],
			  Anchor:"Top",
	            Connector : [ "Bezier", { curviness:50 } ]
			})
			 jsPlumb.ready(function() {

	jsPlumb.setContainer(document.getElementById("inner_canvas"));
	'''

	cpout += "jsPlumb.setSuspendDrawing(true);"


	for key in nodes:
		node = nodes[key]
		if node.kind == "edu":
			node_id_str = "edu" + node.id
		else:
			node_id_str = "g" + node.id
		cpout += 'jsPlumb.makeSource("'+node_id_str+'", {anchor: "Top", filter: ".num_id", allowLoopback:false});'
		cpout += 'jsPlumb.makeTarget("'+node_id_str+'", {anchor: "Top", filter: ".num_id", allowLoopback:false});'


	# Connect nodes
	for key in nodes:
		node = nodes[key]
		if node.parent!="0":
			parent = nodes[node.parent]
			if node.kind == "edu":
				node_id_str = "edu" + node.id
			else:
				node_id_str = "g" + node.id
			if parent.kind == "edu":
				parent_id_str = "edu" + parent.id
			else:
				parent_id_str = "g" + parent.id

			if node.relname == "span":
				cpout += 'jsPlumb.connect({source:"'+node_id_str+'",target:"'+parent_id_str+ '", connector:"Straight", anchors: ["Top","Bottom"]});'
			elif parent.kind == "multinuc" and node.relkind=="multinuc":
				cpout += 'jsPlumb.connect({source:"'+node_id_str+'",target:"'+parent_id_str+ '", connector:"Straight", anchors: ["Top","Bottom"], overlays: [ ["Custom", {create:function(component) {return make_relchooser("'+node.id+'","multi","'+node.relname+'");},location:0.2,id:"customOverlay"}]]});'
			else:
				cpout += 'jsPlumb.connect({source:"'+node_id_str+'",target:"'+parent_id_str+'", overlays: [ ["Arrow" , { width:12, length:12, location:0.95 }],["Custom", {create:function(component) {return make_relchooser("'+node.id+'","rst","'+node.relname+'");},location:0.1,id:"customOverlay"}]]});'

	cpout += '''

		jsPlumb.setSuspendDrawing(false,true);


		jsPlumb.bind("connection", function(info) {
		   source = info.sourceId.replace(/edu|g/,"")
		   target = info.targetId.replace(/edu|g/g,"")
		});

		jsPlumb.bind("beforeDrop", function(info) {
		    $(".minibtn").prop("disabled",true);

	'''

	cpout += '''
			var node_id = "n"+info.sourceId.replace(/edu|g|lg/,"");
			var new_parent_id = "n"+info.targetId.replace(/edu|g|lg/,"");

			nodes = parse_data();
			new_parent = nodes[new_parent_id];
			relname = nodes[node_id].relname;
			new_parent_kind = new_parent.kind;
			if (nodes[node_id].parent != "n0"){
				old_parent_kind = nodes[nodes[node_id].parent].kind;
			}
			else
			{
				old_parent_kind ="none";
			}

			if (info.sourceId != info.targetId){
				if (!(is_ancestor(new_parent_id,node_id))){
					jsPlumb.select({source:info.sourceId}).detach();
					if (new_parent_kind == "multinuc"){
						relname = get_multirel(new_parent_id,node_id,nodes);
						jsPlumb.connect({source:info.sourceId, target:info.targetId, connector:"Straight", anchors: ["Top","Bottom"], overlays: [ ["Custom", {create:function(component) {return make_relchooser(node_id,"multi",relname);},location:0.2,id:"customOverlay"}]]});
					}
					else{
						jsPlumb.connect({source:info.sourceId, target:info.targetId, overlays: [ ["Arrow" , { width:12, length:12, location:0.95 }],["Custom", {create:function(component) {return make_relchooser(node_id,"rst",relname);},location:0.1,id:"customOverlay"}]]});
					}
					new_rel = document.getElementById("sel"+ node_id.replace("n","")).value;
				    act('up:' + node_id.replace("n","") + ',' + new_parent_id.replace("n",""));
					update_rel(node_id,new_rel,nodes);
					recalculate_depth(parse_data());
				}
			}

		    $(".minibtn").prop("disabled",false);

		});

	});
		nodes = parse_data();
		show_warnings(nodes);

			</script>

'''

	cpout += '''
			</div>
			</div>
			</div>
			<div id="anim_catch" class="anim_catch">&nbsp;</div>
	</body>
	</html>

	'''
	if mode != "server":
		cpout = cpout.replace(".py","")
	return cpout
Beispiel #49
0
#!/usr/bin/python
import cgitb  ##REMOVE
cgitb.enable()  ##REMOVE
import cgi
import urllib2
import MySQLdb
import re
from datetime import datetime
import bs4
from bs4 import BeautifulSoup

print "Content-type: text/html;  charset=iso-8859-1\n\n"

try:
    conn = MySQLdb.connect(host="mysql.aaron.magil.org",
                           user="******",
                           passwd="workoutbuddy",
                           db="workoutbuddy")
except MySQLdb.Error, e:
    print "<p>Error %d: %s</p>" % (e.args[0], e.args[1])
    sys.exit(1)
cursor = conn.cursor()

##TODO: set it so that I get check boxes of the exercises.
##      Can commit only the ones I want
url = "http://www.crossfit.com/pdawod.html"
r = urllib2.urlopen(url)
t = r.read()
soup = BeautifulSoup(t)

num_name_dict = {
Beispiel #50
0
def server_main():
    cgitb.enable(format='text')
    main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cgi
import cgitb

cgitb.enable()  # デバッグモード

form = cgi.FieldStorage()
price = 300
num = int(form.getvalue('n', 0))

# ヘッダ文字列の作成
header = "Content-type: text/html\n"

# HTML文字列の作成
html = """
<meta charset="shift-jis">
<h1>カート</h1>
<p>りんご {price}円: {num}個</p>
<p>合計: {sum_price}円</p>
<p>Thank you!</p>
""".format(price=price, num=num, sum_price=num * price)
print(header + html)
Beispiel #52
0
import pyttsx3
import win32com.client
# from aip import AipSpeech  # 百度文本转语音
# from apscheduler.schedulers.blocking import BlockingScheduler
# import schedule  # 轻量级定时任务调度库
# import sched  # 定时
# import time
# from datetime import datetime
# import multiprocessing  # 进程
import threading  # 线程

from utilities import Utils, AnimWin, MyJson
from test3 import Curtain
import cgitb

cgitb.enable(format='text')  # 解决 pyqt5异常只要进入事件循环,程序就崩溃,而没有任何提示

data1 = [
    '每个动作10-15次,循环2-3组。训练过程每个动作尽量慢一点,动作都做到位,体会每个肌群的发力。',  # 每组循环提醒
]
data2 = [
    [
        '周一训练目标:胸+肱二头肌', '每个动作8-12次,每次做3-5组',
        [
            '动作一:上斜哑铃卧推', '将椅背调节到与地面呈30度左右,双脚踩实地面,臀部收紧,绷紧腹部,肩胛骨后缩下沉使上背平贴凳子\n'
            '双手握住哑铃,拳心朝前,小臂垂直地面放于身体两侧\n'
            '胸部发力,使上臂向身体中间靠拢,在最高点肘关节微弯,保持1秒;肩膀始终后缩下沉\n'
            '缓慢下落,小臂始终垂直地面,下落至哑铃下沿与胸部在同一高度,稍作停顿', '2_1.gif'
        ],
        [
            '动作二:平地哑铃卧推', '双脚踩实地面,臀部收紧,绷紧腹部,肩胛骨后缩下沉使上背平贴凳子,小臂垂直地面举起哑铃在身体两侧\n'
Beispiel #53
0
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time   :2018/4/13 16:46
# @author :shangxudong
# @File   : testWebBrowser.py
# @Software: PyCharm Community Edition
import webbrowser
from webbrowser import Chrome
import cgitb
import cgi

cgitb.enable(display=0, logdir="D:\\cgilog.log")

url = 'http://www.baidu.com/'
# webbrowser.open(url)

# webbrowser.open_new(url)
# webbrowser.open_new_tab(url)

# r = webbrowser.get()

# print(r)

chromepath = r'C:\Program Files (x86)\Google\Chrome\Application'
# webbrowser.register('chrome',Chrome('chrome'))
# webbrowser.get(using='chrome').open(url,new=2,autoraise=True)

# print(r2)

# webbrowser.get(using='chrome').open(url)
Beispiel #54
0
##   the Free Software Foundation; either version 2 of the License, or
##   (at your option) any later version.
##
##   This program is distributed in the hope that it will be useful,
##   but WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.
##
##   You should have received a copy of the GNU General Public License
##   along with this program; if not, write to the Free Software
##   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import os, sys

import cgi
import cgitb
cgitb.enable()  # for troubleshooting

import shutil, time


class Lock(object):
    'lock to avoid concurrent access'

    def __init__(self):
        self.locked = False
        self.sysout = sys.stdout.fileno()
        self.stdout = os.dup(self.sysout)
        self.devnull = open(os.devnull, 'w', 0)

    def lock(self):
        assert not self.locked
Beispiel #55
0
def main():

    # gather arguments
    name_values = {}
    isWeb = ('QUERY_STRING' in os.environ.keys())
    if not isWeb:
        if len(sys.argv) < 4:
            myExit(
                "Usage: TimeDriver.py  progfile=prog  cutoff_time=n  result_prefix=prefix  arg=value ..."
            )
        for pair in sys.argv[1:]:
            words = pair.split('=')
            name_values[words[0]] = words[1]
    else:
        cgitb.enable()
        form = cgi.FieldStorage()
        for key in form.keys():
            name_values[key] = form[key].value
        print(HTML_HEADER)

    # make sure all essential arguments are available
    if 'progfile' not in name_values or 'cutoff_time' not in name_values or 'result_prefix' not in name_values:
        myExit(
            'Did not receive necessary arguments: "progfile" or "cutoff_time" or "result_prefix"\n'
            + str(name_values))
    progfile = name_values['progfile']
    cutoff_time = float(name_values['cutoff_time'])
    result_prefix = name_values['result_prefix']

    # check that progfile exists, exit if not.
    # if the file has '\r', rewrite the file removing them
    # get the version of python from the shebang, else 'python3'
    python_version, errmsg = checkProgfile(progfile)
    if errmsg:
        myExit('', errmsg)

    # create random filenames for child's stdout and stderr
    basename = makeRandomFilename(progfile)
    result_file = basename + '.txt'
    stderr_file = basename + '.err'

    # create the child's command-line arguments
    prog_args = []
    for key in name_values.keys():
        if key != 'progfile' and key != 'cutoff_time':
            prog_args.append(key + '=' + name_values[key])
    prog_args.append('result_file=' + result_file)
    to_run = [python_version, progfile] + prog_args

    # delete the result_file in case it exists
    try:
        os.remove(result_file)
    except:
        pass

    #print ('Executing: '+' '.join(to_run))

    # open stderr_file to redirect child's error messages
    try:
        ferr = open(stderr_file, 'w')
    except:
        myExit('', 'Cannot open %s for writing' % stderr_file)

    # LAUNCH THE CHILD, redirecting its stderr
    proc = subprocess.Popen(to_run, stderr=ferr)

    # wait for process to finish, or terminate it if longer than cutoff_time
    start_time = time.time()
    while True:
        # finished?
        if proc.poll() is not None:
            break

        # too long?
        if time.time() - start_time > cutoff_time:
            proc.kill()
            break

        # check 5 times/sec
        time.sleep(.2)

    # gather the results from the output file
    result = lastResult(result_file, name_values['result_prefix'])

    # wait a moment to let proc die
    time.sleep(0.1)

    # add any error messages captured in stderr_file
    try:
        ferr.close()
    except:
        pass
    try:
        ferr = open(stderr_file, 'rU')
        s = ferr.read()
        ferr.close()
        if s:
            result += '\n' + s
    except:
        pass

    # remove the output and error files
    try:
        os.remove(result_file)
    except:
        pass
    try:
        os.remove(stderr_file)
    except:
        pass

    #result+='%4.1f secs in TimeDriver' % (time.time() - start_time)
    result = result.strip()
    if len(result) == 0:
        result = 'No output'
    myExit(result)
Beispiel #56
0
#!/usr/bin/env python3
"""
--documentation--
"""

__author__ = "Peter Kleiweg"
__version__ = "0.1"
__date__ = "2010/05/13"

#| imports

import cgitb
cgitb.enable(format="html")

import cgi, os, re, sys

import u.html, u.path
from u.login import username

#| globals

#| functions


def getval(field):
    return re.sub(r'\s+', ' ', form.getvalue(field, '')).strip()


#| main

u.html.loginCheck()
Beispiel #57
0
#!/usr/bin/python

# tell python where to find source code
import os, sys
src_path = os.path.realpath("../../chapters/06/src")
sys.path.append(src_path)

# enable error display
import cgitb
cgitb.enable(display=1, logdir=".")

# custom imports
from config.config import Config
from web.responder.html import HtmlResponder
from web.auth import SimpleAuth
from db.mongodb.connection import Connection
from sweetscomplete.domain.customer import CustomerService
from sweetscomplete.entity.customer import Customer
from sweetscomplete.domain.purchase import PurchaseService
from sweetscomplete.entity.purchase import Purchase

# create CustomerService instance using configuration class
config = Config()
db_config = config.getConfig('db')
cust_conn = Connection(db_config['host'], db_config['port'], Customer)
cust_service = CustomerService(cust_conn, db_config['database'])
purch_conn = Connection(db_config['host'], db_config['port'], Purchase)
purch_service = PurchaseService(purch_conn, db_config['database'])

# init vars
auth = SimpleAuth(cust_service, config.getConfig('session_storage'))
Beispiel #58
0
#! /usr/bin/env python3

# taken from:
#    https://docs.python.org/3.4/howto/webservers.html

import cgi

# enable debugging.  Note that the Python docs recommend this for testing, but
# say that it's a very bad idea to leave enabled in production, as it can leak
# information about your internal implementation.
import cgitb
cgitb.enable(display=0, logdir="/var/log/httpd/cgi_err/")

import MySQLdb
import private_no_share_dangerous_passwords as pnsdp



# this function handles the processing of the actual text of the HTML file.
# It writes everything from the HTML header, to the content in the body, to
# the closing tags at the bottom.
#
# Later, I ought to make this smarter, to handle cookies and such.  Or, just
# switch over to some framework which makes it all easier for me!

def write_html():
    # see https://docs.python.org/3.4/library/cgi.html for the basic usage
    # here.
    form = cgi.FieldStorage()

Beispiel #59
0
# problem.  This program supports the following operations:
# - move cursor to previous item (in preorder traversal)
# - move cursor to next item (likewise)
# - hide descendants
# - reveal children
# And because it runs over the filesystem, it must be at least somewhat lazy
# about expanding children.
# And it doesn't really bother to worry about someone else changing the outline
# behind its back.
# So the strategy is to store our current linear position in the
# inorder traversal, and defer operations on the current node until the next
# time we're traversing.


import curses.wrapper, time, random, cgitb, os, sys
cgitb.enable(format="text")
ESC = 27
result = ''
start = '.'

def pad(data, width):
    # XXX this won't work with UTF-8
    return data + ' ' * (width - len(data))

class File:
    def __init__(self, name):
        self.name = name
    def render(self, depth, width):
        return pad('%s%s %s' % (' ' * 4 * depth, self.icon(),
                                os.path.basename(self.name)), width)
    def icon(self): return '   '
# -*- coding: utf-8 -*-
import cgitb

cgitb.enable()  # 调用函数enable可显示包含错误或异常信息的网页,程序开发完成后,应关闭cgitb功能

print('Content-type: text/html\n')
print(1 / 0)
print('Hello, world!')

# ### 脚本说明
# 使用cgitb进行调试;
# 执行脚本:
#   1-启动支持cgi的Web服务器:在命令行下执行“py -3 -m http.server --cgi”;
#   2-将本CGI脚本放在服务器所在目录的子目录cgi-bin,并设置权限;
#   3-在浏览器打开“http://127.0.0.1:8000/cgi-bin/Chapter18_Web02_cgitb.py”;
#   4-打开的页面将显示有关“ZeroDivisionError”的信息;
#
# ### 模块cgitb
# Traceback manager for CGI scripts
# https://docs.python.org/3/library/cgitb.html
# 用于CGI栈跟踪,可以帮助调试CGI脚本;
# 特别注意:程序开发完成后,应关闭cgitb功能;