rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
class Request(object): """Request API Object
|
class WSGIRequest(object): """WSGI Request API Object
|
def __call__(self, *args): if not self.result: self.result = self.fn(*args) return self.result
|
_explicit_re = re.compile(r'<pre\s*[^>]*id="paste.debug.prints".*?>',
|
_explicit_re = re.compile(r'<pre\s*[^>]*id="paste-debug-prints".*?>',
|
def remove_printdebug(): removed.append(None)
|
pms.update(self.post) pms.update(self.get)
|
pms.update(self.POST) pms.update(self.GET)
|
def params(self): """MultiDict of keys from POST, GET, URL dicts
|
elif client_clock <= self.last_modified:
|
elif client_clock >= int(self.last_modified):
|
def __call__(self, environ, start_response): headers = self.headers[:] if self.expires is not None: replace_header(headers,'expires', formatdate(time.time()+self.expires))
|
assert start_response_started, ( "The application returned, but did not call start_response()")
|
def start_response_wrapper(*args, **kw): assert len(args) == 2 or len(args) == 3, ( "Invalid number of arguments: %s" % args) assert not kw, "No keyword arguments allowed" status = args[0] headers = args[1] if len(args) == 3: exc_info = args[2] else: exc_info = None
|
|
return IteratorWrapper(iterator)
|
return IteratorWrapper(iterator, start_response_started)
|
def start_response_wrapper(*args, **kw): assert len(args) == 2 or len(args) == 3, ( "Invalid number of arguments: %s" % args) assert not kw, "No keyword arguments allowed" status = args[0] headers = args[1] if len(args) == 3: exc_info = args[2] else: exc_info = None
|
def __init__(self, wsgi_iterator):
|
def __init__(self, wsgi_iterator, check_start_response):
|
def __init__(self, wsgi_iterator): self.original_iterator = wsgi_iterator self.iterator = iter(wsgi_iterator) self.closed = False
|
return self.iterator.next()
|
v = self.iterator.next() if self.check_start_response is not None: assert self.check_start_response, ( "The application returns and we started iterating over its body, but start_response has not yet been called") self.check_start_response = None return v
|
def next(self): assert not self.closed, ( "Iterator read after closed") return self.iterator.next()
|
This an optional SSL certificate file (via OpenSSL) You can
|
This an optional SSL certificate file (via OpenSSL). You can
|
def serve(application, host=None, port=None, handler=None, ssl_pem=None, server_version=None, protocol_version=None, start_loop=True, daemon_threads=None, socket_timeout=None, use_threadpool=True, threadpool_workers=10): """ Serves your ``application`` over HTTP(S) via WSGI interface ``host`` This is the ipaddress to bind to (or a hostname if your nameserver is properly configured). This defaults to 127.0.0.1, which is not a public interface. ``port`` The port to run on, defaults to 8080 for HTTP, or 4443 for HTTPS. This can be a string or an integer value. ``handler`` This is the HTTP request handler to use, it defaults to ``WSGIHandler`` in this module. ``ssl_pem`` This an optional SSL certificate file (via OpenSSL) You can generate a self-signed test PEM certificate file as follows: $ openssl genrsa 1024 > host.key $ chmod 400 host.key $ openssl req -new -x509 -nodes -sha1 -days 365 \ -key host.key > host.cert $ cat host.cert host.key > host.pem $ chmod 400 host.pem ``server_version`` The version of the server as reported in HTTP response line. This defaults to something like "PasteWSGIServer/0.5". Many servers hide their code-base identity with a name like 'Amnesiac/1.0' ``protocol_version`` This sets the protocol used by the server, by default ``HTTP/1.0``. There is some support for ``HTTP/1.1``, which defaults to nicer keep-alive connections. This server supports ``100 Continue``, but does not yet support HTTP/1.1 Chunked Encoding. Hence, if you use HTTP/1.1, you're somewhat in error since chunked coding is a mandatory requirement of a HTTP/1.1 server. If you specify HTTP/1.1, every response *must* have a ``Content-Length`` and you must be careful not to read past the end of the socket. ``start_loop`` This specifies if the server loop (aka ``server.serve_forever()``) should be called; it defaults to ``True``. ``daemon_threads`` This flag specifies if when your webserver terminates all in-progress client connections should be droppped. It defaults to ``False``. You might want to set this to ``True`` if you are using ``HTTP/1.1`` and don't set a ``socket_timeout``. ``socket_timeout`` This specifies the maximum amount of time that a connection to a given client will be kept open. At this time, it is a rude disconnect, but at a later time it might follow the RFC a bit more closely. ``use_threadpool`` Server requests from a pool of worker threads (``threadpool_workers``) rather than creating a new thread for each request. This can substantially reduce latency since there is a high cost associated with thread creation. ``threadpool_workers`` Number of worker threads to create when ``use_threadpool`` is true. This can be a string or an integer value. """ ssl_context = None if ssl_pem: assert SSL, "pyOpenSSL is not installed" port = int(port or 4443) ssl_context = SSL.Context(SSL.SSLv23_METHOD) ssl_context.use_privatekey_file(ssl_pem) ssl_context.use_certificate_file(ssl_pem) host = host or '127.0.0.1' if not port: if ':' in host: host, port = host.split(':', 1) else: port = 8080 server_address = (host, int(port)) if not handler: handler = WSGIHandler if server_version: handler.server_version = server_version handler.sys_version = None if protocol_version: assert protocol_version in ('HTTP/0.9', 'HTTP/1.0', 'HTTP/1.1') handler.protocol_version = protocol_version if converters.asbool(use_threadpool): server = WSGIThreadPoolServer(application, server_address, handler, ssl_context, int(threadpool_workers)) else: server = WSGIServer(application, server_address, handler, ssl_context) if daemon_threads: server.daemon_threads = daemon_threads if socket_timeout: server.wsgi_socket_timeout = int(socket_timeout) if converters.asbool(start_loop): print "serving on %s:%s" % server.server_address try: server.serve_forever() except KeyboardInterrupt: # allow CTRL+C to shutdown pass return server
|
return output
|
return output.write
|
def replacement_start_response(status, headers, exc_info=None): data.append(status) data.append(headers) start_response(status, headers, exc_info) return output
|
return StatusKeeper(app, status='404 Not Found', url='/error')
|
return StatusKeeper(app, status='404 Not Found', url='/error', headers=[])
|
def factory(app): return StatusKeeper(app, status='404 Not Found', url='/error')
|
return_error = error_template( error_message or '''
|
msg = error_message or '''
|
def handle_exception(exc_info, error_stream, html=True, debug_mode=False, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=False, error_email_from='errors@localhost', smtp_server='localhost', error_subject_prefix='', error_message=None, ): """ For exception handling outside of a web context Use like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if error_email: rep = reporter.EmailReporter( to_addresses=error_email, from_address=error_email_from, smtp_server=smtp_server, subject_prefix=error_subject_prefix) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if error_log: rep = reporter.LogReporter( filename=error_log) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if show_exceptions_in_wsgi_errors: rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if debug_mode: error_html = formatter.format_html( exc_data, include_hidden_frames=True, include_reusable=False) head_html = formatter.error_css + formatter.hide_display_js return_error = error_template( head_html, error_html, extra_data) extra_data = '' reported = True else: return_error = error_template( error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''', '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True) err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error
|
''', '')
|
''' return_error = error_template('', error_message, '')
|
def handle_exception(exc_info, error_stream, html=True, debug_mode=False, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=False, error_email_from='errors@localhost', smtp_server='localhost', error_subject_prefix='', error_message=None, ): """ For exception handling outside of a web context Use like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if error_email: rep = reporter.EmailReporter( to_addresses=error_email, from_address=error_email_from, smtp_server=smtp_server, subject_prefix=error_subject_prefix) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if error_log: rep = reporter.LogReporter( filename=error_log) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if show_exceptions_in_wsgi_errors: rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if debug_mode: error_html = formatter.format_html( exc_data, include_hidden_frames=True, include_reusable=False) head_html = formatter.error_css + formatter.hide_display_js return_error = error_template( head_html, error_html, extra_data) extra_data = '' reported = True else: return_error = error_template( error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''', '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True) err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error
|
host, port = host.split(':', 1)[0]
|
host, port = host.split(':', 1)
|
def __call__(self, environ, start_response): host = environ.get('HTTP_HOST', environ.get('SERVER_NAME')).lower() if ':' in host: host, port = host.split(':', 1)[0] else: if environ['wsgi.url_scheme'] == 'http': port = '80' else: port = '443' path_info = environ.get('PATH_INFO') path_info = self.normalize_url(path_info, False)[1] for (domain, app_url), app in self.applications: if domain and domain != host and domain != host+':'+port: continue if (path_info == app_url or path_info.startswith(app_url + '/')): environ['SCRIPT_NAME'] += app_url environ['PATH_INFO'] = path_info[len(app_url):] return app(environ, start_response) environ['paste.urlmap_object'] = self return self.not_found_application(environ, start_response)
|
status = '200 OK' headers = [] import pprint pprint.pprint(cgi_environ)
|
def __call__(self, environ, start_response): if 'REQUEST_URI' not in environ: environ['REQUEST_URI'] = ( environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')) if self.include_os_environ: cgi_environ = os.environ.copy() else: cgi_environ = {} for name in environ: # Should unicode values be encoded? if (name.upper() == name and isinstance(environ[name], str)): cgi_environ[name] = environ[name] if self.query_string is not None: old = cgi_environ.get('QUERY_STRING', '') if old: old += '&' cgi_environ['QUERY_STRING'] = old + self.query_string # Default status in CGI: status = '200 OK' headers = [] import pprint pprint.pprint(cgi_environ) proc = subprocess.Popen( [self.script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=cgi_environ, cwd=os.path.dirname(self.script), ) proc_communicate( proc, stdin=StdinReader.from_environ(environ), stdout=CGIWriter(environ, start_response), stderr=environ['wsgi.errors']) return []
|
|
//var jsolait = importModule("jsolait"); //jsolait.baseURL = "%(lib)s"; //jsolait.libURL = "%(jsolaitURL)s";
|
jsolait.baseURL = "%(lib)s"; jsolait.libURL = "%(jsolaitURL)s";
|
def jsonjs(self): env = self.servlet().request().environ() jsolaitURL = self.jsolaitURL lib = self.libURL here = wsgilib.construct_url(env, False) here += '?_action_=jsonaction'; if self.baseConfig: app_base = env['%s.base_url' % self.baseConfig] if not jsolaitURL.startswith('/'): jsolaitURL = app_base + '/' + jsolaitURL if not lib.startswith('/'): lib = app_base + '/' + lib text = (r''' <script type="text/javascript" src="%(jsolaitURL)s/init.js"></script> <script type="text/javascript"> //var jsolait = importModule("jsolait"); //jsolait.baseURL = "%(lib)s"; //jsolait.libURL = "%(jsolaitURL)s"; </script> <script type="text/javascript" src="%(jsolaitURL)s/lib/urllib.js"></script> <script type="text/javascript" src="%(jsolaitURL)s/lib/jsonrpc.js"></script> <script type="text/javascript" src="%(jsolaitURL)s/lib/lang.js"></script> <script type="text/javascript"> jsonrpc = importModule("jsonrpc"); var servlet = new jsonrpc.ServiceProxy(%(here)r, %(methods)r); </script> ''' % {'jsolaitURL': jsolaitURL, 'lib': lib, 'here': here, 'methods': self.jsonMethods()}) return text
|
sys.exit(server.run_commandline(self.args))
|
sys.exit(server.run_server(conf, self.app))
|
def command(self): conf = self.config verbose = conf.get('verbose') or 0 if conf.get('daemon'): # We must enter daemon mode! if verbose > 1: print 'Entering daemon mode' pid = os.fork() if pid: sys.exit() # Always record PID and output when daemonized if not conf.get('pid_file'): conf['pid_file'] = 'server.pid' if not conf.get('log_file'): conf['log_file'] = 'server.log' if conf.get('pid_file'): # @@: We should check if the pid file exists and has # an active process in it if verbose > 1: print 'Writing pid %s to %s' % (os.getpid(), conf['pid_file']) f = open(conf['pid_file'], 'w') f.write(str(os.getpid())) f.close() if conf.get('log_file'): if verbose > 1: print 'Logging to %s' % conf['log_file'] f = open(conf['log_file'], 'a', 1) # 1==line buffered sys.stdout = sys.stderr = f f.write('-'*20 + ' Starting server PID: %s ' % os.getpid() + '-'*20 + '\n') self.change_user_group(conf.get('user'), conf.get('group')) sys.exit(server.run_commandline(self.args))
|
return self.find_method(servlet, *args, **kw)
|
result = self.find_method(servlet, *args, **kw) if result is None: return event.Continue else: return result
|
def respond_event(self, name, servlet, *args, **kw): if name == 'end_awake': return self.find_method(servlet, *args, **kw) return event.Continue
|
try: return action, getattr(servlet, action) except AttributeError: pass
|
def get_method(self, servlet, action): try: return action, getattr(servlet, action) except AttributeError: pass if self.prefix: try: return (self.prefix + action, getattr(servlet, self.prefix + action)) except AttributeError: pass return None, None
|
|
def __init__(self, action_name='_action_'):
|
def __init__(self, action_name='_action_', default_action=None):
|
def __init__(self, action_name='_action_'): self.action_name = action_name
|
def find_method(self, servlet, ret_value):
|
def find_method(self, servlet, ret_value, **kw):
|
def find_method(self, servlet, ret_value): possible_actions = [] for name, value in servlet.fields.items(): if name == self.action_name: possible_actions.append(value) elif name.startswith(self.action_name): possible_actions.append(name[len(self.action_name):]) if not possible_actions: return event.Continue if len(possible_actions) > 1: raise httpexceptions.HTTPBadRequest( "More than one action received: %s" % ', '.join(map(repr, possible_actions))) action = possible_actions[0] name, method = self.get_method(servlet, action) if name is None: raise httpexceptions.Forbidden( "Action method not found: %r" % action) if not self.valid_method(name, method): raise httpexceptions.Forbidden( "Method not allowed: %r" % action) return method()
|
return event.Continue
|
if self.default_action: possible_actions = [self.default_action] else: return event.Continue
|
def find_method(self, servlet, ret_value): possible_actions = [] for name, value in servlet.fields.items(): if name == self.action_name: possible_actions.append(value) elif name.startswith(self.action_name): possible_actions.append(name[len(self.action_name):]) if not possible_actions: return event.Continue if len(possible_actions) > 1: raise httpexceptions.HTTPBadRequest( "More than one action received: %s" % ', '.join(map(repr, possible_actions))) action = possible_actions[0] name, method = self.get_method(servlet, action) if name is None: raise httpexceptions.Forbidden( "Action method not found: %r" % action) if not self.valid_method(name, method): raise httpexceptions.Forbidden( "Method not allowed: %r" % action) return method()
|
raise httpexceptions.Forbidden(
|
raise httpexceptions.HTTPForbidden(
|
def find_method(self, servlet, ret_value): possible_actions = [] for name, value in servlet.fields.items(): if name == self.action_name: possible_actions.append(value) elif name.startswith(self.action_name): possible_actions.append(name[len(self.action_name):]) if not possible_actions: return event.Continue if len(possible_actions) > 1: raise httpexceptions.HTTPBadRequest( "More than one action received: %s" % ', '.join(map(repr, possible_actions))) action = possible_actions[0] name, method = self.get_method(servlet, action) if name is None: raise httpexceptions.Forbidden( "Action method not found: %r" % action) if not self.valid_method(name, method): raise httpexceptions.Forbidden( "Method not allowed: %r" % action) return method()
|
assert self.prefix, "must set prefix"
|
assert self.prefix is not None, "must set prefix"
|
def __init__(self, *args, **kwargs): assert self.app_obj, "must set app_obj" assert self.prefix, "must set prefix" args = (self,) + args scgi_server.SCGIHandler.__init__(*args, **kwargs)
|
include_ip=True):
|
include_ip=True, logout_path=None):
|
def __init__(self, app, secret, cookie_name='auth_tkt', secure=False, include_ip=True): self.app = app self.secret = secret self.cookie_name = cookie_name self.secure = secure self.include_ip = include_ip
|
secret, cookie, remote_addr)
|
self.secret, cookie_value, remote_addr)
|
def __call__(self, environ, start_response): cookies = request.get_cookies(environ) if cookies.has_key(self.cookie_name): cookie_value = cookies[self.cookie_name].value else: cookie_value = '' if cookie_value: if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: # mod_auth_tkt uses this dummy value when IP is not # checked: remote_addr = '0.0.0.0' # @@: This should handle bad signatures better: # Also, timeouts should cause cookie refresh timestamp, userid, tokens, user_data = parse_ticket( secret, cookie, remote_addr) tokens = ','.join(tokens) environ['REMOTE_USER'] = userid if environ.get('REMOTE_USER_TOKENS'): # We want to add tokens/roles to what's there: tokens = environ['REMOTE_USER_TOKENS'] + ',' + tokens environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' set_cookies = [] def set_user(userid, tokens='', user_data=''): set_cookies.extend(self.set_user_cookie( environ, userid, tokens, user_data)) def logout_user(): set_cookies.extend(self.logout_user_cookie(environ)) environ['paste.auth_tkt.set_user'] = set_user environ['paste.auth_tkt.logout_user'] = logout_user def cookie_setting_start_response(status, headers, exc_info=None): headers.extend(set_cookies) return start_response(status, headers, exc_info) return self.app(environ, cookie_setting_start_response)
|
if not rep_err:
|
if rep_err:
|
def handle_exception(exc_info, conf, error_stream, html=True): """ You can also use exception handling outside of a web context, like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if conf.get('error_email'): rep = reporter.EmailReporter( to_addresses=conf['error_email'], from_address=conf.get('error_email_from', 'errors@localhost'), smtp_server=conf.get('smtp_server', 'localhost'), subject_prefix=conf.get('error_subject_prefix', '')) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True if conf.get('error_log'): rep = reporter.LogReporter( filename=conf['error_log']) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True if conf.get('show_exceptions_in_error_log', True): rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if conf.get('debug', False): error_html = formatter.format_html(exc_data, include_hidden_frames=True) return_error = error_template( error_html, extra_data) extra_data = '' reported = True else: error_message = conf.get('error_message') return_error = error_template( error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''', '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True) err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error
|
reported = True if conf.get('show_exceptions_in_error_log', True):
|
else: reported = True if conf.get('show_exceptions_in_error_log', False):
|
def handle_exception(exc_info, conf, error_stream, html=True): """ You can also use exception handling outside of a web context, like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if conf.get('error_email'): rep = reporter.EmailReporter( to_addresses=conf['error_email'], from_address=conf.get('error_email_from', 'errors@localhost'), smtp_server=conf.get('smtp_server', 'localhost'), subject_prefix=conf.get('error_subject_prefix', '')) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True if conf.get('error_log'): rep = reporter.LogReporter( filename=conf['error_log']) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True if conf.get('show_exceptions_in_error_log', True): rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if not rep_err: extra_data += rep_err reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if conf.get('debug', False): error_html = formatter.format_html(exc_data, include_hidden_frames=True) return_error = error_template( error_html, extra_data) extra_data = '' reported = True else: error_message = conf.get('error_message') return_error = error_template( error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''', '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True) err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error
|
"paste.webkit.FakeWebware.MiscUtils"],
|
"paste.webkit.FakeWebware.MiscUtils", "paste.servers", "paste.servers.scgi_server", "paste.wareweb"],
|
def get_data_files(path, files = []): l = [] for name in os.listdir(path): if name[0] == ".": continue relpath = os.path.join(path, name) f = os.path.join(BASEDIR, relpath) if os.path.isdir(f): get_data_files(relpath, files) elif os.path.isfile(f): l.append(f) pref = sysconfig.get_python_lib()[len(sysconfig.PREFIX) + 1:] files.append((os.path.join(pref, path), l)) return files
|
environ['REMOTE_USER_TOKENS'] = tokens
|
def __call__(self, environ, start_response): cookies = request.get_cookies(environ) if cookies.has_key(self.cookie_name): cookie_value = cookies[self.cookie_name].value else: cookie_value = '' if cookie_value: if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: # mod_auth_tkt uses this dummy value when IP is not # checked: remote_addr = '0.0.0.0' # @@: This should handle bad signatures better: # Also, timeouts should cause cookie refresh timestamp, userid, tokens, user_data = parse_ticket( secret, cookie, remote_addr) tokens = ','.join(tokens) environ['REMOTE_USER'] = userid if environ.get('REMOTE_USER_TOKENS'): # We want to add tokens/roles to what's there: tokens = environ['REMOTE_USER_TOKENS'] + ',' + tokens #environ['REMOTE_USER_TOKENS'] = @@needs fix environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' set_cookies = [] def set_user(userid, tokens='', user_data=''): set_cookies.extend(self.set_user_cookie( environ, userid, tokens, user_data)) def logout_user(): set_cookies.extend(self.logout_user_cookie(environ)) environ['paste.auth_tkt.set_user'] = set_user environ['paste.auth_tkt.logout_user'] = logout_user def cookie_setting_start_response(status, headers, exc_info=None): headers.extend(set_cookies) return start_response(status, headers, exc_info) return self.app(environ, cookie_setting_start_response)
|
|
print "login! %r" % username print request['environ'].keys()
|
def do_process(self, request): """Handle the redirect from the OpenID server. """ oidconsumer = self.oidconsumer
|
|
print "Set with", request['environ']['paste.auth_tkt.set_user']
|
def do_process(self, request): """Handle the redirect from the OpenID server. """ oidconsumer = self.oidconsumer
|
|
if end: break
|
def _parse_action(self): self.action = None for match in self._tag_re.finditer(self.text): end = match.group(1) == '/' tag = match.group(2).lower() if tag != 'form': continue attrs = _parse_attrs(match.group(3)) self.action = attrs.get('action', '') self.method = attrs.get('method', 'GET') self.id = attrs.get('id') # @@: enctype? if end: break else: assert 0, "No </form> tag found" assert self.action is not None, ( "No <form> tag found")
|
|
return -len(url), '\xff'
|
return '\xff', -len(url)
|
def key(app_desc): (domain, url), app = app_desc if not domain: # Make sure empty domains sort last: return -len(url), '\xff' else: return -len(url), domain
|
return -len(url), domain
|
return domain, -len(url)
|
def key(app_desc): (domain, url), app = app_desc if not domain: # Make sure empty domains sort last: return -len(url), '\xff' else: return -len(url), domain
|
if type(app_iter) in (list, tuple): reg.cleanup() return app_iter else: new_app_iter = wsgilib.add_close(app_iter, reg.cleanup) return new_app_iter
|
reg.cleanup() return app_iter
|
def __call__(self, environ, start_response): app_iter = None reg = environ.setdefault('paste.registry', Registry()) reg.prepare() try: app_iter = self.application(environ, start_response) finally: if app_iter is None: # An error occurred... reg.cleanup() if type(app_iter) in (list, tuple): # Because it is a concrete iterator (not a generator) we # know the configuration for this thread is no longer # needed: reg.cleanup() return app_iter else: new_app_iter = wsgilib.add_close(app_iter, reg.cleanup) return new_app_iter
|
self.originElev)
|
self.originElev.value) CSGeo.initialize(self)
|
def initialize(self): """Initialize coordinate system.""" import spatialdata.geocoords.geocoords as bindings bindings.CppCSGeoLocalCart_origin(self._cppCoordSys, self.originLon, self.originLat, self.originElev)
|
CSGeo.initialize(self)
|
def initialize(self): """Initialize coordinate system.""" import spatialdata.geocoords.geocoords as bindings bindings.CppCSGeoLocalCart_origin(self._cppCoordSys, self.originLon, self.originLat, self.originElev)
|
|
__id__ = "$Id: SimpleDB.py,v 1.3 2005/03/21 20:25:08 baagaard Exp $"
|
__id__ = "$Id: SimpleDB.py,v 1.4 2005/03/23 18:09:11 baagaard Exp $"
|
def __init__(self, name="simpledb"): """Constructor.""" SpatialDB.__init__(self, name) self._cppSpatialDB = bindings.CppSimpleDB() return
|
__id__ = "$Id: GeoCoordSys.py,v 1.1 2005/06/01 23:55:34 baagaard Exp $"
|
__id__ = "$Id: GeoCoordSys.py,v 1.2 2005/06/02 21:33:39 baagaard Exp $"
|
def __init__(self, name="geocoordsys"): """Constructor.""" Component.__init__(self, name, facility="geocoordsys")
|
dash_i = relsfx.rfind('-')
|
dash_i = relsfx.find('-')
|
def __build_search_suffixes(self): "Construct arch & kernel-versioning search suffixes." ss = set()
|
@param mail: an email address sha1sum @type mail: string
|
@param mail_sha1sum: an email address sha1sum @type mail_sha1sum: string
|
def getFoafFromSha(self, mail_sha1sum): """ Services to obtain FOAF URI from an email sha1sum @param mail: an email address sha1sum @type mail: string @return: the FOAF URI of this email owner @rtype: string @todo: customize FOAF service """ # TODO: customize this with a real service # # ideas: - PyGoogle <http://pygoogle.sourceforge.net/> # import google # google.LICENSE_KEY = '...' # data = google.doGoogleSearch('119222cf3a2893a375cc4f884a0138155c771415 filetype:rdf') # # - Swoogle <http://swoogle.umbc.edu/> # # - Ping the Semantic Web.com <http://pingthesemanticweb.com/> foafs = { 'd0fd987214f56f70b4c47fb96795f348691f93ab' : 'http://www.wikier.org/foaf.rdf', '119222cf3a2893a375cc4f884a0138155c771415' : 'http://www.wikier.org/foaf.rdf', '98a99390f2fe9395041bddc41e933f50e59a5ecb' : 'http://www.asturlinux.org/~berrueta/foaf.rdf', '8114083efd55b6d18cae51f1591dd9906080ae89' : 'http://di002.edv.uniovi.es/~labra/labraFoaf.rdf', '84d076726727b596b08198e26ef37e4817353e97' : 'http://frade.no-ip.info:2080/~ivan/foaf.rdf', '3665f4f2370ddd6358da4062f3293f6dc7f39b7c' : 'http://eikeon.com/foaf.rdf', '56e6f2903933a611708ebac456d45e454ddb8838' : 'http://captsolo.net/semweb/foaf-captsolo.rdf', '9a6b7eefc08fd755d51dd9321aecfcc87992e9a2' : 'http://www.johnbreslin.com/foaf/foaf.rdf' } if (mail_sha1sum in foafs): return foafs[mail_sha1sum] else: return None
|
path = self.config.get('url') + 'index.rdf'
|
path = self.config.get('dir') + 'index.rdf'
|
def toRDF(self): """Dump inde to RDF file"""
|
person = URIRef(subscriber.getStringId())
|
person = URIRef(self.baseUri + '
|
def __toRDF(self): """Dump to RDF file all subscribers""" if not (os.path.exists(self.config.get('dir'))): os.mkdir(self.config.get('dir'))
|
self.subscribers.process()
|
if (self.config.get('foaf')): self.subscribers.process()
|
def publish(self): """ Publish the messages """ self.__createDir() #fisrt lap self.__parse() #and second lap mbox = Mbox(self.config.get('mbox')) messages = 0
|
opts, args = getopt.getopt(argv, "dufh:", ["dir=","url=","file=","help"])
|
opts, args = getopt.getopt(argv, "d:u:f:h", ["dir=","url=","file=","help"])
|
def args(self, argv, config): "Getting params"
|
gsr.reset()
|
gsr.clear() gsr.clearSearchForm()
|
def goButtonClicked(self): uri = widgets.get_widget('urlInput').get_text() if (uri != ''): gsr.reset() gsr.messageBar( 'query on ' + uri) gsr.drawTree(gsr.getPosts(uri))
|
def reset(self):
|
def clear(self):
|
def reset(self): #tree self.treeTranslator = {} for column in self.treeView.get_columns(): self.treeView.remove_column(column)
|
self.text.get_buffer().set_text('') def clearSearchForm(self):
|
def reset(self): #tree self.treeTranslator = {} for column in self.treeView.get_columns(): self.treeView.remove_column(column)
|
|
widgets.get_widget('toYearSpin').set_value(2010.0) self.text.get_buffer().set_text('')
|
widgets.get_widget('toYearSpin').set_value(2010.0)
|
def reset(self): #tree self.treeTranslator = {} for column in self.treeView.get_columns(): self.treeView.remove_column(column)
|
print '' print '-----------------------------------------' print 'original: ' + str(msg['From'])
|
def toRDF(self, message, n): """Print a message into RDF in XML format""" msg = message template = Template() tpl = template.get('rdf_message')
|
|
print '1'
|
def toRDF(self, message, n): """Print a message into RDF in XML format""" msg = message template = Template() tpl = template.get('rdf_message')
|
|
print '2' print 'name: ' + from_name print 'mail: ' + from_mail
|
def toRDF(self, message, n): """Print a message into RDF in XML format""" msg = message template = Template() tpl = template.get('rdf_message')
|
|
def loadAdditionalData(self, uri): for post in self.graph.objects(uri, SIOC['container_of']):
|
def loadAdditionalData(self): for post in self.graph.objects(self.uri, SIOC['container_of']):
|
def loadAdditionalData(self, uri): for post in self.graph.objects(uri, SIOC['container_of']): if not self.hasValueForPredicate(post, SIOC['title']): print 'Resolving reference to get additional data (', post, ')...', self.graph.parse(post) print 'OK, now', len(self.graph), 'triples' for user in self.graph.objects(uri, SIOC['has_subscriber']): if not self.hasValueForPredicate(user, SIOC['email_sha1sum']): print 'Resolving reference to get additional data (', user, ')...', self.graph.parse(user) print 'OK, now', len(self.graph), 'triples'
|
for user in self.graph.objects(uri, SIOC['has_subscriber']):
|
for user in self.graph.objects(self.uri, SIOC['has_subscriber']):
|
def loadAdditionalData(self, uri): for post in self.graph.objects(uri, SIOC['container_of']): if not self.hasValueForPredicate(post, SIOC['title']): print 'Resolving reference to get additional data (', post, ')...', self.graph.parse(post) print 'OK, now', len(self.graph), 'triples' for user in self.graph.objects(uri, SIOC['has_subscriber']): if not self.hasValueForPredicate(user, SIOC['email_sha1sum']): print 'Resolving reference to get additional data (', user, ')...', self.graph.parse(user) print 'OK, now', len(self.graph), 'triples'
|
select = ('?post', '?id', '?postTitle', '?userName')
|
select = ('?post', '?postTitle', '?userName', '?parent')
|
def query(self): try: self.graph = self.loadMailingList(self.uri) self.loadAdditionalData(self.uri) print 'Total triples loaded:', len(self.graph) sparqlGr = sparql.sparqlGraph.SPARQLGraph(self.graph) select = ('?post', '?id', '?postTitle', '?userName') where = sparql.GraphPattern([('?post', RDF['type'], SIOC['Post']), ('?post', SIOC['id'], '?id')]) opt = sparql.GraphPattern([('?post', SIOC['title'], '?postTitle'), ('?post', SIOC['has_creator'], '?user'), ('?user', SIOC['name'], '?userName')]) posts = sparqlGr.query(select, where, opt) return posts except Exception, details: gsr.messageBar('unknow problem parsing RDF at ' + self.uri) print 'parsing exception:', str(details) return None
|
('?post', SIOC['id'], '?id')]) opt = sparql.GraphPattern([('?post', SIOC['title'], '?postTitle'),
|
('?post', SIOC['title'], '?postTitle'),
|
def query(self): try: self.graph = self.loadMailingList(self.uri) self.loadAdditionalData(self.uri) print 'Total triples loaded:', len(self.graph) sparqlGr = sparql.sparqlGraph.SPARQLGraph(self.graph) select = ('?post', '?id', '?postTitle', '?userName') where = sparql.GraphPattern([('?post', RDF['type'], SIOC['Post']), ('?post', SIOC['id'], '?id')]) opt = sparql.GraphPattern([('?post', SIOC['title'], '?postTitle'), ('?post', SIOC['has_creator'], '?user'), ('?user', SIOC['name'], '?userName')]) posts = sparqlGr.query(select, where, opt) return posts except Exception, details: gsr.messageBar('unknow problem parsing RDF at ' + self.uri) print 'parsing exception:', str(details) return None
|
for (post, id, title, creator) in posts: self.treeTranslator[id] = self.treeStore.append(self.__getParent(id), [str(title)])
|
for (post, title, creator, parent) in posts: self.treeTranslator[post] = self.treeStore.append(self.__getParent(parent), [str(title)])
|
def drawTree(self, url): self.cache = Cache(url) posts = self.cache.query() if (posts!=None and len(posts)>0): #create view and model self.treeView = widgets.get_widget('postsTree') self.treeStore = gtk.TreeStore(str) self.treeView.set_model(self.treeStore) #append items parent = None for (post, id, title, creator) in posts: self.treeTranslator[id] = self.treeStore.append(self.__getParent(id), [str(title)]) #and show it treeColumn = gtk.TreeViewColumn('Posts') self.treeView.append_column(treeColumn) cell = gtk.CellRendererText() treeColumn.pack_start(cell, True) treeColumn.add_attribute(cell, 'text', 0) treeColumn.set_sort_column_id(0) self.messageBar('loaded ' + url) else: self.messageBar('none posts founded at ' + url)
|
def __getParent(self, id): if (id in self.treeTranslator): return self.treeTranslator[id]
|
def __getParent(self, uri): if (uri in self.treeTranslator): return self.treeTranslator[uri]
|
def __getParent(self, id): if (id in self.treeTranslator): return self.treeTranslator[id] else: return None
|
print msg['Subject'] + ' - ' + subject
|
def __init__(self, msg, config): """Message constructor""" self.__class__.id += 1 self.id = self.__class__.id self.messageId = msg['Message-Id'] self.date = msg['Date'] self.From = msg['From'] self.getAddressFrom = msg.getaddr('From') self.to = msg['To'] #tip because decode_header returns the exception # ValueError: too many values to unpack #performance this tip subject_parted = msg['Subject'].split(' ') subject = '' for one in subject_parted: [(s, enconding)] = decode_header(one) if (subject == ''): subject = s else: subject += ' ' + s print msg['Subject'] + ' - ' + subject self.subject = subject #unicode(msg['Subject'], errors='ignore') self.body = msg.fp.read() #[(self.body, enconding)] = decode_header(msg.fp.read()) self.config = config
|
|
self.to = msg['To'] subject_parted = msg['Subject'].split(' ') subject = '' for one in subject_parted: [(s, enconding)] = decode_header(one) if (subject == ''): subject = s else: subject += ' ' + s self.subject = subject
|
try: self.to = msg['To'] except: self.to = self.config.get('defaultTo')
|
def __init__(self, msg, config): """Message constructor""" self.__class__.id += 1 self.id = self.__class__.id self.messageId = msg['Message-Id'] self.date = msg['Date'] self.From = msg['From'] self.getAddressFrom = msg.getaddr('From') self.to = msg['To'] #tip because decode_header returns the exception # ValueError: too many values to unpack #performance this tip subject_parted = msg['Subject'].split(' ') subject = '' for one in subject_parted: [(s, enconding)] = decode_header(one) if (subject == ''): subject = s else: subject += ' ' + s self.subject = subject #unicode(msg['Subject'], errors='ignore') self.body = msg.fp.read() #[(self.body, enconding)] = decode_header(msg.fp.read()) self.config = config
|
self.config = config
|
def __init__(self, msg, config): """Message constructor""" self.__class__.id += 1 self.id = self.__class__.id self.messageId = msg['Message-Id'] self.date = msg['Date'] self.From = msg['From'] self.getAddressFrom = msg.getaddr('From') self.to = msg['To'] #tip because decode_header returns the exception # ValueError: too many values to unpack #performance this tip subject_parted = msg['Subject'].split(' ') subject = '' for one in subject_parted: [(s, enconding)] = decode_header(one) if (subject == ''): subject = s else: subject += ' ' + s self.subject = subject #unicode(msg['Subject'], errors='ignore') self.body = msg.fp.read() #[(self.body, enconding)] = decode_header(msg.fp.read()) self.config = config
|
|
to = ' ' try: to = self.to except: to = self.config.get('defaultTo')
|
to = self.to
|
def getTo(self): to = ' ' try: to = self.to except: #some mails have not a 'to' field to = self.config.get('defaultTo') to = to.replace('@', self.config.getAntiSpam()) to = to.replace('<', '') to = to.replace('>', '') return unicode(to, errors='ignore')
|
self.msg = msg
|
self.messageId = msg['Message-Id'] self.date = msg['Date'] self.From = msg['From'] self.getAddressFrom = msg.getaddr('From') self.to = msg['To'] subject_parted = msg['Subject'].split(' ') subject = '' for one in subject_parted: [(s, enconding)] = decode_header(one) if (subject == ''): subject = s else: subject += ' ' + s print msg['Subject'] + ' - ' + subject self.subject = subject self.body = msg.fp.read()
|
def __init__(self, msg, config): """Message constructor""" self.__class__.id += 1 self.id = self.__class__.id self.msg = msg self.config = config
|
parted_id = self.msg['Message-Id'].split('.') msg_id = parted_id[len(parted_id)-1] + '-' + self.msg['Date'] + '-swaml-' + str(self.id)
|
parted_id = self.messageId.split('.') msg_id = parted_id[len(parted_id)-1] + '-' + self.date + '-swaml-' + str(self.id)
|
def getSwamlId(self): #TODO: obtain a better SWAML ID parted_id = self.msg['Message-Id'].split('.') msg_id = parted_id[len(parted_id)-1] + '-' + self.msg['Date'] + '-swaml-' + str(self.id) return sha.new(msg_id).hexdigest()
|
date = email.Utils.parsedate(self.getDate())
|
date = email.Utils.parsedate(self.date)
|
def getPath(self): """Return the message's index name"""
|
if(self.msg['From'].find('<')!= -1):
|
if(self.From.find('<')!= -1):
|
def getFromName(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[0]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_name
|
return str(self.msg.getaddr('From')[0])
|
return str(self.getAddressFrom[0])
|
def getFromName(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[0]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_name
|
from_name, from_mail = self.parseFrom(self.msg['From'])
|
from_name, from_mail = self.parseFrom(self.From)
|
def getFromName(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[0]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_name
|
if(self.msg['From'].find('<')!= -1):
|
if(self.From.find('<')!= -1):
|
def getFromMail(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[1]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_mail
|
return str(self.msg.getaddr('From')[1])
|
return str(self.getAddressFrom[1])
|
def getFromMail(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[1]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_mail
|
from_name, from_mail = self.parseFrom(self.msg['From'])
|
from_name, from_mail = self.parseFrom(self.From)
|
def getFromMail(self): if(self.msg['From'].find('<')!= -1): #mail similar than: Name Surmane <[email protected]> return str(self.msg.getaddr('From')[1]) else: #something like: Name Surmane [email protected] from_name, from_mail = self.parseFrom(self.msg['From']) return from_mail
|
to = self.msg['To']
|
to = self.to
|
def getTo(self): to = ' ' try: to = self.msg['To'] except: #some mails have not a 'to' field to = self.config.get('defaultTo') to = to.replace('@', self.config.getAntiSpam()) to = to.replace('<', '') to = to.replace('>', '') return unicode(to, errors='ignore')
|
return unicode(self.msg['Subject'], errors='ignore')
|
return self.subject
|
def getSubject(self): return unicode(self.msg['Subject'], errors='ignore')
|
return self.msg['Date']
|
return self.date
|
def getDate(self): return self.msg['Date']
|
return unicode(self.msg.fp.read(), errors='ignore')
|
return self.body
|
def getBody(self): return unicode(self.msg.fp.read(), errors='ignore')
|
print "SWAML", __init__.__version__
|
print "SWAML 0.0.5",
|
def version(self): print "SWAML", __init__.__version__ sys.exit()
|
elif opt in ("-d", "--dir=") and arg:
|
elif opt in ("-d", "--dir") and arg:
|
def args(self, argv, config): "Getting params of default input"
|
elif opt in ("-u", "--url=") and arg:
|
elif opt in ("-u", "--url") and arg:
|
def args(self, argv, config): "Getting params of default input"
|
elif opt in ("-m", "--mbox=") and arg:
|
elif opt in ("-m", "--mbox") and arg:
|
def args(self, argv, config): "Getting params of default input"
|
elif opt in ("-f", "--format=") and arg:
|
elif opt in ("-f", "--format") and arg:
|
def args(self, argv, config): "Getting params of default input"
|
self.cache.dump()
|
self.cache.dump(self.base + 'buxon.cache')
|
def destroy(self): if (self.cache != None): self.cache.dump()
|
self.window.set_icon_from_file('includes/images/rdf.ico')
|
self.window.set_icon_from_file(self.base + 'includes/images/rdf.ico')
|
def main(self, uri=None): #widgets self.treeView = widgets.get_widget('postsTree') self.text = widgets.get_widget('buxonTextView') buffer = self.text.get_buffer() self.insertBufferTag(buffer, 'bold', 'weight', pango.WEIGHT_BOLD) self.insertBufferTag(buffer, 'monospace', 'family', 'monospace') self.insertBufferTag(buffer, 'wrap_mode', 'wrap_mode', gtk.WRAP_WORD) self.input = widgets.get_widget('urlInput') self.statusbar = widgets.get_widget('buxonStatusbar') self.messageBar('ready') #main window self.window = widgets.get_widget('buxon') self.window.set_icon_from_file('includes/images/rdf.ico') self.window.show() if (uri != None): self.input.set_text(uri) gtk.main()
|
def __init__(self):
|
def __init__(self, base):
|
def __init__(self): GtkUI.__init__(self, 'buxon') self.cache = None self.treeTranslator = {}
|
widgets = ObjectBuilder('includes/ui/graphical/buxon.glade')
|
path = __file__.split('/') base = '/'.join(path[:-1]) + '/' widgets = ObjectBuilder(base + 'includes/ui/graphical/buxon.glade')
|
def __init__(self): GtkUI.__init__(self, 'buxon') self.cache = None self.treeTranslator = {}
|
buxon = Buxon()
|
buxon = Buxon(base)
|
def __init__(self): GtkUI.__init__(self, 'buxon') self.cache = None self.treeTranslator = {}
|
import socket socket.setdefaulttimeout(10)
|
def __getGraph(self, foaf): """ A simple mechanism to cache foaf graph """ if (self.__actualFoaf != foaf or self.__graph == None): self.__actualFoaf = foaf self.__graph = sparqlGraph.SPARQLGraph() try: self.__graph.parse(foaf) except: self.__graph = None
|
|
'bd6566af7b3bfa28f917aa545bf4174661817d79' : 'http://www.asturlinux.org/~jsmanrique/foaf.rdf'
|
'bd6566af7b3bfa28f917aa545bf4174661817d79' : 'http://www.asturlinux.org/~jsmanrique/foaf.rdf', '97d9756f1281858d0e9e4489003073e4986546ce' : 'http://xtrasgu.asturlinux.org/descargas/foaf.rdf'
|
def getFoaf(self, mail): """ Services to obtain FOAF URI from an email address @param mail: an email address @type mail: string @return: the FOAF URI of this email owner @rtype: string @todo customize foaf service """ mail_sha1sum = self.getShaMail(mail) # TODO: customize this with a real service # # ideas: - PyGoogle <http://pygoogle.sourceforge.net/> # import google # google.LICENSE_KEY = '...' # data = google.doGoogleSearch('119222cf3a2893a375cc4f884a0138155c771415 filetype:rdf') # # - Swoogle <http://swoogle.umbc.edu/> foafs = { '119222cf3a2893a375cc4f884a0138155c771415' : 'http://www.wikier.org/foaf.rdf', '98a99390f2fe9395041bddc41e933f50e59a5ecb' : 'http://www.asturlinux.org/~berrueta/foaf.rdf', '8114083efd55b6d18cae51f1591dd9906080ae89' : 'http://di002.edv.uniovi.es/~labra/labraFoaf.rdf', '84d076726727b596b08198e26ef37e4817353e97' : 'http://frade.no-ip.info:2080/~ivan/foaf.rdf', 'bd6566af7b3bfa28f917aa545bf4174661817d79' : 'http://www.asturlinux.org/~jsmanrique/foaf.rdf' } if (mail_sha1sum in foafs): return foafs[mail_sha1sum] else: return None
|
to_tmp = self.msg['To'] self.tpl = self.tpl.replace('{TO}', to_tmp)
|
tmp_to = ' ' try: tmp_to = self.msg['To'] if (self.default_to == ''): self.default_to = tmp_to except: if (self.default_to != ''): tmp_to = self.default_to tmp_to = tmp_to.replace('@', self.config.getAntiSpam()) tmp_to = tmp_to.replace('<', '<') tmp_to = tmp_to.replace('>', '>') self.tpl = self.tpl.replace('{TO}', tmp_to)
|
def addIndex(self, message, n): self.msg = message self.template = Template() self.tpl = self.template.get('rdf_index_item')
|
print '(index) Error proccesing messages: ' + str(detail)
|
print 'Error proccesing messages: ' + str(detail)
|
def addIndex(self, message, n): self.msg = message self.template = Template() self.tpl = self.template.get('rdf_index_item')
|
to_tmp = self.msg.getaddr('To')[1] self.tpl = self.tpl.replace('{TO}', to_tmp)
|
tmp_to = ' ' try: tmp_to = self.msg['To'] if (self.default_to == ''): self.default_to = tmp_to except: if (self.default_to != ''): tmp_to = self.default_to tmp_to = tmp_to.replace('@', self.config.getAntiSpam()) tmp_to = tmp_to.replace('<', '<') tmp_to = tmp_to.replace('>', '>') self.tpl = self.tpl.replace('{TO}', tmp_to)
|
def intoRDF(self, message, n): self.msg = message self.template = Template() self.tpl = self.template.get('rdf_message')
|
print '(intoRDF) Error proccesing messages: ' + str(detail)
|
print 'Error proccesing messages: ' + str(detail)
|
def intoRDF(self, message, n): self.msg = message self.template = Template() self.tpl = self.template.get('rdf_message')
|
self.graph = self.loadMailingList(self.uri) self.loadAdditionalData(self.uri) print 'Total triples loaded:', len(self.graph)
|
self.bad = False try: self.graph = self.loadMailingList(self.uri) except Exception, details: print '\nAn exception ocurred parsing ' + uri + ': ' + str(details) self.bad = True return self.loadAdditionalData() print 'Total triples loaded:', len(self.graph)
|
def __init__(self, uri): self.uri = uri self.graph = self.loadMailingList(self.uri) self.loadAdditionalData(self.uri) print 'Total triples loaded:', len(self.graph)
|
if (uri != self.cache.uri):
|
if (uri!=self.cache.uri or self.cache.bad):
|
def getPosts(self, uri, min=None, max=None, text=None): if (self.cache == None): self.cache = Cache(uri) else: if (uri != self.cache.uri): self.cache = Cache(uri) min, max = self.getDates() posts = self.cache.query() if (min!=None or max!=None or text!=None): posts = self.cache.filterPosts(posts, min, max, text) return posts
|
posts = self.cache.query() if (min!=None or max!=None or text!=None): posts = self.cache.filterPosts(posts, min, max, text) return posts
|
if (not self.cache.bad): posts = self.cache.query() if (min!=None or max!=None or text!=None): posts = self.cache.filterPosts(posts, min, max, text) return posts else: return None
|
def getPosts(self, uri, min=None, max=None, text=None): if (self.cache == None): self.cache = Cache(uri) else: if (uri != self.cache.uri): self.cache = Cache(uri) min, max = self.getDates() posts = self.cache.query() if (min!=None or max!=None or text!=None): posts = self.cache.filterPosts(posts, min, max, text) return posts
|
f.write(url + ' ' + title)
|
f.write(url + ' ' + title + '\n')
|
def dumpTranslation(self): try: f = open(self.translationFile, 'w') for url in self.translation.keys(): title = self.translation[url] f.write(url + ' ' + title) f.close() print 'dumped URL\'s cache in', self.destinationFile except IOError, details: print 'Problem writing translation cache: ' + str(details)
|
print 'dumped URL\'s cache in', self.destinationFile
|
print 'dumped URL\'s cache in', self.translationFile
|
def dumpTranslation(self): try: f = open(self.translationFile, 'w') for url in self.translation.keys(): title = self.translation[url] f.write(url + ' ' + title) f.close() print 'dumped URL\'s cache in', self.destinationFile except IOError, details: print 'Problem writing translation cache: ' + str(details)
|
ret = self.__force_decode(orig)
|
ret = self.__unicode(orig, self.charset)
|
def encode(self, orig): """ Encode an string @param orig: original string """ ret = '' try: ret = self.__force_decode(orig) except Exception: ret = self.__unicode(orig, self.charset) return ret
|
ret = self.__unicode(orig, self.charset)
|
ret = self.__decode(orig)
|
def encode(self, orig): """ Encode an string @param orig: original string """ ret = '' try: ret = self.__force_decode(orig) except Exception: ret = self.__unicode(orig, self.charset) return ret
|
GtkUI.__init__(self, 'buxon')
|
GtkUI.__init__(self, 'buxon', base)
|
def __init__(self, base='./'): """ Buxon constructor @param base: base directory """ GtkUI.__init__(self, 'buxon') self.base = base self.cache = None self.treeTranslator = {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.