rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if e.errno == errno.EBADF: | (err, message) = e.args if err == errno.EBADF: | def remove_pending_socket(socket): with self.send_pending_lock: self.send_sockets_pending.remove(sock) |
if e.errno == errno.ENOTCONN: | if err == errno.ENOTCONN: | def testing_thread(self): log.debug("Starting test thread.") self.tests_started = time.time() data_recv = {} while not self.terminated: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("waiting f... |
if e.errno == errno.ECONNRESET: | (err, message) = e.args if err == errno.ECONNRESET: | def testing_thread(self): log.debug("Starting test thread.") self.tests_started = time.time() data_recv = {} while not self.terminated: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("waiting f... |
if e.errno == errno.ECONNRESET: | if err == errno.ECONNRESET: | def testing_thread(self): log.debug("Starting test thread.") self.tests_started = time.time() data_recv = {} while not self.terminated: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("waiting f... |
filename = filename[:3] | filename = filename[:-3] | def list_import(self, filename): """ Import exit list from filename. Supports CSV and JSON exports, optionally gzipped. """ if filename.endswith(".gz"): infile = gzip.open(filename, "rb") filename = filename[:3] else: infile = open(filename, "rb") |
self.guard_cache.remove(router.guard.idhex) | try: self.guard_cache.remove(router.guard.idhex) except ValueError: pass | def closeCallback(sport): self.stream_remove(source_port = sport) |
out.writerow([ip, self.idhex, self.nickname, self.last_tested, True, self.exit_policy(), list(self.working_ports), list(self.failed_ports)]) | out.writerow([ip self.idhex, self.nickname, self.last_tested, not self.stale, self.exit_policy(), list(self.working_ports), list(self.failed_ports)]) | def export_csv(self, out): """ Export record in CSV format, given a Python csv.writer instance. """ # If actual_ip is set, it differs from router.ip (advertised ExitAddress). ip = self.actual_ip if self.actual_ip else self.ip out.writerow([ip, self.idhex, self.nickname, self.last_tested, True, self.exit_policy(), list... |
self.tests_completed / ((time.time() - self.tests_started) / 60), | self.tests_completed / ((time.time() - self.tests_started) / 60.0), | def completed_test(self, router): """ Close test circuit associated with router. Restore associated guard to guard_cache. """ router.circuit_successes += 1 router.guard.guard_successes += 1 self.test_cleanup(router) self.tests_completed += 1 |
log.info("Joining test threads.") for cond in (self.send_recv_cond, self.send_pending_cond, | if self.test_thread: log.info("Joining test threads.") for cond in (self.send_recv_cond, self.send_pending_cond, | def close(self): """ Close the connection to the Tor control port. """ self.terminated = True log.info("Joining test threads.") # Notify any sleeping threads. for cond in (self.send_recv_cond, self.send_pending_cond, self.pending_circuit_cond): with cond: cond.notify() self.test_thread.join() self.circuit_thread.join()... |
with cond: cond.notify() self.test_thread.join() self.circuit_thread.join() self.listen_thread.join() self.stream_thread.join() log.info("All threads joined. Closing Tor controller connection.") | with cond: cond.notify() self.test_thread.join() self.circuit_thread.join() self.listen_thread.join() self.stream_thread.join() log.info("All threads joined.") log.info("Closing Tor controller connection.") | def close(self): """ Close the connection to the Tor control port. """ self.terminated = True log.info("Joining test threads.") # Notify any sleeping threads. for cond in (self.send_recv_cond, self.send_pending_cond, self.pending_circuit_cond): with cond: cond.notify() self.test_thread.join() self.circuit_thread.join()... |
log.debug("Closing test sockets.") for sock in self.test_bind_sockets: sock.close() | if self.test_bind_sockets: log.debug("Closing test sockets.") for sock in self.test_bind_sockets: sock.close() | def close(self): """ Close the connection to the Tor control port. """ self.terminated = True log.info("Joining test threads.") # Notify any sleeping threads. for cond in (self.send_recv_cond, self.send_pending_cond, self.pending_circuit_cond): with cond: cond.notify() self.test_thread.join() self.circuit_thread.join()... |
return struct.unpack(">I", socket.inet_aton(struct))[0] | return struct.unpack(">I", inet_aton(string))[0] | def ip_from_string(string): return struct.unpack(">I", socket.inet_aton(struct))[0] |
except select.error as (err, strerror): if err == errno.EBADF: | except select.error, e: if e[0] == errno.EBADF: | def remove_pending_socket(socket): with self.send_pending_lock: self.send_sockets_pending.remove(sock) |
elif err != errno.EINTR: | elif e[0] != errno.EINTR: | def remove_pending_socket(socket): with self.send_pending_lock: self.send_sockets_pending.remove(sock) |
log.error("select() error: %s", err) | log.error("select() error: %s", e[1]) | def remove_pending_socket(socket): with self.send_pending_lock: self.send_sockets_pending.remove(sock) |
except select.error as (err, strerror): | except select.error, e: (err, strerror) = e | def listen_thread(self): """ Thread that waits for new connections from the Tor network. """ log.debug("Starting listen thread.") listen_set = set() for sock in self.test_bind_sockets: ip, port = sock.getsockname() # LISTEN OK. Is 20 too large of a backlog? Testing will tell. sock.listen(20) listen_set.add(sock) |
except IOError as (errno, strerror): | except IOError, e: (errno, strerror) = e | def export_csv(self, gzip = False): """ Export current router cache in CSV format. See data-spec for more information on export formats. """ try: if gzip: csv_file = gzip.open(config.csv_export_file + ".gz", "w") else: csv_file = open(config.csv_export_file, "w") out = csv.writer(csv_file, dialect = csv.excel) |
self.retry_soon(self, router) | self.retry_soon(router) | def retry_later(self, router): """ Indicate to the scheduler that the controller was not able to complete a stream test due to a possibly temporary failure, and that it should retry at a longer interval than retry_soon. """ # Default behavior is to use the retry_soon behavior unless # implemented otherwise. self.retry_... |
pass | log.debug("%d pending circuits, %d running circuits.", len(self.pending_circuits), len(self.circuits)) | def print_stats(self): pass |
return set(ready[:(available_pending - len(retry_list))]) | retry | return set(ready[:(available_pending - len(retry))]) | retry | def fetch_next_tests(self): control = self.controller |
log.debug("%d pending circuits, %d running circuits.", len(self.pending_circuits), len(self.circuits)) | def print_stats(self): TestScheduler.print_stats(self) with self.pending_circuit_cond: self.pending_circuit_cond.notify() #log.debug("new_router_lock.locked(): %s", self.new_router_lock.locked()) log.debug("%d pending new tests, %d pending retries.", len(self.router_list), len(self.retry_routers)) log.debug("%d pending... | |
self.working_ports = [] self.failed_ports = [] | self.working_ports = set() self.failed_ports = set() | def __init__(self, *args, **kwargs): _OldRouterClass.__init__(self, *args, **kwargs) self.actual_ip = None self.last_tested = 0 # 0 indicates the router is as yet untested self.last_test_length = 0 self.working_ports = [] self.failed_ports = [] self.circuit = None # Router's current circuit ID, if any. self.gua... |
self.working_ports, self.failed_ports]) | list(self.working_ports), list(self.failed_ports)]) | def export_csv(self, out): """ Export record in CSV format, given a Python csv.writer instance. """ # If actual_ip is set, it differs from router.ip (advertised ExitAddress). ip = self.actual_ip if self.actual_ip else self.ip out.writerow([ip, self.idhex, self.nickname, self.last_tested, True, self.exit_policy(), self... |
test_length_average = None | test_average_len = None tests = 0 | def test_thread_func(self): log.debug("Starting test thread...") test_length_average = None |
exit = self.test_queue.get() log.debug("Pulled off %s for test.", exit.idhex) self.exit_test(exit) if test_length_average is None: test_length_average = router.last_test_length else: test_length_average = (test_length_average + exit.last_test_length) / 2.0 log.debug("%s: test completed in %f sec (%f average).", exit.ni... | if test_average_len is None: test_average_len = exit.last_test_length else: test_average_len = (test_average_len + exit.last_test_length) / 2.0 log.debug("%s: test completed in %f sec (%f average).", exit.nickname, exit.last_test_length, test_average_len) log.debug("%s: %s working, %s failed", exit.nickname, exit.worki... | def test_thread_func(self): log.debug("Starting test thread...") test_length_average = None |
test_ports = [] | test_ports = set() | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
log.debug("Setting up test to port %d.", port) | log.debug("(%s, %d): Listening.", router.nickname, port) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
test_ports.append(port) | test_ports.add(port) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
log.debug("%s: select() timeout (accept/SOCKS stage)!", router.nickname) | log.debug("%s: select() timeout (accept/SOCKS stage)! %d sockets remain", router.nickname, len(pending_sockets)) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
recv_sockets.append(recv_sock) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... | |
peer_ip, ignore = recv_sock.getpeername() ignore, listen_port = recv_sock.getsockname() log.debug("%s: accepted connection from %s on port %d.", router.nickname, peer_ip, listen_port) | try: peer_ip, ignore = recv_sock.getpeername() ignore, listen_port = recv_sock.getsockname() recv_sockets.append(recv_sock) log.debug("%s: accepted connection from %s on port %d.", router.nickname, peer_ip, listen_port) except socket.error, e: if e.errno == errno.ENOTCONN: log.error("Got ENOTCONN after accept(2)... | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
router.failed_ports.append(s.getpeername()[1]) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... | |
select.select(recv_sockets, send_sockets, [], 10) | select.select(recv_sockets, send_sockets, [], 20) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
continue | continue else: raise | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
ip, port = read_sock.getsockname() | try: ip, source_port = read_sock.getpeername() my_ip, port = read_sock.getsockname() except socket.error, e: if e.errno == errno.ENOTCONN: continue | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
log.debug("%s: port %d test succeeded!", router.nickname, port) | log.debug("(%s, %d): test succeeded!", router.nickname, port) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
router.working_ports.append(port) | router.working_ports.add(port) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
log.debug("%s: port %d test failed! Expected %s, got %s.", | log.debug("(%s, %d): test failed! Expected %s, got %s.", | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
router.failed_ports.append(port) | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... | |
log.debug("%s: writing test data to port %d.", router.nickname, port) write_sock.send(test_data[port]) | log.debug("(%s, %d): writing test data.", router.nickname, port) try: write_sock.send(test_data[port]) except socket.error, e: if e.errno == errno.ECONNRESET: log.debug("(%s, %d): Connection reset by peer.", router.nickname, port) send_sockets.remove(write_sock) continue | def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] listen_sockets = [] self.test_exit = route... |
out = csv.writer(csv_file) | out = csv.writer(csv_file, dialect = csv.excel) | def export_csv(self, gzip = False): try: if gzip: csv_file = gzip.open("bel.csv.gz", "w") else: csv_file = open("bel.csv", "w") out = csv.writer(csv_file) for router in self.routers.itervalues(): router.export_csv(csvout) |
router.export_csv(csvout) | router.export_csv(out) | def export_csv(self, gzip = False): try: if gzip: csv_file = gzip.open("bel.csv.gz", "w") else: csv_file = open("bel.csv", "w") out = csv.writer(csv_file) for router in self.routers.itervalues(): router.export_csv(csvout) |
log.debug("%d:%d streams open", len(self.streams_by_id), len(self.streams_by_source)) | def test_schedule_thread(self): log.debug("Starting test schedule thread.") | |
exitp = "" for exitline in self.exitpolicy: exitp += str(exitline) + ";" return exitp | return ";".join(map(str, self.exitpolicy)) | def exit_policy(self): """ Collapse the router's ExitPolicy into one line, with each rule delimited by a semicolon (';'). """ exitp = "" for exitline in self.exitpolicy: exitp += str(exitline) + ";" |
router.unreachable = False if router.retry: self.circuit_retry_success_count += 1 router.retry = False log.verbose1("Retry for %s successful after %d failures (%d/%d %.2f%%)!", router.nickname, router.circuit_failures, self.circuit_retry_success_count, self.circuit_fail_count + self.circuit_retry_success_count, 100 *... | router.unreachable = False if router.retry: self.circuit_retry_success_count += 1 router.retry = False log.verbose1("Retry for %s successful after %d failures (%d/%d %.2f%%)!", router.nickname, router.circuit_failures, self.circuit_retry_success_count, self.circuit_fail_count + self.circuit_retry_success_count, 100 *... | def circ_built(self, event): circ_id = event.circ_id with self.pending_circuit_cond: if circ_id in self.pending_circuits: router = self.pending_circuits[circ_id] del self.pending_circuits[circ_id] # Notify scheduler thread that we have # completed building a circuit and we could # need to pre-build more. self.pending_c... |
def cleanup_and_notify(router, retry = False): if router.current_test and router.current_test.circ_id == circ_id: self.controller.test_cleanup(router, circ_failed = True) self.pending_circuit_cond.notify() if retry: self.retry_soon(router) | def cleanup_and_notify(router, retry = False): # Cleanup test results and notify the circuit thread. if router.current_test and router.current_test.circ_id == circ_id: self.controller.test_cleanup(router, circ_failed = True) self.pending_circuit_cond.notify() if retry: # Append this router to our failure list, and let... | |
cleanup_and_notify(router, retry = True) | retry = True | def cleanup_and_notify(router, retry = False): # Cleanup test results and notify the circuit thread. if router.current_test and router.current_test.circ_id == circ_id: self.controller.test_cleanup(router, circ_failed = True) self.pending_circuit_cond.notify() if retry: # Append this router to our failure list, and let... |
cleanup_and_notify(router, retry = True) | if router.current_test and router.current_test.circ_id == circ_id: self.controller.test_cleanup(router, circ_failed = True) self.pending_circuit_cond.notify() if retry: self.retry_soon(router) | def cleanup_and_notify(router, retry = False): # Cleanup test results and notify the circuit thread. if router.current_test and router.current_test.circ_id == circ_id: self.controller.test_cleanup(router, circ_failed = True) self.pending_circuit_cond.notify() if retry: # Append this router to our failure list, and let... |
out.writerow([ip | out.writerow([ip, | def export_csv(self, out): """ Export record in CSV format, given a Python csv.writer instance. """ # If actual_ip is set, it differs from router.ip (advertised ExitAddress). ip = self.actual_ip if self.actual_ip else self.ip |
log.debug("Updating router record for %s.", router) | log.debug("Updating router record for %s.", rid) | def new_desc_event(self, event): for rid in event.idlist: ns = self.conn.get_network_status("id/" + rid)[0] |
log.debug("Adding new router record for %s.", router) | log.debug("Adding new router record for %s.", rid) | def new_desc_event(self, event): for rid in event.idlist: ns = self.conn.get_network_status("id/" + rid)[0] |
control.start("torbeltes") | control.start("torbeltest") | def torbel_start(host, port): log.info("TorBEL v%s starting.", __version__) control = Controller(host, port) try: control.start("torbeltes") except socket.error, e: if "Connection refused" in e.args: log.error("Connection refused! Is Tor control port available?") return 1 except TorCtl.ErrorReply, e: log.error("Conn... |
def addMessage(self, name, message): | def addMessage(self, name, message=None): | def addMessage(self, name, message): """Adds a new error code with a default error message.""" self.__messages[name] = message |
self.deffnm = kwargs.setdefault('deffnm', 'md') | self.deffnm = kwargs.pop('deffnm', 'md') | def __init__(self, molecule=None, top=None, struct=None, simulation=None, filename=None, **kwargs): """Prepare all input files. :Arguments: *molecule* name of the molecule for which the hydration free energy is to be computed (as in the gromacs topology) [REQUIRED] *top* topology [REQUIRED] *struct* solvated and equil... |
if force or numpy.any(numpy.array( [len(xvgs) for (lambdas,xvgs) in self.results.xvg.values()]) == 0): | if force or not self.has_dVdl(): | def analyze(self, c0=1.0, force=False, autosave=True): """Extract dV/dl from output and calculate dG by TI. |
logger.info("Hydration free energy %g kJ/mol", self.results.DeltaA.total) | logger.info("DeltaA0 = -(DeltaA_coul + DeltaA_vdw) + DeltaA_stdstate") for component, value in self.results.DeltaA.items(): logger.info("%s solvation free energy (%s) %g kJ/mol", self.solvent_type.capitalize(), component, value) | def analyze(self, c0=1.0, force=False, autosave=True): """Extract dV/dl from output and calculate dG by TI. |
if payload_string == self.hashed_payload and self.options.check: self.check_positives = self.check_positives + 1 | def get_url_payload(self, url, payload, query_string, attack_payload=None): """ Attack the given url with the given payload """ options = self.options self._ongoing_attacks = {} | |
vectors = self.total_vectors - self.check_positives total_payloads = self.check_positives + vectors + self.special_vectors | vectors = self.total_vectors - self.false_positives if vectors < 0: vectors = 0 else: vectors = vectors total_payloads = self.false_positives + vectors + self.special_vectors | def print_results(self): """ Print results from an attack. """ |
print "Checkers:", self.check_positives , "|" , "Vectors:" , vectors , "|" , "Specials:" , self.special_vectors | print "Checkers:", self.false_positives, "|" , "Vectors:" , vectors , "|" , "Specials:" , self.special_vectors | def print_results(self): """ Print results from an attack. """ |
self.report(curl_handle.info()) | def _report_attack_success(self, curl_handle, dest_url, payload, attack_vector): """ report success of an attack """ options = self.options self.report("[+] \033[1;33mTrying:\033[1;m " + dest_url.strip(), 'info') | |
msg.obj.append(("create", struct.pack("!I", 1))) msg.obj.append(("exclusive", struct.pack("!I", 1))) | msg.message.append(("create", struct.pack("!I", 1))) msg.message.append(("exclusive", struct.pack("!I", 1))) | def add_host(self, ip, mac): """ @type ip: str @type mac: str @raises ValueError: @raises OmapiError: @raises socket.error: """ # FIXME: test whether this code works msg = OmapiMessage.open("host") msg.obj.append(("create", struct.pack("!I", 1))) msg.obj.append(("exclusive", struct.pack("!I", 1))) msg.obj.append(("hard... |
if response.opcode != OMAPI_OP_NOTIFY: | if response.opcode != OMAPI_OP_UPDATE: | def add_host(self, ip, mac): """ @type ip: str @type mac: str @raises ValueError: @raises OmapiError: @raises socket.error: """ # FIXME: test whether this code works msg = OmapiMessage.open("host") msg.obj.append(("create", struct.pack("!I", 1))) msg.obj.append(("exclusive", struct.pack("!I", 1))) msg.obj.append(("hard... |
if response.opcode != OMAPI_OP_NOTIFY: | if response.opcode != OMAPI_OP_STATUS: | def del_host(self, mac): """ @type mac: str @raises ValueError: @raises OmapiError: @raises socket.error: """ # FIXME: test whether this code works msg = OmapiMessage.open("host") msg.obj.append(("hardware-address", pack_mac(mac))) msg.obj.append(("hardware-type", struct.pack("!I", 1))) response = self.query_server(msg... |
rv.extensions.update(load_extensions(extensions)) | rv.extensions.update(load_extensions(rv, extensions)) | def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, extensions=missing, optimized=missing, undefined=... |
ZeroDivisionError: int(eger)? division or modulo by zero | ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero | def test(): tmpl.render(fail=lambda: 1 / 0) |
return tmpl.render() == '1|1' | assert tmpl.render() == '1|1', tmpl.render() | def test_abs(self): tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''') return tmpl.render() == '1|1' |
source = generate(source, self, name, filename, defer_init=defer_init) | source = self._generate(source, name, filename, defer_init=defer_init) | def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated fil... |
return compile(source, filename, 'exec') | return self._compile(source, filename) | def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated fil... |
c = compile(code, _encode_filename(filename), 'exec') | c = self._compile(code, _encode_filename(filename)) | def write_file(filename, data, mode): if zip: info = ZipInfo(filename) info.external_attr = 0755 << 16L zip_file.writestr(info, data) else: f = open(os.path.join(target, filename), mode) try: f.write(data) finally: f.close() |
def chain_frames(self): """Chains the frames. Requires ctypes or the debugsupport extension.""" | def chain_frames(self): """Chains the frames. Requires ctypes or the debugsupport extension.""" prev_tb = None for tb in self.frames: if prev_tb is not None: prev_tb.tb_next = tb prev_tb = tb prev_tb.tb_next = None | |
return self.exc_type, self.exc_value, self.frames[0].tb | tb = self.frames[0] if type(tb) is not TracebackType: tb = tb.tb return self.exc_type, self.exc_value, tb | def standard_exc_info(self): """Standard python exc_info for re-raising""" return self.exc_type, self.exc_value, self.frames[0].tb |
frames.append(TracebackFrameProxy(tb)) | frames.append(make_frame_proxy(tb)) | def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in xrange(initial_skip): if tb is not None: tb = tb.tb_next init... |
traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames) if tb_set_next is not None: traceback.chain_frames() return traceback | return ProcessedTraceback(exc_info[0], exc_info[1], frames) | def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in xrange(initial_skip): if tb is not None: tb = tb.tb_next init... |
any python traceback object. | any python traceback object. Do not attempt to use this on non cpython interpreters | def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. """ import ctypes from types import TracebackType # figure out side of _Py_ssize_t if hasattr(ctypes.pythonapi, 'Py_InitModu... |
try: from jinja2._debugsupport import tb_set_next except ImportError: | tb_set_next = None if tproxy is None: | def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Trace... |
tb_set_next = _init_ugly_crap() except: tb_set_next = None del _init_ugly_crap | from jinja2._debugsupport import tb_set_next except ImportError: try: tb_set_next = _init_ugly_crap() except: pass del _init_ugly_crap | def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Trace... |
__ne__ = Undefined._fail_with_undefined_error if sys.version_info >= (3, 0): __bool__ = __nonzero__ del __nonzero__ | __ne__ = __bool__ = Undefined._fail_with_undefined_error | def __unicode__(self): if self._undefined_hint is None: if self._undefined_obj is missing: return u'{{ %s }}' % self._undefined_name return '{{ no such element: %s[%r] }}' % ( object_type_repr(self._undefined_obj), self._undefined_name ) return u'{{ undefined value printed: %s }}' % self._undefined_hint |
if object.__basicsize__ != ctypes.sizeof(_PyObject): | if hasattr(sys, 'getobjects'): | def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. """ import ctypes from types import TracebackType # figure out side of _Py_ssize_t if hasattr(ctypes.pythonapi, 'Py_InitModu... |
return self.environment.getattr(self.node.as_const(eval_ctx), arg) | return self.environment.getattr(self.node.as_const(eval_ctx), self.attr) | def as_const(self, eval_ctx=None): if self.ctx != 'load': raise Impossible() try: eval_ctx = get_eval_context(self, eval_ctx) return self.environment.getattr(self.node.as_const(eval_ctx), arg) except: raise Impossible() |
self.assert_equal(env.from_string('{{ missing|list }}').render, '[]') self.assert_equal(env.from_string('{{ missing is not defined }}').render, 'True') | self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]') self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True') | def test_default_undefined(self): env = Environment(undefined=Undefined) self.assert_equal(env.from_string('{{ missing }}').render(), u'') self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render) self.assert_equal(env.from_string('{{ missing|list }}').render, '[]') self.assert_equal(env.fro... |
def test_debug_undefined(): | def test_debug_undefined(self): | def test_debug_undefined(): env = Environment(undefined=DebugUndefined) self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}') self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render()) self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]') u'[]' self... |
env.from_string('{{ missing.attribute }}').render()) | env.from_string('{{ missing.attribute }}').render) | def test_debug_undefined(): env = Environment(undefined=DebugUndefined) self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}') self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render()) self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]') u'[]' self... |
u'[]' self.assert_equal(env.from_string('{{ missing is not defined }}').render, 'True') | self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True') | def test_debug_undefined(): env = Environment(undefined=DebugUndefined) self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}') self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render()) self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]') u'[]' self... |
u"{{ no such element: int['missing'] }}") | u"{{ no such element: int object['missing'] }}") | def test_debug_undefined(): env = Environment(undefined=DebugUndefined) self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}') self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render()) self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]') u'[]' self... |
def test_strict_undefined(): | def test_strict_undefined(self): | def test_strict_undefined(): env = Environment(undefined=StrictUndefined) self.assert_raises(UndefinedError, env.from_string('{{ missing }}').render) self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render) self.assert_raises(UndefinedError, env.from_string('{{ missing|list }}').render) sel... |
assert_raises(UndefinedError, t.render, var=0) | self.assert_raises(UndefinedError, t.render, var=0) | def test_indexing_gives_undefined(self): t = Template("{{ var[42].foo }}") assert_raises(UndefinedError, t.render, var=0) |
Environment().getattr(None, 'split') | Environment().getattr(None, 'split')() | def test_none_gives_proper_error(self): try: Environment().getattr(None, 'split') except UndefinedError, e: assert e.message == "None has no attribute 'split'" else: assert False, 'expected exception' |
assert e.message == "None has no attribute 'split'" | assert e.message == "'None' has no attribute 'split'" | def test_none_gives_proper_error(self): try: Environment().getattr(None, 'split') except UndefinedError, e: assert e.message == "None has no attribute 'split'" else: assert False, 'expected exception' |
Undefined(obj=42, name='upper') | Undefined(obj=42, name='upper')() | def test_object_repr(self): try: Undefined(obj=42, name='upper') except UndefinedError, e: assert e.message == "'int' object has no attribute 'upper'" else: assert False, 'expected exception' |
assert e.message == "'int' object has no attribute 'upper'" | assert e.message == "'int object' has no attribute 'upper'" | def test_object_repr(self): try: Undefined(obj=42, name='upper') except UndefinedError, e: assert e.message == "'int' object has no attribute 'upper'" else: assert False, 'expected exception' |
:class:`EvalContext` for nodes in the :attr:`body`. | :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`. | def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) return Markup(self.expr.as_const(eval_ctx)) |
def _set_tb_next(self, next): | @property def tb_next(self): return self._tb_next def set_next(self, next): | def _set_tb_next(self, next): if tb_set_next is not None: tb_set_next(self.tb, next and next.tb or None) self._tb_next = next |
def _get_tb_next(self): return self._tb_next tb_next = property(_get_tb_next, _set_tb_next) del _get_tb_next, _set_tb_next | def _set_tb_next(self, next): if tb_set_next is not None: tb_set_next(self.tb, next and next.tb or None) self._tb_next = next | |
prev_tb._tb_next = tb | prev_tb.set_next(tb) | def __init__(self, exc_type, exc_value, frames): assert frames, 'no frames for this traceback?' self.exc_type = exc_type self.exc_value = exc_value self.frames = frames |
prev_tb._tb_next = None | prev_tb.set_next(None) | def __init__(self, exc_type, exc_value, frames): assert frames, 'no frames for this traceback?' self.exc_type = exc_type self.exc_value = exc_value self.frames = frames |
[r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*%s)' % ( | [r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % ( | def __init__(self, environment): # shortcuts c = lambda x: re.compile(x, re.M | re.S) e = re.escape |
load_extensions(self, [extension]) | self.extensions.update(load_extensions(self, [extension])) | def add_extension(self, extension): """Adds an extension after the environment was created. |
self.writeline('return ') | def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" self.writeline('return ') if frame.eval_ctx.volatile: self.write('(Markup(concat(%s)) if context.eval_ctx' '.autoescape else concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))... | |
self.write('(Markup(concat(%s)) if context.eval_ctx' '.autoescape else concat(%s))' % (frame.buffer, frame.buffer)) | self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() | def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" self.writeline('return ') if frame.eval_ctx.volatile: self.write('(Markup(concat(%s)) if context.eval_ctx' '.autoescape else concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))... |
self.write('Markup(concat(%s))' % frame.buffer) else: self.write('concat(%s)' % frame.buffer) | self.writeline('return Markup(concat(%s))' % frame.buffer) else: self.writeline('return concat(%s)' % frame.buffer) | def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" self.writeline('return ') if frame.eval_ctx.volatile: self.write('(Markup(concat(%s)) if context.eval_ctx' '.autoescape else concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.