rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
sys.stderr.write("PyWPS ERROR: %s in self.process.execute()\n" % (e))
ays.stderr.write("PyWPS ERROR: %s in self.process.execute()\n" % (e))
def execute(self): """ 1) Creates the temporary directory 2) If needed, downloads the data 3) Calls the process 4) Returns the XML or the resulting file/value 5) Cleans the temporary directory
tempdir = tempfile.mkdtemp(prefix="tmpgrass",dir=directory)
tempdir = tempfile.mkdtemp(prefix="tmppywps",dir=directory)
def mktempdir(self,directory=None): """ Creates temporary directory and chdir to it
tempdir = tempfile.mkdtemp(prefix="tmpgrass",dir=self.settings.ServerSettings['tempPath'])
tempdir = tempfile.mkdtemp(prefix="tmppywps",dir=self.settings.ServerSettings['tempPath'])
def mktempdir(self,directory=None): """ Creates temporary directory and chdir to it
procOutput['value'] not self.process.DataOutputs[procOutput['Identifier']]:
procOutput['value'] != self.process.DataOutputs[procOutput['Identifier']]:
def execute(self): """ 1) Creates the temporary directory 2) If needed, downloads the data 3) Calls the process 4) Returns the XML or the resulting file/value 5) Cleans the temporary directory
'value': ["0 0", "10 10"],
'value': [0,0, 10,10],
def __init__(self): self.Identifier = "inputsoutputs" self.processVersion = "0.1" self.Title="Test input and output structures" self.statusSuported="false" self.storeSuported="false" self.Inputs = [ { 'Identifier': 'literal', 'Title': 'Literal Value', 'Abstract': ' "literal value" ', 'LiteralValue': {'UOMs':["cm"]}, 'M...
reader = HistoricalReader()
from pyrepl.unix_console import UnixConsole reader = HistoricalReader(UnixConsole(1, None))
def test(): reader = HistoricalReader() reader.ps1 = "h**> " reader.ps2 = "h/*> " reader.ps3 = "h|*> " reader.ps4 = "h\*> " while reader.readline(): pass
def main(use_pygame_console=0, interactmethod="twistedinteract"):
def main(use_pygame_console=0, interactmethod=default_interactmethod):
def main(use_pygame_console=0, interactmethod="twistedinteract"): si, se, so = sys.stdin, sys.stderr, sys.stdout try: if 0 and use_pygame_console: # pygame currently borked from pyrepl.pygame_console import PyGameConsole, FakeStdin, FakeStdout con = PyGameConsole() sys.stderr = sys.stdout = FakeStdout(con) sys.stdin = ...
self.error("")
r.error("cannot transpose at start of buffer")
def do(self): r = self.reader b = r.buffer s = r.pos - 1 if s < 0: self.error("") else: if s == len(b): s -= 1 t = min(s + r.get_arg(), len(b) - 1) c = b[s] del b[s] b.insert(t, c) r.pos = t r.dirty = 1
_packages[''] += _make_module_list_dir(dir, suffs)
if os.path.isdir(dir): _packages[''] += _make_module_list_dir(dir, suffs)
def compare(x, y): c = -cmp(len(x), len(y)) if c: return c else: return -cmp(x, y)
if self.stack or unicodedata.category(key) == 'C':
if self.stack or len(key) > 1 or unicodedata.category(key) == 'C':
def push(self, evt): if self.verbose: print "pushed", evt.data, key = evt.data d = self.k.get(key) if isinstance(d, dict): if self.verbose: print "transition" self.stack.append((key, self.stack + [key])) self.k = d else: if d is None: if self.verbose: print "invalid" if self.stack or unicodedata.category(key) == 'C': s...
maxlen = max(map(len, wordlist))
maxlen = min(max(map(len, wordlist)), cons.width - 4)
def build_menu(cons, wordlist, start): maxlen = max(map(len, wordlist)) cols = cons.width / (maxlen + 4) rows = (len(wordlist) - 1)/cols + 1 menu = [] i = start for r in range(rows): row = [] for col in range(cols): row.append("[ %-*s ]"%(maxlen, wordlist[i])) i += 1 if i >= len(wordlist): break menu.append( ''.join(ro...
row.append("[ %-*s ]"%(maxlen, wordlist[i]))
row.append("[ %-*s ]"%(maxlen, wordlist[i][:maxlen]))
def build_menu(cons, wordlist, start): maxlen = max(map(len, wordlist)) cols = cons.width / (maxlen + 4) rows = (len(wordlist) - 1)/cols + 1 menu = [] i = start for r in range(rows): row = [] for col in range(cols): row.append("[ %-*s ]"%(maxlen, wordlist[i])) i += 1 if i >= len(wordlist): break menu.append( ''.join(ro...
elif self.threading_level < 2 and self.requests: self.log(2, rec.request_id, "no handler for this role, rejecting")
elif waitstream is not None: self.log(2, rec.request_id, "already handling a request, rejecting")
def process_input(self, waitstream): while 1: try: # this select *should* be pointless, however it works around a bug # in OpenBSD whereby the read() does not get interrupted when # another thread closes the socket (and it does no harm on other # OSes) select.select([self.socket], [], []) rec = Record(self.socket) exce...
for i in xrange(1, 4):
for i in xrange(0, 4):
def _get_template(self): for i in xrange(1, 4): template = self.req.environ.get("REDIRECT_" * i + "WT_TEMPLATE_FILENAME") if template: return template raise Exception, "Couldn't determine template filename"
if self.eof and not self.data: return ""
def read(self, nbytes=-1): if self.eof and not self.data: return "" ret = "" while not self.eof and nbytes != 0: while not self.eof and not self.data: self.sema.acquire() if self.eof: break if nbytes < 0: ret += self.data.pop(0) continue s = self.data[0][self.pos:self.pos+nbytes] self.pos += nbytes ret += s nbytes -= l...
while not self.eof and nbytes != 0:
while nbytes != 0:
def read(self, nbytes=-1): if self.eof and not self.data: return "" ret = "" while not self.eof and nbytes != 0: while not self.eof and not self.data: self.sema.acquire() if self.eof: break if nbytes < 0: ret += self.data.pop(0) continue s = self.data[0][self.pos:self.pos+nbytes] self.pos += nbytes ret += s nbytes -= l...
if self.eof:
if self.eof and not self.data:
def read(self, nbytes=-1): if self.eof and not self.data: return "" ret = "" while not self.eof and nbytes != 0: while not self.eof and not self.data: self.sema.acquire() if self.eof: break if nbytes < 0: ret += self.data.pop(0) continue s = self.data[0][self.pos:self.pos+nbytes] self.pos += nbytes ret += s nbytes -= l...
self._handler_type().process(self)
try: self._handler_type().process(self) except: self.traceback()
def run(self): self.log(2, "New request running") self._read_cgi_data(self.environ, self.fcgi_stdin) self.log(3, "Read CGI data: %s" % `self.params`) self.log(2, "Calling handler") self._handler_type().process(self) self.log(2, "Handler finished") self.flush() if self.aborted < 2: try: rec = Record() rec.type = FCGI_ST...
import traceback exc = sys.exc_info()
import traceback, time, types, linecache, inspect, repr repr = repr.Repr() repr.maxother = 80 repr.maxstring = 80 repr = repr.repr (etype, evalue, etb) = sys.exc_info() if type(etype) is types.ClassType: etype = etype.__name__
def traceback(req, html=0): import traceback exc = sys.exc_info() if html: try: req.clear_headers() req.clear_output() req.set_header("Content-Type", "text/html; charset=iso-8859-1") except SequencingError: pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for ...
pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for line in traceback.format_exception_only(exc[0], exc[1]):
req.write("</font></font></font></script></object></blockquote></pre>" "</table></table></table></table></table></table></font></font>") req.write("""\ <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"...
def traceback(req, html=0): import traceback exc = sys.exc_info() if html: try: req.clear_headers() req.clear_output() req.set_header("Content-Type", "text/html; charset=iso-8859-1") except SequencingError: pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for ...
req.write(html_encode(line)) req.error(line)
req.write("""\ <table width="100%" cellspacing="0" cellpadding="0" border="0">""") fn = fn and os.path.abspath(fn) or "?" args, varargs, varkw, locls = inspect.getargvalues(frame) if func != "?": fav = inspect.formatargvalues(args, varargs, varkw, locls) if html: req.write("<tr><td class=\"tb_frame\">%s in <strong>%s</...
def traceback(req, html=0): import traceback exc = sys.exc_info() if html: try: req.clear_headers() req.clear_output() req.set_header("Content-Type", "text/html; charset=iso-8859-1") except SequencingError: pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for ...
req.write("</b>\n") lines = traceback.format_tb(exc[2]) lines.reverse() for line in lines: if html: req.write(html_encode(line)) req.error(line)
req.write("<p><strong>%s</strong>: %s" % (_tb_encode(etype), _tb_encode(evalue))) req.error("%s: %s\n" % (etype, evalue)) if type(evalue) is types.InstanceType: for name in dir(evalue): if html: req.write("\n<br /><tt>&nbsp;&nbsp;&nbsp;&nbsp;</tt>%s&nbsp;= %s" % (_tb_encode(name), _tb_encode(repr(getattr(evalue, name))...
def traceback(req, html=0): import traceback exc = sys.exc_info() if html: try: req.clear_headers() req.clear_output() req.set_header("Content-Type", "text/html; charset=iso-8859-1") except SequencingError: pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for ...
req.write("</pre></body></html>\n")
req.write("</p>\n") if html: req.write("</body></html>\n") linecache.clearcache()
def traceback(req, html=0): import traceback exc = sys.exc_info() if html: try: req.clear_headers() req.clear_output() req.set_header("Content-Type", "text/html; charset=iso-8859-1") except SequencingError: pass req.write("<html><head><title>jonpy traceback</title></head><body>" "<h1>jonpy traceback</h1><pre><b>") for ...
class DebugHandler(DebugHandlerMixIn, HandlerBase):
class DebugHandler(DebugHandlerMixIn, Handler):
def traceback(self, req): """Display a traceback, req is a Request object.""" traceback(req, html=1)
print "making new connection"
def connect(*args, **kwargs): if _dbmod is None: raise Exception, "No database module has been specified" try: return _available[`args` + "\0" + `kwargs`].get(0) except (KeyError, _Queue.Empty): print "making new connection" return _Connection(None, None, *args, **kwargs)
self.socketf = socket.makefile("r+b")
self.socketf = socket.makefile("r+b", 0)
def __init__(self, socket, handler_types, *args, **kwargs): threading.Thread.__init__(self, *args, **kwargs) self.socket = socket self.socketf = socket.makefile("r+b") self.socketlock = threading.Lock() self.handler_types = handler_types self.fileno = self.socket.fileno()
self.socket.close()
self.socketlock.acquire() try: self.socketf.close() finally: self.socketlock.release()
def close(self): self.socket.close()
self.socketf.write(rec.encode()) self.socketf.flush() self.socketlock.release()
try: self.socketf.write(rec.encode()) finally: self.socketlock.release()
def write(self, rec): self.socketlock.acquire() self.socketf.write(rec.encode()) self.socketf.flush() self.socketlock.release()
except EOFError: self.log(2, 0, "EOF received on connection") for req in self.requests.values(): req.aborted = 1 break
except: x = sys.exc_info()[1] if isinstance(x, EOFError) or isinstance(x, ValueError) or \ (isinstance(x, socket.error) and x[0] == errno.EBADF): self.log(2, 0, "EOF received on connection") for req in self.requests.values(): req.aborted = 2 break else: raise
def run(self): self.log(2, 0, "New connection running") self.requests = {} while 1: try: rec = Record(self.socketf) except EOFError: self.log(2, 0, "EOF received on connection") for req in self.requests.values(): req.aborted = 1 break if rec.type == FCGI_GET_VALUES: data = NameValueData(rec.content_data) self.log(3, 0,...
self.log(2, rec.request_id, "FCGI_BEGIN_REQUEST: role = %d" % role)
self.log(2, rec.request_id, "FCGI_BEGIN_REQUEST: role = %d, flags = %d" % (role, flags))
def run(self): self.log(2, 0, "New connection running") self.requests = {} while 1: try: rec = Record(self.socketf) except EOFError: self.log(2, 0, "EOF received on connection") for req in self.requests.values(): req.aborted = 1 break if rec.type == FCGI_GET_VALUES: data = NameValueData(rec.content_data) self.log(3, 0,...
self.close()
def run(self): self.log(2, 0, "New connection running") self.requests = {} while 1: try: rec = Record(self.socketf) except EOFError: self.log(2, 0, "EOF received on connection") for req in self.requests.values(): req.aborted = 1 break if rec.type == FCGI_GET_VALUES: data = NameValueData(rec.content_data) self.log(3, 0,...
rec = Record() rec.type = FCGI_STDOUT rec.request_id = self.__request_id rec.content_data = "" self.__connection.write(rec) self.log(2, "Closed FCGI_STDOUT") if self._stderr_used: rec.type = FCGI_STDERR self.__connection.write(rec) self.log(2, "Closed FCGI_STDERR") rec.type = FCGI_END_REQUEST rec.request_id = self.__re...
if self.aborted < 2: try: rec = Record() rec.type = FCGI_STDOUT rec.request_id = self.__request_id rec.content_data = "" self.__connection.write(rec) self.log(2, "Closed FCGI_STDOUT") if self._stderr_used: rec.type = FCGI_STDERR self.__connection.write(rec) self.log(2, "Closed FCGI_STDERR") rec.type = FCGI_END_REQUEST ...
def run(self): self.log(2, "New request running") self.read_cgi_data(self.environ, self.fcgi_stdin) self.log(3, "Read CGI data: %s" % `self.params`) self.log(2, "Calling handler") self._handler_type().process(self) self.log(2, "Handler finished") self.flush() rec = Record() rec.type = FCGI_STDOUT rec.request_id = self....
self.__connection.write(rec)
try: self.__connection.write(rec) except IOError, x: if x[0] == errno.EPIPE: self.aborted = 2 self.log(2, "Aborted due to EPIPE") else: raise
def _recwrite(self, type, s): if s: pos = 0 while pos < len(s): if self.aborted: return rec = Record() rec.type = type rec.request_id = self.__request_id if pos == 0 and len(s) <= 65535: # (avoid copying in the common case of s <= 65535 bytes) rec.content_data = s else: rec.content_data = s[pos:pos+65535] pos += len(re...
name_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff
name_length = struct.unpack("!I", data[pos:pos+4])[0] & 0x7fffffff
def __init__(self, data=""): self.values = [] pos = 0 while pos < len(data): if ord(data[pos]) & 128: name_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff pos += 4 else: name_length = ord(data[pos]) pos += 1 if ord(data[pos]) & 128: value_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff pos += 4 el...
value_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff
value_length = struct.unpack("!I", data[pos:pos+4])[0] & 0x7fffffff
def __init__(self, data=""): self.values = [] pos = 0 while pos < len(data): if ord(data[pos]) & 128: name_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff pos += 4 else: name_length = ord(data[pos]) pos += 1 if ord(data[pos]) & 128: value_length = struct.unpack("!I", data[pos:pos+4]) & 0x7fffffff pos += 4 el...
raise Error, "Unexpect end of string before disposition"
raise Error, "Unexpected end of string before disposition"
def parse_content_disposition(s): i = 0 # skip whitespace before disposition while i < len(s) and s[i] in _whitespace: i+= 1 if i >= len(s): raise Error, "Unexpect end of string before disposition" # disposition disposition = "" while i < len(s) and s[i] in _tokenchars: disposition += s[i] i+= 1 while i < len(s) and s[...
self.max_requests = max_requests + 1
self.max_requests = max_requests
def __init__(self, handler_types, max_requests=0): self.handler_types = handler_types self.max_requests = max_requests + 1
if self.max_requests > 0: self.max_requests -= 1 if self.max_requests <= 0: self.log(1, "reached max_requests, exiting") break
def run(self): self.log(1, "Server.run()") web_server_addrs = os.environ.get("FCGI_WEB_SERVER_ADDRS", "").split(",") self.log(1, "web_server_addrs = %s" % `web_server_addrs`) sock = socket.fromfd(sys.stdin.fileno(), socket.AF_INET, socket.SOCK_STREAM) try: sock.getpeername() except socket.error, x: if x[0] != errno.ENO...
def notify_signoff(self, user): self._cache_user(user) drivers.log.info('SILC: Notify (Signoff): %s', user)
def notify_signoff(self, user, msg): self._cache_user(user) drivers.log.info('SILC: Notify (Signoff): %s: %s', user, msg)
def notify_signoff(self, user): self._cache_user(user) drivers.log.info('SILC: Notify (Signoff): %s', user)
ircemu = ':%s 332 RPL_TOPIC channel_name, topic)
ircemu = ':%s 332 %s self.username, channel_name, topic)
def command_reply_join(self, channel, channel_name, topic, hmac_name, mode, user_limit, users): self._cache_channel(channel) myself = self.user() drivers.log.info('SILC: Reply (Join)', channel, topic, users) ircemu = ':%s!%s@%s JOIN :#%s' % (myself.nickname, myself.username, myself.hostname, channel_name)
self.silc.command_call('TOPIC %s %s' % (strip_leading_hash(msg.args[0]), msg.args[1]))
if len(msg.args) > 1: self.silc.command_call('TOPIC %s %s' % (strip_leading_hash(msg.args[0]), msg.args[1])) else: self.silc.command_call('TOPIC %s' % strip_leading_hash(msg.args[0]))
def do_TOPIC(self, msg): self.silc.command_call('TOPIC %s %s' % (strip_leading_hash(msg.args[0]), msg.args[1]))
self._cache_user(changedby)
self._cache_user(changer)
def notify_topic_set(self, changer_type, changer, channel, topic): self._cache_user(changedby) self._cache_channel(channel) drivers.log.info('SILC: Notify (Topic Set):', channel, topic) if changer_type == silc.SILC_ID_CLIENT: ircemu = ':%s!n=%s@%s TOPIC #%s :%s' % \ (changer.nickname, changer.username, changer.hostname...
This methid can only be called in direct response to an
This method can only be called in direct response to an
def setHandler(handler): """Set the IConnectionHandler for a connection.
simultaniously from separate threads, so implementation of the
simultaneously from separate threads, so implementation of the
def close(): """Close the connection """
Note that there are no promises about blocking. There data
Note that there are no promises about blocking. The data
def handle_input(connection, data): """Handle input data from a connection The data is an 8-bit string.
in theory be passed one character at a time. It os up to
in theory be passed one character at a time. It is up to
def handle_input(connection, data): """Handle input data from a connection The data is an 8-bit string.
"""Recieve notification that a connection has closed
"""Receive notification that a connection has closed
def handle_close(connection, reason): """Recieve notification that a connection has closed The reason argument can be converted to a string for logging purposes. It may have data useful for debugging, but this is undefined. Notifications are received when the connection is closed externally, for example, when the ot...
if and when the connection suceeds or failed_connect method
if and when the connection succeeds or failed_connect method
def __call__(address, handler): """Try to make a connection to the given address The handler is an IClientConnectHandler. The handler connected method will be called with an IConnection object if and when the connection suceeds or failed_connect method will be called if the connection fails. """
"""Recieve notifications of connection results
"""Receive notifications of connection results
def __call__(address, handler): """Try to make a connection to the given address The handler is an IClientConnectHandler. The handler connected method will be called with an IConnection object if and when the connection suceeds or failed_connect method will be called if the connection fails. """
"""Recieve notification that a connection had been established
"""Receive notification that a connection had been established
def connected(connection): """Recieve notification that a connection had been established """
"""Recieve notificantion that a connection could not be established
"""Receive notification that a connection could not be established
def failed_connect(reason): """Recieve notificantion that a connection could not be established
When a connection is recieved, call the handler.
When a connection is received, call the handler.
def __call__(address, handler): """Listen for incoming connections
"""Close the listener and all of it's connections
"""Close the listener and all of its connections
def close(handler=None): """Close the listener and all of it's connections
If no handler is passed, the listener and it's connections
If no handler is passed, the listener and its connections
def close(handler=None): """Close the listener and all of it's connections
pass
if __debug__: logger.debug("server handle_close(%r, %r)", connection, reason)
def handle_close(self, connection, reason): pass
mod, name, port = sys.argv[1:]
mod, name, port, level = sys.argv[1:]
def serve(): mod, name, port = sys.argv[1:] __import__(mod) logger.info('serving') getattr(sys.modules[mod], name)(('localhost', int(port)), Server) run()
module, name, str(port), env)
module, name, str(port), str(logger.getEffectiveLevel()), env)
def start_server_process(listener): """Start a server in a subprocess and return the port used """ module = listener.__module__ name = listener.__name__ port = get_port() env = dict( os.environ, PYTHONPATH=os.pathsep.join(sys.path), ) os.spawnle(os.P_NOWAIT, sys.executable, sys.executable, __file__, module, name, str(p...
if self.lines:
if self.lines and self._cur_line is None:
def reopenCurrentLine(self): if self.lines: self._cur_line = self.lines[-1]
self._lastlineno += 1 if self._use_defaults: for part in self.defaultDirectives.get(self._lastlineno, []): self._handleDirective(part)
if not self._continuing: self._lastlineno += 1 if self._use_defaults: for part in self.defaultDirectives.get(self._lastlineno, []): word = part.split()[0] if word not in self._directives_used_in_this_line: self._handleDirective(part)
def _handleText(self, line): self._lastlineno += 1 if self._use_defaults: for part in self.defaultDirectives.get(self._lastlineno, []): self._handleDirective(part) self.slides[-1].addText(line)
if len(bits) == 1 or remaining_space <= 0: break
break
def split(self, canvas, w, h): chunks_that_fit = [] remaining_chunks = list(self.chunks) remaining_space = w while remaining_chunks: chunk = remaining_chunks.pop(0) cw, ch = chunk.size(canvas, w, h) if cw <= remaining_space: chunks_that_fit.append(chunk) remaining_space -= cw else: bits = chunk.split(canvas, w, h, rema...
if opts.verbose: print p
def main(): parser = optparse.OptionParser() parser.add_option('-v', action='store_true', dest='verbose', default=False, help="print the presentation as text (debug)") parser.add_option('-o', action='store', dest='outfile', help="override output file name") try: opts, args = parser.parse_args(sys.argv[1:]) except optpa...
line = line.rstrip().replace(r'\
line = line.rstrip('\n').replace(r'\
def _handleText(self, line): if not self._continuing: self._lastlineno += 1 if self._use_defaults: for part in self.defaultDirectives.get(self._lastlineno, []): word = self._splitArgs(part)[0] if word not in self._directives_used_in_this_line: self._handleDirective(part) line = line.rstrip().replace(r'\#', '#').replace...
if s[idx-1].isalnum() and not s[idx].isalnum():
if not s[idx-1].isspace() and s[idx].isspace():
def textWrapPositions(s): """Find all break points in text, starting from the rightmost. >>> textWrapPositions('well hello world') [16, 10, 4] >>> textWrapPositions('a good day') [12, 7, 1] """ poses = [len(s)] for idx in range(len(s) - 1, 0, -1): if s[idx-1].isalnum() and not s[idx].isalnum(): poses.append(idx) re...
self._cur_line = Line(self.alignment)
self._cur_line = Line(self.alignment, self.prefix)
def currentOrNewLine(self): if self._cur_line is None: self._cur_line = Line(self.alignment) self.lines.append(self._cur_line) return self._cur_line
def __init__(self, alignment=Left):
def __init__(self, alignment=Left, prefix=0):
def __init__(self, alignment=Left): self.chunks = [] self.alignment = alignment
clone = Line(self.alignment)
clone = Line(self.alignment, self.prefix)
def cloneStyle(self, newchunks): clone = Line(self.alignment) clone.chunks = newchunks return clone
return [self.cloneStyle(chunks_that_fit), self.cloneStyle(remaining_chunks)]
return ([self.cloneStyle(chunks_that_fit)] + self.cloneStyle(remaining_chunks).split(canvas, w, h))
def split(self, canvas, w, h): chunks_that_fit = [] remaining_chunks = list(self.chunks) remaining_space = w while remaining_chunks: chunk = remaining_chunks.pop(0) cw, ch = chunk.size(canvas, w, h) if cw <= remaining_space: chunks_that_fit.append(chunk) remaining_space -= cw else: bits = chunk.split(canvas, w, h, rema...
parts = line.split(",")
parts = self._splitDirectives(line)
def _handleDirectives(self, line): line = line[1:].strip() parts = line.split(",") if parts[0].startswith('default'): n = int(parts[0].split()[1]) parts[0] = ' '.join(parts[0].split()[2:]) self.defaultDirectives[n] = parts else: for part in parts: self._handleDirective(part.strip())
n = int(parts[0].split()[1]) parts[0] = ' '.join(parts[0].split()[2:])
args = self._splitArgs(parts[0]) n = int(args[1]) parts[0] = ' '.join(args[2:])
def _handleDirectives(self, line): line = line[1:].strip() parts = line.split(",") if parts[0].startswith('default'): n = int(parts[0].split()[1]) parts[0] = ' '.join(parts[0].split()[2:]) self.defaultDirectives[n] = parts else: for part in parts: self._handleDirective(part.strip())
parts = directive.split()
parts = self._splitArgs(directive)
def _handleDirective(self, directive): parts = directive.split() if not parts: return # warn maybe word = parts[0] self._directives_used_in_this_line.add(word) handler = getattr(self, '_handleDirective_%s' % word, self._handleUnknownDirective) handler(parts)
word = part.split()[0]
word = self._splitArgs(part)[0]
def _handleText(self, line): if not self._continuing: self._lastlineno += 1 if self._use_defaults: for part in self.defaultDirectives.get(self._lastlineno, []): word = part.split()[0] if word not in self._directives_used_in_this_line: self._handleDirective(part) line = line.rstrip().replace(r'\#', '#').replace(r'\\', '...
offset_record = ":02000004%04X\n" % high_ofs
offset_record = ":02000004%04X" % high_ofs
def writefile(self, f): """Write data to file f in HEX format. @return True if successful. """ if hasattr(f, "write"): fobj = f else: fobj = file(f, 'w')
fobj.write("%02X\n" % csum)
offset_record += "%02X\n" % csum
def writefile(self, f): """Write data to file f in HEX format. @return True if successful. """ if hasattr(f, "write"): fobj = f else: fobj = file(f, 'w')
def test_init_form_file(self):
def test_init_from_file(self):
def test_init_form_file(self): #FOLD01 ih = intelhex.IntelHex(self.f) for addr in xrange(len(bin8)): expected = bin8[addr] actual = ih[addr] self.assertEqual(expected, actual, "Data different at address %x (%x != %x)" % (addr, expected, actual))
sys.exit(hex2bin(fin, fout))
sys.exit(hex2bin(fin, fout, start, end, size, pad))
#/def hex2bin
if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']:
if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY'] or self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE']:
def determine_mode(self): if self.config['GENERAL']['PARENT_PROXY']: if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: try: host = self.client_head_obj.get_param_values('Host') if host: if host[0] in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode()...
host = self.client_head_obj.get_param_values('Host') if host: if host[0] in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode()
if self.config['GENERAL']['PARENT_SKIP_FOR_INTERNAL'] and self.can_connect(): self.move_to_www_mode()
def determine_mode(self): if self.config['GENERAL']['PARENT_PROXY']: if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: try: host = self.client_head_obj.get_param_values('Host') if host: if host[0] in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode()...
self.move_to_proxy_mode()
host = self.client_head_obj.get_param_values('Host') if host: if host[0] in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode()
def determine_mode(self): if self.config['GENERAL']['PARENT_PROXY']: if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: try: host = self.client_head_obj.get_param_values('Host') if host: if host[0] in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode()...
conf['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] makeInt(conf['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'], 'DIRECT_CONNECT_IF_POSSIBLE')
conf['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] = makeInt(conf['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'], 'DIRECT_CONNECT_IF_POSSIBLE')
def arrange(conf): #----------------------------------------------- # GENERAL conf['GENERAL']['PARENT_PROXY'] # If we do not use PARENT_PROXY then there are some items we just don't need: if conf['GENERAL']['PARENT_PROXY']: conf['GENERAL']['AVAILABLE_PROXY_LIST'] = string.split(conf['GENERAL']['PARENT_PROXY']) conf['...
res[section_name][string.strip(parts[0])] = string.strip(parts[1])
res[section_name][string.strip(parts[0])] = string.strip(string.join(parts[1:], ':'))
def read_config(fname): res = {} buf = open(fname).readlines() for line in buf: workingLine = string.strip(line) if workingLine: if workingLine[0] != '#': if workingLine[0] == '[' and workingLine[-1] == ']': section_name = string.strip(workingLine[1:-1]) if section_name: res[section_name] = {} else: parts = string.spl...
if self.mode_undecided: self.determine_mode() self.mode_undecided = 0
def run_client_loop(self): try: res = select.select([self.client_socket.fileno()], [], [], 0.0) except (socket.error, select.error, ValueError): thread.exit() if res[0]: try: socket_data = self.client_socket.recv(4096) except: socket_data = '' self.logger.log('*** Exception in client recv() happend.\n')
try: if self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] and self.can_connect(): self.move_to_www_mode() else: rs, rsp = self.client_head_obj.get_http_server() if rs in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() else: self.move_to_proxy_mode() except KeyError:
rs, rsp = self.client_head_obj.get_http_server() if rs in self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY']: self.move_to_www_mode() elif self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] and self.can_connect(rs, rsp): self.move_to_www_mode() else:
def determine_mode(self): if self.config['GENERAL']['PARENT_PROXY']: if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY'] or self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE']: try: if self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] and self.can_connect(): self.move_to_www_mode() else: rs, rsp = self.client...
def can_connect(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) rs, rsp = self.client_head_obj.get_http_server() s.connect((rs, rsp)) s.close() return True except: return False
def can_connect(self, rs, rsp): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) res = s.connect_ex((rs, rsp)) s.close() return not res
def can_connect(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) rs, rsp = self.client_head_obj.get_http_server() s.connect((rs, rsp)) s.close() return True except: return False
def send_client_header(self):
def proxy_send_client_header(self):
def send_client_header(self): self.logger.log('*** Sending client request header to remote server...') ok = self.client_head_obj.send(self.rserver_socket) if ok: self.client_header_sent = 1 self.logger.log('Done.\n') else: self.rserver_socket_closed = 1 self.logger.log('Failed.\n')
def send_client_header(self):
def www_send_client_header(self):
def send_client_header(self): if self.client_head_obj.get_http_method() == 'CONNECT': self.client_header_sent = 1 else: self.logger.log('*** Sending client request header to remote server...') ok = self.client_head_obj.send(self.rserver_socket) if ok: self.client_header_sent = 1 self.logger.log('Done.\n') else: self.rs...
if self.config['GENERAL']['PARENT_SKIP_FOR_INTERNAL'] and self.can_connect():
if self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE'] and self.can_connect():
def determine_mode(self): if self.config['GENERAL']['PARENT_PROXY']: if self.config['GENERAL']['HOSTS_TO_BYPASS_PARENT_PROXY'] or self.config['GENERAL']['DIRECT_CONNECT_IF_POSSIBLE']: try: if self.config['GENERAL']['PARENT_SKIP_FOR_INTERNAL'] and self.can_connect(): self.move_to_www_mode() else: host = self.client_head...
getpass = getpass.getpass
password_prompt = getpass.getpass
def __init__(self, config): self.config = config self.MyHost = '' self.ListenPort = self.config['GENERAL']['LISTEN_PORT'] self.sigLock = thread.allocate_lock() # For locking in the sigHandler self.monLock = thread.allocate_lock() # For keeping the monitor thread sane self.watchUpstream = 0 self.monitor = None if not se...
getpass = win32console.getpass
password_prompt = win32console.getpass
def __init__(self, config): self.config = config self.MyHost = '' self.ListenPort = self.config['GENERAL']['LISTEN_PORT'] self.sigLock = thread.allocate_lock() # For locking in the sigHandler self.monLock = thread.allocate_lock() # For keeping the monitor thread sane self.watchUpstream = 0 self.monitor = None if not se...
getpass = getpass.getpass self.config['NTLM_AUTH']['PASSWORD'] = getpass('Your NT password to be used:')
password_prompt = getpass.getpass self.config['NTLM_AUTH']['PASSWORD'] = password_prompt('Your NT password to be used:')
def __init__(self, config): self.config = config self.MyHost = '' self.ListenPort = self.config['GENERAL']['LISTEN_PORT'] self.sigLock = thread.allocate_lock() # For locking in the sigHandler self.monLock = thread.allocate_lock() # For keeping the monitor thread sane self.watchUpstream = 0 self.monitor = None if not se...
mod = self.store
if self.page == 0: mod = self.store
def add_entry (self, it): mod = self.store
for i in self.vars: print i.get_text () utils.cmd ('insert into pesci values(?,?,?,?,?,?,?)', id, self.vars[0].get_text (), self.vars[1].get_text (), self.vars[2].get_text (), self.vars[3].get_text (), self.vars[4].get_text (), self.vars[5].get_text ()) self.update_status (dbwindow.NotifyType.ADD, _("Row aggiunta (ID...
utils.cmd ('insert into pesci values(?,?,?,?,?,?,?)', id, self.vars[0].get_text (), self.vars[1].get_text (), self.vars[2].get_text (), self.vars[3].get_text (), self.vars[4].get_text (), self.vars[5].get_text ()) self.update_status (dbwindow.NotifyType.ADD, _("Row aggiunta (ID: %d)") % id) elif self.page == 1: self.s...
def add_entry (self, it): mod = self.store
('Aiuto', None, '_Aiuto', None, 'Aiuto...', 'aiuto_apri'),
('Help', None, '_Aiuto', None, 'Aiuto...', 'aiuto_apri'),
def create_menu(self): w = [ ('Acquario', None, '_Acquario'), ('Calcoli', None, '_Calcoli', '<control>C', 'Calcoli...', 'calcoli_apri'), ('Vasche', None, '_Vasche', '<control>V', 'Vasche...', 'vasca_apri'), ('Test', None, '_Test', '<control>T', 'Test', 'test_apri'), ('Pesci', None, '_Pesci', '<control>P', 'Pes...
<menuitem action='Aiuto'/>
<menuitem action='Help'/>
def create_menu(self): w = [ ('Acquario', None, '_Acquario'), ('Calcoli', None, '_Calcoli', '<control>C', 'Calcoli...', 'calcoli_apri'), ('Vasche', None, '_Vasche', '<control>V', 'Vasche...', 'vasca_apri'), ('Test', None, '_Test', '<control>T', 'Test', 'test_apri'), ('Pesci', None, '_Pesci', '<control>P', 'Pes...
print "limite", window.axis.xaxis.xlim
window.axis.autoscale_view () limite_sup += 2 limite_inf -= 2 print limite_sup, limite_inf print window.axis.set_ylim (limite_inf, limite_sup)
def plot (self, values): window = gtk.Window () window.set_title (_("PyAcqua - Grafico")) window.set_size_request (800, 600) window.figure = Figure ()#figsize=(6,4), dpi=72) window.axis = window.figure.add_subplot (111) window.canvas = FigureCanvasGTK(window.figure) sw = gtk.ScrolledWindow () sw.set_policy (gtk.POL...
def exit (self, widget, window):
def exit (self, widget, window, unz=None): if unz: window = unz
def exit (self, widget, window): window.hide () window.destroy ()
self.fert_store.clear() self.filt_store.clear() cur.execute('select * from fertilizzante') for i in cur.fetchall(): self.fert_store.append([i[0], i[1], i[2], i[3], i[4]]) cur.execute('select * from filtro') for i in cur.fetchall(): self.filt_store.append([i[0], i[1], i[2]])
def refresh(self, widget): impostazioni.refresh() con = sqlite.connect(os.path.join('Data', 'db')) cur = con.cursor() cur.execute('select * from test') for x in cur.fetchall(): if x[1] < float(impostazioni.minph): self.ph.set_label('Ph basso') if x[1] > float(impostazioni.maxph): self.ph.set_label('Ph alto') else: s...
print "ok" print ">> matplotlib.use ('GTKAgg')",
def check_iterator (self, mod, it): # TODO: implementare i valori ideali if it == None: return checks = impostazioni.get_collection (mod.get_value (it, 16)) if checks == None: return keys = ('ph', 'kh', 'gh', 'no2', 'no3', 'con', 'am', 'fe', 'ra', 'fo', 'cal', 'mag', 'den') x = 0 for i in keys: if checks.has_key (...
print "ok" print ">> Setting chart to True (if you are pietro this doesn't work :P)",
def check_iterator (self, mod, it): # TODO: implementare i valori ideali if it == None: return checks = impostazioni.get_collection (mod.get_value (it, 16)) if checks == None: return keys = ('ph', 'kh', 'gh', 'no2', 'no3', 'con', 'am', 'fe', 'ra', 'fo', 'cal', 'mag', 'den') x = 0 for i in keys: if checks.has_key (...
doc = parse (os.path.join (utils.HOME_DIR, "pyacqua.xml"))
try: doc = parse (os.path.join (utils.HOME_DIR, "pyacqua.xml")) except: print "pyacqua.xml not found.. using default values" return
def Load (self): doc = parse (os.path.join (utils.HOME_DIR, "pyacqua.xml")) if doc.documentElement.tagName == "pyacqua": # Seems valid for node in doc.documentElement.childNodes: if node.nodeName == "values": self.parseValues (node) if node.nodeName == "preferences": self.parsePreferences (node)
self.context_id = self.main_db.create_context (1, 7, [_('Id'), _('Vasca'), _('Data'), _('Tipo'), _('Nome'), _('Quantita'), _('Prossima volta'), _('Note')],
self.context_id = self.main_db.create_context (1, 7, self.col_lst,
def bind_context (self): lst = gtk.ListStore (int, str, str, str, str, str, str, str) self.context_id = self.main_db.create_context (1, 7, [_('Id'), _('Vasca'), _('Data'), _('Tipo'), _('Nome'), _('Quantita'), _('Prossima volta'), _('Note')], [utils.Combo (), utils.DataButton (), utils.Combo ([_("Fertilizzante"), _("Fi...