text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ For each incoming message, decode the JSON, evaluate expression, encode as JSON and write that to the output file. """
for line in self.incoming: message = loads(line) result = self._evaluate(message) if result is self._SKIP: continue self.output.write(dumps(result, cls=_DatetimeJSONEncoder) + b"\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _evaluate(self, message): """ Evaluate the expression with the given Python object in its locals. @param message: A decoded JSON input. @return: The resulting object. """
return eval( self.code, globals(), { "J": message, "timedelta": timedelta, "datetime": datetime, "SKIP": self._SKIP})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond(self): """Process the current request. From :pep:`333`: The start_response callable must not actually transmit the response headers. Instead, it must store them for the server or gateway to transmit only after the first iteration of the application return value that yields a NON-EMPTY string, or upon the application's first invocation of the write() callable. """
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in filter(None, response): if not isinstance(chunk, six.binary_type): raise ValueError('WSGI Applications must yield bytes') self.write(chunk) finally: # Send headers if not already sent self.req.ensure_headers_sent() if hasattr(response, 'close'): response.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_status(status): """Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are restricted to code points in the "latin-1" set. """
if six.PY2: return status if not isinstance(status, str): raise TypeError('WSGI response status is not of type str.') return status.encode('ISO-8859-1')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, chunk): """WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application). """
if not self.started_response: raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if rbo is not None and chunklen > rbo: if not self.req.sent_headers: # Whew. We can send a 500 to the client. self.req.simple_response( '500 Internal Server Error', 'The requested resource returned more bytes than the ' 'declared Content-Length.', ) else: # Dang. We have probably already sent data. Truncate the chunk # to fit (so the client doesn't hang) and raise an error later. chunk = chunk[:rbo] self.req.ensure_headers_sent() self.req.write(chunk) if rbo is not None: rbo -= chunklen if rbo < 0: raise ValueError( 'Response body exceeds the declared Content-Length.', )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, b): """Write bytes to buffer."""
self._checkClosed() if isinstance(b, str): raise TypeError("can't write str to binary stream") with self._write_lock: self._write_buf.extend(b) self._flush_unlocked() return len(b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, data): """Sendall for non-blocking sockets."""
bytes_sent = 0 data_mv = memoryview(data) payload_size = len(data_mv) while bytes_sent < payload_size: try: bytes_sent += self.send( data_mv[bytes_sent:bytes_sent + SOCK_WRITE_BLOCKSIZE], ) except socket.error as e: if e.args[0] not in errors.socket_errors_nonblocking: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Write all data from buffer to socket and reset write buffer."""
if self._wbuf: buffer = ''.join(self._wbuf) self._wbuf = [] self.write(buffer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_wsgi_bind_location(bind_addr_string): """Convert bind address string to a BindLocation."""
# try and match for an IP/hostname and port match = six.moves.urllib.parse.urlparse('//{}'.format(bind_addr_string)) try: addr = match.hostname port = match.port if addr is not None or port is not None: return TCPSocket(addr, port) except ValueError: pass # else, assume a UNIX socket path # if the string begins with an @ symbol, use an abstract socket if bind_addr_string.startswith('@'): return AbstractSocket(bind_addr_string[1:]) return UnixSocket(path=bind_addr_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Create a new Cheroot instance with arguments from the command line."""
parser = argparse.ArgumentParser( description='Start an instance of the Cheroot WSGI/HTTP server.', ) for arg, spec in _arg_spec.items(): parser.add_argument(arg, **spec) raw_args = parser.parse_args() # ensure cwd in sys.path '' in sys.path or sys.path.insert(0, '') # create a server based on the arguments provided raw_args._wsgi_app.server(raw_args).safe_start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def server_args(self, parsed_args): """Return keyword args for Server class."""
args = { arg: value for arg, value in vars(parsed_args).items() if not arg.startswith('_') and value is not None } args.update(vars(self)) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plat_specific_errors(*errnames): """Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names. """
missing_attr = set([None, ]) unique_nums = set(getattr(errno, k, None) for k in errnames) return list(unique_nums - missing_attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assert_ssl_exc_contains(exc, *msgs): """Check whether SSL exception contains either of messages provided."""
if len(msgs) < 1: raise TypeError( '_assert_ssl_exc_contains() requires ' 'at least one message to be passed.', ) err_msg_lower = str(exc).lower() return any(m.lower() in err_msg_lower for m in msgs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def env_dn_dict(self, env_prefix, cert_value): """Return a dict of WSGI environment variables for a client cert DN. E.g. SSL_CLIENT_S_DN_CN, SSL_CLIENT_S_DN_C, etc. See SSL_CLIENT_S_DN_x509 at https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#envvars. """
if not cert_value: return {} env = {} for rdn in cert_value: for attr_name, val in rdn: attr_code = self.CERT_KEY_TO_LDAP_CODE.get(attr_name) if attr_code: env['%s_%s' % (env_prefix, attr_code)] = val return env
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_call(self, is_reader, call, *args, **kwargs): """Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """
start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. # Ref: https://stackoverflow.com/a/5133568/595220 time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return b'' errnum = e.args[0] if is_reader and errnum in errors.socket_errors_to_ignore: return b'' raise socket.error(errnum) except SSL.Error as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return b'' thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise errors.NoSSLError() raise errors.FatalSSLAlert(*e.args) if time.time() - start > self.ssl_timeout: raise socket.timeout('timed out')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendall(self, *args, **kwargs): """Send whole message to the socket."""
return self._safe_call( False, super(SSLFileobjectMixin, self).sendall, *args, **kwargs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, sock): """Wrap and return the given socket."""
if self.context is None: self.context = self.get_context() conn = SSLConnection(self.context, sock) self._environ = self.get_environ() return conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context(self): """Return an SSL.Context from self attributes."""
# See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environ(self): """Return WSGI environ entries to be merged into each request."""
ssl_environ = { 'HTTPS': 'on', # pyOpenSSL doesn't provide access to any of these AFAICT # 'SSL_PROTOCOL': 'SSLv2', # SSL_CIPHER string The cipher specification name # SSL_VERSION_INTERFACE string The mod_ssl program version # SSL_VERSION_LIBRARY string The OpenSSL program version } if self.certificate: # Server certificate attributes cert = open(self.certificate, 'rb').read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ssl_environ.update({ 'SSL_SERVER_M_VERSION': cert.get_version(), 'SSL_SERVER_M_SERIAL': cert.get_serial_number(), # 'SSL_SERVER_V_START': # Validity of server's certificate (start time), # 'SSL_SERVER_V_END': # Validity of server's certificate (end time), }) for prefix, dn in [ ('I', cert.get_issuer()), ('S', cert.get_subject()), ]: # X509Name objects don't seem to have a way to get the # complete DN string. Use str() and slice it instead, # because str(dn) == "<X509Name object '/C=US/ST=...'>" dnstr = str(dn)[18:-2] wsgikey = 'SSL_SERVER_%s_DN' % prefix ssl_environ[wsgikey] = dnstr # The DN should be of the form: /k1=v1/k2=v2, but we must allow # for any value to contain slashes itself (in a URL). while dnstr: pos = dnstr.rfind('=') dnstr, value = dnstr[:pos], dnstr[pos + 1:] pos = dnstr.rfind('/') dnstr, key = dnstr[:pos], dnstr[pos + 1:] if key and value: wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key) ssl_environ[wsgikey] = value return ssl_environ
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ssl_adapter_class(name='builtin'): """Return an SSL adapter class for the given name."""
adapter = ssl_adapters[name.lower()] if isinstance(adapter, six.string_types): last_dot = adapter.rfind('.') attr_name = adapter[last_dot + 1:] mod_path = adapter[:last_dot] try: mod = sys.modules[mod_path] if mod is None: raise KeyError() except KeyError: # The last [''] is important. mod = __import__(mod_path, globals(), locals(), ['']) # Let an AttributeError propagate outward. try: adapter = getattr(mod, attr_name) except AttributeError: raise AttributeError("'%s' object has no attribute '%s'" % (mod_path, attr_name)) return adapter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_trailer_lines(self): """Read HTTP headers and yield them. Returns: Generator: yields CRLF separated lines. """
if not self.closed: raise ValueError( 'Cannot read trailers until the request body has been read.', ) while True: line = self.rfile.readline() if not line: # No more data--illegal end of headers raise ValueError('Illegal end of headers.') self.bytes_read += len(line) if self.maxlen and self.bytes_read > self.maxlen: raise IOError('Request Entity Too Large') if line == CRLF: # Normal end of headers break if not line.endswith(CRLF): raise ValueError('HTTP requires CRLF terminators') yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_headers(self): """Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this. """
hkeys = [key.lower() for key, value in self.outheaders] status = int(self.status[:3]) if status == 413: # Request Entity Too Large. Close conn to avoid garbage. self.close_connection = True elif b'content-length' not in hkeys: # "All 1xx (informational), 204 (no content), # and 304 (not modified) responses MUST NOT # include a message-body." So no point chunking. if status < 200 or status in (204, 205, 304): pass else: needs_chunked = ( self.response_protocol == 'HTTP/1.1' and self.method != b'HEAD' ) if needs_chunked: # Use the chunked transfer-coding self.chunked_write = True self.outheaders.append((b'Transfer-Encoding', b'chunked')) else: # Closing the conn is the only way to determine len. self.close_connection = True if b'connection' not in hkeys: if self.response_protocol == 'HTTP/1.1': # Both server and client are HTTP/1.1 or better if self.close_connection: self.outheaders.append((b'Connection', b'close')) else: # Server and/or client are HTTP/1.0 if not self.close_connection: self.outheaders.append((b'Connection', b'Keep-Alive')) if (not self.close_connection) and (not self.chunked_read): # Read any remaining request body data on the socket. # "If an origin server receives a request that does not include an # Expect request-header field with the "100-continue" expectation, # the request includes a request body, and the server responds # with a final status code before reading the entire request body # from the transport connection, then the server SHOULD NOT close # the transport connection until it has read the entire request, # or until the client closes the connection. Otherwise, the client # might not reliably receive the response message. However, this # requirement is not be construed as preventing a server from # defending itself against denial-of-service attacks, or from # badly broken client implementations." remaining = getattr(self.rfile, 'remaining', 0) if remaining > 0: self.rfile.read(remaining) if b'date' not in hkeys: self.outheaders.append(( b'Date', email.utils.formatdate(usegmt=True).encode('ISO-8859-1'), )) if b'server' not in hkeys: self.outheaders.append(( b'Server', self.server.server_name.encode('ISO-8859-1'), )) proto = self.server.protocol.encode('ascii') buf = [proto + SPACE + self.status + CRLF] for k, v in self.outheaders: buf.append(k + COLON + SPACE + v + CRLF) buf.append(CRLF) self.conn.wfile.write(EMPTY.join(buf))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conditional_error(self, req, response): """Respond with an error. Don't bother writing if a response has already started being written. """
if not req or req.sent_headers: return try: req.simple_response(response) except errors.FatalSSLAlert: pass except errors.NoSSLError: self._handle_no_ssl(req)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_peer_creds(self): # LRU cached on per-instance basis """Return the username and group tuple of the peercreds if available. Raises: NotImplementedError: in case of unsupported OS RuntimeError: in case of UID/GID lookup unsupported or disabled """
if not IS_UID_GID_RESOLVABLE: raise NotImplementedError( 'UID/GID lookup is unavailable under current platform. ' 'It can only be done under UNIX-like OS ' 'but not under the Google App Engine', ) elif not self.peercreds_resolve_enabled: raise RuntimeError( 'UID/GID lookup is disabled within this server', ) user = pwd.getpwuid(self.peer_uid).pw_name # [0] group = grp.getgrgid(self.peer_gid).gr_name # [0] return user, group
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _close_kernel_socket(self): """Close kernel socket in outdated Python versions. On old Python versions, Python's socket module does NOT call close on the kernel socket when you call socket.close(). We do so manually here because we want this server to send a FIN TCP segment immediately. Note this must be called *before* calling socket.close(), because the latter drops its reference to the kernel socket. """
if six.PY2 and hasattr(self.socket, '_sock'): self.socket._sock.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_stats(self): """Reset server stat counters.."""
self._start_time = None self._run_time = 0 self.stats = { 'Enabled': False, 'Bind Address': lambda s: repr(self.bind_addr), 'Run time': lambda s: (not s['Enabled']) and -1 or self.runtime(), 'Accepts': 0, 'Accepts/sec': lambda s: s['Accepts'] / self.runtime(), 'Queue': lambda s: getattr(self.requests, 'qsize', None), 'Threads': lambda s: len(getattr(self.requests, '_threads', [])), 'Threads Idle': lambda s: getattr(self.requests, 'idle', None), 'Socket Errors': 0, 'Requests': lambda s: (not s['Enabled']) and -1 or sum( [w['Requests'](w) for w in s['Worker Threads'].values()], 0, ), 'Bytes Read': lambda s: (not s['Enabled']) and -1 or sum( [w['Bytes Read'](w) for w in s['Worker Threads'].values()], 0, ), 'Bytes Written': lambda s: (not s['Enabled']) and -1 or sum( [w['Bytes Written'](w) for w in s['Worker Threads'].values()], 0, ), 'Work Time': lambda s: (not s['Enabled']) and -1 or sum( [w['Work Time'](w) for w in s['Worker Threads'].values()], 0, ), 'Read Throughput': lambda s: (not s['Enabled']) and -1 or sum( [w['Bytes Read'](w) / (w['Work Time'](w) or 1e-6) for w in s['Worker Threads'].values()], 0, ), 'Write Throughput': lambda s: (not s['Enabled']) and -1 or sum( [w['Bytes Written'](w) / (w['Work Time'](w) or 1e-6) for w in s['Worker Threads'].values()], 0, ), 'Worker Threads': {}, } logging.statistics['Cheroot HTTPServer %d' % id(self)] = self.stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runtime(self): """Return server uptime."""
if self._start_time is None: return self._run_time else: return self._run_time + (time.time() - self._start_time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_addr(self, value): """Set the interface on which to listen for connections."""
if isinstance(value, tuple) and value[0] in ('', None): # Despite the socket module docs, using '' does not # allow AI_PASSIVE to work. Passing None instead # returns '0.0.0.0' like we want. In other words: # host AI_PASSIVE result # '' Y 192.168.x.y # '' N 192.168.x.y # None Y 0.0.0.0 # None N 127.0.0.1 # But since you can get the same effect with an explicit # '0.0.0.0', we deny both the empty string and None as values. raise ValueError( "Host values of '' or None are not allowed. " "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead " 'to listen on all active interfaces.', ) self._bind_addr = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_start(self): """Run the server forever, and stop it cleanly on exit."""
try: self.start() except (KeyboardInterrupt, IOError): # The time.sleep call might raise # "IOError: [Errno 4] Interrupted function call" on KBInt. self.error_log('Keyboard Interrupt: shutting down') self.stop() raise except SystemExit: self.error_log('SystemExit raised: shutting down') self.stop() raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self): """Prepare server to serving requests. It binds a socket's port, setups the socket to ``listen()`` and does other preparing things. """
self._interrupt = None if self.software is None: self.software = '%s Server' % self.version # Select the appropriate socket self.socket = None msg = 'No socket could be created' if os.getenv('LISTEN_PID', None): # systemd socket activation self.socket = socket.fromfd(3, socket.AF_INET, socket.SOCK_STREAM) elif isinstance(self.bind_addr, six.string_types): # AF_UNIX socket try: self.bind_unix_socket(self.bind_addr) except socket.error as serr: msg = '%s -- (%s: %s)' % (msg, self.bind_addr, serr) six.raise_from(socket.error(msg), serr) else: # AF_INET or AF_INET6 socket # Get the correct address family for our host (allows IPv6 # addresses) host, port = self.bind_addr try: info = socket.getaddrinfo( host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE, ) except socket.gaierror: sock_type = socket.AF_INET bind_addr = self.bind_addr if ':' in host: sock_type = socket.AF_INET6 bind_addr = bind_addr + (0, 0) info = [(sock_type, socket.SOCK_STREAM, 0, '', bind_addr)] for res in info: af, socktype, proto, canonname, sa = res try: self.bind(af, socktype, proto) break except socket.error as serr: msg = '%s -- (%s: %s)' % (msg, sa, serr) if self.socket: self.socket.close() self.socket = None if not self.socket: raise socket.error(msg) # Timeout so KeyboardInterrupt can be caught on Win32 self.socket.settimeout(1) self.socket.listen(self.request_queue_size) # Create worker threads self.requests.start() self.ready = True self._start_time = time.time()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error_log(self, msg='', level=20, traceback=False): """Write error message to log. Args: msg (str): error message level (int): logging level traceback (bool): add traceback to output or not """
# Override this in subclasses as desired sys.stderr.write(msg + '\n') sys.stderr.flush() if traceback: tblines = traceback_.format_exc() sys.stderr.write(tblines) sys.stderr.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter): """Create and prepare the socket object."""
sock = socket.socket(family, type, proto) prevent_socket_inheritance(sock) host, port = bind_addr[:2] IS_EPHEMERAL_PORT = port == 0 if not (IS_WINDOWS or IS_EPHEMERAL_PORT): """Enable SO_REUSEADDR for the current socket. Skip for Windows (has different semantics) or ephemeral ports (can steal ports from others). Refs: * https://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx * https://github.com/cherrypy/cheroot/issues/114 * https://gavv.github.io/blog/ephemeral-port-reuse/ """ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if nodelay and not isinstance(bind_addr, str): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if ssl_adapter is not None: sock = ssl_adapter.bind(sock) # If listening on the IPV6 any address ('::' = IN6ADDR_ANY), # activate dual-stack. See # https://github.com/cherrypy/cherrypy/issues/871. listening_ipv6 = ( hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and host in ('::', '::0', '::0.0.0.0') ) if listening_ipv6: try: sock.setsockopt( socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0, ) except (AttributeError, socket.error): # Apparently, the socket option is not available in # this machine's TCP stack pass return sock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_real_bind_addr(socket_): """Retrieve actual bind addr from bound socket."""
# FIXME: keep requested bind_addr separate real bound_addr (port # is different in case of ephemeral port 0) bind_addr = socket_.getsockname() if socket_.family in ( # Windows doesn't have socket.AF_UNIX, so not using it in check socket.AF_INET, socket.AF_INET6, ): """UNIX domain sockets are strings or bytes. In case of bytes with a leading null-byte it's an abstract socket. """ return bind_addr[:2] return bind_addr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interrupt(self, interrupt): """Perform the shutdown of this server and save the exception."""
self._interrupt = True self.stop() self._interrupt = interrupt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Process incoming HTTP connections. Retrieves incoming connections from thread pool. """
self.server.stats['Worker Threads'][self.getName()] = self.stats try: self.ready = True while True: conn = self.server.requests.get() if conn is _SHUTDOWNREQUEST: return self.conn = conn if self.server.stats['Enabled']: self.start_time = time.time() try: conn.communicate() finally: conn.close() if self.server.stats['Enabled']: self.requests_seen += self.conn.requests_seen self.bytes_read += self.conn.rfile.bytes_read self.bytes_written += self.conn.wfile.bytes_written self.work_time += time.time() - self.start_time self.start_time = None self.conn = None except (KeyboardInterrupt, SystemExit) as ex: self.server.interrupt = ex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, obj): """Put request into queue. Args: obj (cheroot.server.HTTPConnection): HTTP connection waiting to be processed """
self._queue.put(obj, block=True, timeout=self._queue_put_timeout) if obj is _SHUTDOWNREQUEST: return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self, timeout=5): """Terminate all worker threads. Args: timeout (int): time to wait for threads to stop gracefully """
# Must shut down threads here so the code that calls # this method can know when all threads are stopped. for worker in self._threads: self._queue.put(_SHUTDOWNREQUEST) # Don't join currentThread (when stop is called inside a request). current = threading.currentThread() if timeout is not None and timeout >= 0: endtime = time.time() + timeout while self._threads: worker = self._threads.pop() if worker is not current and worker.isAlive(): try: if timeout is None or timeout < 0: worker.join() else: remaining_time = endtime - time.time() if remaining_time > 0: worker.join(remaining_time) if worker.isAlive(): # We exhausted the timeout. # Forcibly shut down the socket. c = worker.conn if c and not c.rfile.closed: try: c.socket.shutdown(socket.SHUT_RD) except TypeError: # pyOpenSSL sockets don't take an arg c.socket.shutdown() worker.join() except ( AssertionError, # Ignore repeated Ctrl-C. # See # https://github.com/cherrypy/cherrypy/issues/691. KeyboardInterrupt, ): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_last_child_with_lineno(node): """ Return the last direct child of `node` that has a lineno attribute, or None if `node` has no such children. Almost all node._field lists are sorted by the order in which they appear in source code. For some nodes however, we have to skip some fields that either don't have line numbers (e.g., "ctx" and "names") or that are in the wrong position (e.g., "decorator_list" and "returns"). Then we choose the first field (i.e., the field with the highest line number) that actually contains a node. If it contains a list of nodes, we return the last one. """
ignored_fields = set(['ctx', 'decorator_list', 'names', 'returns']) fields = node._fields # The fields of ast.Call are in the wrong order. if isinstance(node, ast.Call): fields = ('func', 'args', 'starargs', 'keywords', 'kwargs') for name in reversed(fields): if name in ignored_fields: continue try: last_field = getattr(node, name) except AttributeError: continue # Ignore non-AST objects like "is_async", "level" and "nl". if isinstance(last_field, ast.AST): return last_field elif isinstance(last_field, list) and last_field: return last_field[-1] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_line_number(node): """Estimate last line number of the given AST node. The estimate is based on the line number of the last descendant of `node` that has a lineno attribute. Therefore, it underestimates the size of code ending with, e.g., multiline strings and comments. When traversing the tree, we may see a mix of nodes with line numbers and nodes without line numbers. We therefore, store the maximum line number seen so far and report it at the end. A more accurate (but also slower to compute) estimate would traverse all children, instead of just the last one, since choosing the last one may lead to a path that ends with a node without line number. """
max_lineno = node.lineno while True: last_child = _get_last_child_with_lineno(node) if last_child is None: return max_lineno else: try: max_lineno = max(max_lineno, last_child.lineno) except AttributeError: pass node = last_child
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_eval(node, default): """ Safely evaluate the Boolean expression under the given AST node. Substitute `default` for all sub-expressions that cannot be evaluated (because variables or functions are undefined). We could use eval() to evaluate more sub-expressions. However, this function is not safe for arbitrary Python code. Even after overwriting the "__builtins__" dictionary, the original dictionary can be restored (https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). """
if isinstance(node, ast.BoolOp): results = [_safe_eval(value, default) for value in node.values] if isinstance(node.op, ast.And): return all(results) else: return any(results) elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): return not _safe_eval(node.operand, not default) else: try: return ast.literal_eval(node) except ValueError: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_modules(paths, toplevel=True): """Take files from the command line even if they don't end with .py."""
modules = [] for path in paths: path = os.path.abspath(path) if toplevel and path.endswith('.pyc'): sys.exit('.pyc files are not supported: {0}'.format(path)) if os.path.isfile(path) and (path.endswith('.py') or toplevel): modules.append(path) elif os.path.isdir(path): subpaths = [ os.path.join(path, filename) for filename in sorted(os.listdir(path))] modules.extend(get_modules(subpaths, toplevel=False)) elif toplevel: sys.exit('Error: {0} could not be found.'.format(path)) return modules
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_unused_code(self, min_confidence=0, sort_by_size=False): """ Return ordered list of unused Item objects. """
if not 0 <= min_confidence <= 100: raise ValueError('min_confidence must be between 0 and 100.') def by_name(item): return (item.filename.lower(), item.first_lineno) def by_size(item): return (item.size,) + by_name(item) unused_code = (self.unused_attrs + self.unused_classes + self.unused_funcs + self.unused_imports + self.unused_props + self.unused_vars + self.unreachable_code) confidently_unused = [obj for obj in unused_code if obj.confidence >= min_confidence] return sorted(confidently_unused, key=by_size if sort_by_size else by_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self, min_confidence=0, sort_by_size=False, make_whitelist=False): """ Print ordered list of Item objects to stdout. """
for item in self.get_unused_code( min_confidence=min_confidence, sort_by_size=sort_by_size): print(item.get_whitelist_string() if make_whitelist else item.get_report(add_size=sort_by_size)) self.found_dead_code_or_error = True return self.found_dead_code_or_error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_ast_list(self, ast_list): """ Find unreachable nodes in the given sequence of ast nodes. """
for index, node in enumerate(ast_list): if isinstance(node, (ast.Break, ast.Continue, ast.Raise, ast.Return)): try: first_unreachable_node = ast_list[index + 1] except IndexError: continue class_name = node.__class__.__name__.lower() self._define( self.unreachable_code, class_name, first_unreachable_node, last_node=ast_list[-1], message="unreachable code after '{class_name}'".format( **locals()), confidence=100) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_occurrences(project, resource, offset, unsure=False, resources=None, in_hierarchy=False, task_handle=taskhandle.NullTaskHandle()): """Return a list of `Location`\s If `unsure` is `True`, possible matches are returned, too. You can use `Location.unsure` to see which are unsure occurrences. `resources` can be a list of `rope.base.resource.File`\s that should be searched for occurrences; if `None` all python files in the project are searched. """
name = worder.get_name_at(resource, offset) this_pymodule = project.get_pymodule(resource) primary, pyname = rope.base.evaluate.eval_location2( this_pymodule, offset) def is_match(occurrence): return unsure finder = occurrences.create_finder( project, name, pyname, unsure=is_match, in_hierarchy=in_hierarchy, instance=primary) if resources is None: resources = project.get_python_files() job_set = task_handle.create_jobset('Finding Occurrences', count=len(resources)) return _find_locations(finder, resources, job_set)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_implementations(project, resource, offset, resources=None, task_handle=taskhandle.NullTaskHandle()): """Find the places a given method is overridden. Finds the places a method is implemented. Returns a list of `Location`\s. """
name = worder.get_name_at(resource, offset) this_pymodule = project.get_pymodule(resource) pyname = rope.base.evaluate.eval_location(this_pymodule, offset) if pyname is not None: pyobject = pyname.get_object() if not isinstance(pyobject, rope.base.pyobjects.PyFunction) or \ pyobject.get_kind() != 'method': raise exceptions.BadIdentifierError('Not a method!') else: raise exceptions.BadIdentifierError('Cannot resolve the identifier!') def is_defined(occurrence): if not occurrence.is_defined(): return False def not_self(occurrence): if occurrence.get_pyname().get_object() == pyname.get_object(): return False filters = [is_defined, not_self, occurrences.InHierarchyFilter(pyname, True)] finder = occurrences.Finder(project, name, filters=filters) if resources is None: resources = project.get_python_files() job_set = task_handle.create_jobset('Finding Implementations', count=len(resources)) return _find_locations(finder, resources, job_set)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_errors(project, resource): """Find possible bad name and attribute accesses It returns a list of `Error`\s. """
pymodule = project.get_pymodule(resource) finder = _BadAccessFinder(pymodule) ast.walk(pymodule.get_ast(), finder) return finder.errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, pyobject): """Transform a `PyObject` to textual form"""
if pyobject is None: return ('none',) object_type = type(pyobject) try: method = getattr(self, object_type.__name__ + '_to_textual') return method(pyobject) except AttributeError: return ('unknown',)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, textual): """Transform an object from textual form to `PyObject`"""
if textual is None: return None type = textual[0] try: method = getattr(self, type + '_to_pyobject') return method(textual) except AttributeError: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_patched_ast(source, sorted_children=False): """Adds ``region`` and ``sorted_children`` fields to nodes Adds ``sorted_children`` field only if `sorted_children` is True. """
return patch_ast(ast.parse(source), source, sorted_children)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_ast(node, source, sorted_children=False): """Patches the given node After calling, each node in `node` will have a new field named `region` that is a tuple containing the start and end offsets of the code that generated it. If `sorted_children` is true, a `sorted_children` field will be created for each node, too. It is a list containing child nodes as well as whitespaces and comments that occur between them. """
if hasattr(node, 'region'): return node walker = _PatchingASTWalker(source, children=sorted_children) ast.call_for_nodes(node, walker) return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_ast(patched_ast_node): """Extract source form a patched AST node with `sorted_children` field If the node is patched with sorted_children turned off you can use `node_region` function for obtaining code using module source code. """
result = [] for child in patched_ast_node.sorted_children: if isinstance(child, ast.AST): result.append(write_ast(child)) else: result.append(child) return ''.join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_parens(self, children, start, formats): """Changes `children` and returns new start"""
opens, closes = self._count_needed_parens(formats) old_end = self.source.offset new_end = None for i in range(closes): new_end = self.source.consume(')')[1] if new_end is not None: if self.children: children.append(self.source[old_end:new_end]) new_start = start for i in range(opens): new_start = self.source.rfind_token('(', 0, new_start) if new_start != start: if self.children: children.appendleft(self.source[new_start:start]) start = new_start return start
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _good_token(self, token, offset, start=None): """Checks whether consumed token is in comments"""
if start is None: start = self.offset try: comment_index = self.source.rindex('#', start, offset) except ValueError: return True try: new_line_index = self.source.rindex('\n', start, offset) except ValueError: return False return comment_index < new_line_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_block_start(lines, lineno, maximum_indents=80): """Approximate block start"""
pattern = get_block_start_patterns() for i in range(lineno, 0, -1): match = pattern.search(lines.get_line(i)) if match is not None and \ count_line_indents(lines.get_line(i)) <= maximum_indents: striped = match.string.lstrip() # Maybe we're in a list comprehension or generator expression if i > 1 and striped.startswith('if') or striped.startswith('for'): bracs = 0 for j in range(i, min(i + 5, lines.length() + 1)): for c in lines.get_line(j): if c == '#': break if c in '[(': bracs += 1 if c in ')]': bracs -= 1 if bracs < 0: break if bracs < 0: break if bracs < 0: continue return i return 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_logicals(self): """Should initialize _starts and _ends attributes"""
size = self.lines.length() + 1 self._starts = [None] * size self._ends = [None] * size for start, end in self._generate(self.lines): self._starts[start] = True self._ends[end] = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_move(project, resource, offset=None): """A factory for creating Move objects Based on `resource` and `offset`, return one of `MoveModule`, `MoveGlobal` or `MoveMethod` for performing move refactoring. """
if offset is None: return MoveModule(project, resource) this_pymodule = project.get_pymodule(resource) pyname = evaluate.eval_location(this_pymodule, offset) if pyname is not None: pyobject = pyname.get_object() if isinstance(pyobject, pyobjects.PyModule) or \ isinstance(pyobject, pyobjects.PyPackage): return MoveModule(project, pyobject.get_resource()) if isinstance(pyobject, pyobjects.PyFunction) and \ isinstance(pyobject.parent, pyobjects.PyClass): return MoveMethod(project, resource, offset) if isinstance(pyobject, pyobjects.PyDefinedObject) and \ isinstance(pyobject.parent, pyobjects.PyModule) or \ isinstance(pyname, pynames.AssignedName): return MoveGlobal(project, resource, offset) raise exceptions.RefactoringError( 'Move only works on global classes/functions/variables, modules and ' 'methods.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_changes(self, dest_attr, new_name=None, resources=None, task_handle=taskhandle.NullTaskHandle()): """Return the changes needed for this refactoring Parameters: - `dest_attr`: the name of the destination attribute - `new_name`: the name of the new method; if `None` uses the old name - `resources` can be a list of `rope.base.resources.File`\s to apply this refactoring on. If `None`, the restructuring will be applied to all python files. """
changes = ChangeSet('Moving method <%s>' % self.method_name) if resources is None: resources = self.project.get_python_files() if new_name is None: new_name = self.get_method_name() resource1, start1, end1, new_content1 = \ self._get_changes_made_by_old_class(dest_attr, new_name) collector1 = codeanalyze.ChangeCollector(resource1.read()) collector1.add_change(start1, end1, new_content1) resource2, start2, end2, new_content2 = \ self._get_changes_made_by_new_class(dest_attr, new_name) if resource1 == resource2: collector1.add_change(start2, end2, new_content2) else: collector2 = codeanalyze.ChangeCollector(resource2.read()) collector2.add_change(start2, end2, new_content2) result = collector2.get_changed() import_tools = importutils.ImportTools(self.project) new_imports = self._get_used_imports(import_tools) if new_imports: goal_pymodule = libutils.get_string_module( self.project, result, resource2) result = _add_imports_to_module( import_tools, goal_pymodule, new_imports) if resource2 in resources: changes.add_change(ChangeContents(resource2, result)) if resource1 in resources: changes.add_change(ChangeContents(resource1, collector1.get_changed())) return changes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_kind(self): """Get function type It returns one of 'function', 'method', 'staticmethod' or 'classmethod' strs. """
scope = self.parent.get_scope() if isinstance(self.parent, PyClass): for decorator in self.decorators: pyname = rope.base.evaluate.eval_node(scope, decorator) if pyname == rope.base.builtins.builtins['staticmethod']: return 'staticmethod' if pyname == rope.base.builtins.builtins['classmethod']: return 'classmethod' return 'method' return 'function'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk(node, walker): """Walk the syntax tree"""
method_name = '_' + node.__class__.__name__ method = getattr(walker, method_name, None) if method is not None: if isinstance(node, _ast.ImportFrom) and node.module is None: # In python < 2.7 ``node.module == ''`` for relative imports # but for python 2.7 it is None. Generalizing it to ''. node.module = '' return method(node) for child in get_child_nodes(node): walk(child, walker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_for_nodes(node, callback, recursive=False): """If callback returns `True` the child nodes are skipped"""
result = callback(node) if recursive and not result: for child in get_child_nodes(node): call_for_nodes(child, callback, recursive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _realpath(path): """Return the real path of `path` Is equivalent to ``realpath(abspath(expanduser(path)))``. Of the particular notice is the hack dealing with the unfortunate sitaution of running native-Windows python (os.name == 'nt') inside of Cygwin (abspath starts with '/'), which apparently normal os.path.realpath completely messes up. """
# there is a bug in cygwin for os.path.abspath() for abs paths if sys.platform == 'cygwin': if path[1:3] == ':\\': return path elif path[1:3] == ':/': path = "/cygdrive/" + path[0] + path[2:] return os.path.abspath(os.path.expanduser(path)) return os.path.realpath(os.path.abspath(os.path.expanduser(path)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_resource(self, resource_name): """Get a resource in a project. `resource_name` is the path of a resource in a project. It is the path of a resource relative to project root. Project root folder address is an empty string. If the resource does not exist a `exceptions.ResourceNotFound` exception would be raised. Use `get_file()` and `get_folder()` when you need to get nonexistent `Resource`\s. """
path = self._get_resource_path(resource_name) if not os.path.exists(path): raise exceptions.ResourceNotFoundError( 'Resource <%s> does not exist' % resource_name) elif os.path.isfile(path): return File(self, resource_name) elif os.path.isdir(path): return Folder(self, resource_name) else: raise exceptions.ResourceNotFoundError('Unknown resource ' + resource_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_module(self, name, folder=None): """Returns a `PyObject` if the module was found."""
# check if this is a builtin module pymod = self.pycore.builtin_module(name) if pymod is not None: return pymod module = self.find_module(name, folder) if module is None: raise ModuleNotFoundError('Module %s not found' % name) return self.pycore.resource_to_pyobject(module)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_source_folders(self): """Returns project source folders"""
if self.root is None: return [] result = list(self._custom_source_folders) result.extend(self.pycore._find_source_folders(self.root)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, folder): """Validate files and folders contained in this folder It validates all of the files and folders contained in this folder if some observers are interested in them. """
for observer in list(self.observers): observer.validate(folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do(self, changes, task_handle=taskhandle.NullTaskHandle()): """Apply the changes in a `ChangeSet` Most of the time you call this function for committing the changes for a refactoring. """
self.history.do(changes, task_handle=task_handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_module(self, modname, folder=None): """Returns a resource corresponding to the given module returns None if it can not be found """
for src in self.get_source_folders(): module = _find_module_in_folder(src, modname) if module is not None: return module for src in self.get_python_path_folders(): module = _find_module_in_folder(src, modname) if module is not None: return module if folder is not None: module = _find_module_in_folder(folder, modname) if module is not None: return module return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_python_files(self): """Returns all python files available in the project"""
return [resource for resource in self.get_files() if self.pycore.is_python_file(resource)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_objects(self): """Returns the list of objects passed as this parameter"""
return rope.base.oi.soi.get_passed_objects( self.pyfunction, self.index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_changes(self, *args, **kwds): """Get a project to changes dict"""
result = [] for project, refactoring in zip(self.projects, self.refactorings): args, kwds = self._resources_for_args(project, args, kwds) result.append((project, refactoring.get_changes(*args, **kwds))) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveit(func): """A decorator that caches the return value of a function"""
name = '_' + func.__name__ def _wrapper(self, *args, **kwds): if not hasattr(self, name): setattr(self, name, func(self, *args, **kwds)) return getattr(self, name) return _wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prevent_recursion(default): """A decorator that returns the return value of `default` in recursions"""
def decorator(func): name = '_calling_%s_' % func.__name__ def newfunc(self, *args, **kwds): if getattr(self, name, False): return default() setattr(self, name, True) try: return func(self, *args, **kwds) finally: setattr(self, name, False) return newfunc return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_exception(exception_class): """A decorator that ignores `exception_class` exceptions"""
def _decorator(func): def newfunc(*args, **kwds): try: return func(*args, **kwds) except exception_class: pass return newfunc return _decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecated(message=None): """A decorator for deprecated functions"""
def _decorator(func, message=message): if message is None: message = '%s is deprecated' % func.__name__ def newfunc(*args, **kwds): warnings.warn(message, DeprecationWarning, stacklevel=2) return func(*args, **kwds) return newfunc return _decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached(size): """A caching decorator based on parameter objects"""
def decorator(func): cached_func = _Cached(func, size) return lambda *a, **kw: cached_func(*a, **kw) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(str_or_obj): """Returns object from string"""
from rope.base.utils.pycompat import string_types if not isinstance(str_or_obj, string_types): return str_or_obj if '.' not in str_or_obj: str_or_obj += '.' mod_name, obj_name = str_or_obj.rsplit('.', 1) __import__(mod_name) mod = sys.modules[mod_name] return getattr(mod, obj_name) if obj_name else mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_primary_without_dot_start(self, offset): """It tries to find the undotted primary start It is different from `self._get_atom_start()` in that it follows function calls, too; such as in ``f(x)``. """
last_atom = offset offset = self._find_last_non_space_char(last_atom) while offset > 0 and self.code[offset] in ')]': last_atom = self._find_parens_start(offset) offset = self._find_last_non_space_char(last_atom - 1) if offset >= 0 and (self.code[offset] in '"\'})]' or self._is_id_char(offset)): atom_start = self._find_atom_start(offset) if not keyword.iskeyword(self.code[atom_start:offset + 1]): return atom_start return last_atom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_splitted_primary_before(self, offset): """returns expression, starting, starting_offset This function is used in `rope.codeassist.assist` function. """
if offset == 0: return ('', '', 0) end = offset - 1 word_start = self._find_atom_start(end) real_start = self._find_primary_start(end) if self.code[word_start:offset].strip() == '': word_start = end if self.code[end].isspace(): word_start = end if self.code[real_start:word_start].strip() == '': real_start = word_start if real_start == word_start == end and not self._is_id_char(end): return ('', '', offset) if real_start == word_start: return ('', self.raw[word_start:offset], word_start) else: if self.code[end] == '.': return (self.raw[real_start:end], '', offset) last_dot_position = word_start if self.code[word_start] != '.': last_dot_position = \ self._find_last_non_space_char(word_start - 1) last_char_position = \ self._find_last_non_space_char(last_dot_position - 1) if self.code[word_start].isspace(): word_start = offset return (self.raw[real_start:last_char_position + 1], self.raw[word_start:offset], word_start)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_inline(project, resource, offset): """Create a refactoring object for inlining Based on `resource` and `offset` it returns an instance of `InlineMethod`, `InlineVariable` or `InlineParameter`. """
pyname = _get_pyname(project, resource, offset) message = 'Inline refactoring should be performed on ' \ 'a method, local variable or parameter.' if pyname is None: raise rope.base.exceptions.RefactoringError(message) if isinstance(pyname, pynames.ImportedName): pyname = pyname._get_imported_pyname() if isinstance(pyname, pynames.AssignedName): return InlineVariable(project, resource, offset) if isinstance(pyname, pynames.ParameterName): return InlineParameter(project, resource, offset) if isinstance(pyname.get_object(), pyobjects.PyFunction): return InlineMethod(project, resource, offset) else: raise rope.base.exceptions.RefactoringError(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_imported_resource(self, context): """Get the imported resource Returns `None` if module was not found. """
if self.level == 0: return context.project.find_module( self.module_name, folder=context.folder) else: return context.project.find_relative_module( self.module_name, context.folder, self.level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_imported_module(self, context): """Get the imported `PyModule` Raises `rope.base.exceptions.ModuleNotFoundError` if module could not be found. """
if self.level == 0: return context.project.get_module( self.module_name, context.folder) else: return context.project.get_relative_module( self.module_name, context.folder, self.level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def code_assist(project, source_code, offset, resource=None, templates=None, maxfixes=1, later_locals=True): """Return python code completions as a list of `CodeAssistProposal`\s `resource` is a `rope.base.resources.Resource` object. If provided, relative imports are handled. `maxfixes` is the maximum number of errors to fix if the code has errors in it. If `later_locals` is `False` names defined in this scope and after this line is ignored. """
if templates is not None: warnings.warn('Codeassist no longer supports templates', DeprecationWarning, stacklevel=2) assist = _PythonCodeAssist( project, source_code, offset, resource=resource, maxfixes=maxfixes, later_locals=later_locals) return assist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starting_offset(source_code, offset): """Return the offset in which the completion should be inserted Usually code assist proposals should be inserted like:: completion = proposal.name result = (source_code[:starting_offset] + completion + source_code[offset:]) Where starting_offset is the offset returned by this function. """
word_finder = worder.Worder(source_code, True) expression, starting, starting_offset = \ word_finder.get_splitted_primary_before(offset) return starting_offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_doc(project, source_code, offset, resource=None, maxfixes=1): """Get the pydoc"""
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes) pyname = fixer.pyname_at(offset) if pyname is None: return None pyobject = pyname.get_object() return PyDocExtractor().get_doc(pyobject)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_calltip(project, source_code, offset, resource=None, maxfixes=1, ignore_unknown=False, remove_self=False): """Get the calltip of a function The format of the returned string is ``module_name.holding_scope_names.function_name(arguments)``. For classes `__init__()` and for normal objects `__call__()` function is used. Note that the offset is on the function itself *not* after the its open parenthesis. (Actually it used to be the other way but it was easily confused when string literals were involved. So I decided it is better for it not to try to be too clever when it cannot be clever enough). You can use a simple search like:: offset = source_code.rindex('(', 0, offset) - 1 to handle simple situations. If `ignore_unknown` is `True`, `None` is returned for functions without source-code like builtins and extensions. If `remove_self` is `True`, the first parameter whose name is self will be removed for methods. """
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes) pyname = fixer.pyname_at(offset) if pyname is None: return None pyobject = pyname.get_object() return PyDocExtractor().get_calltip(pyobject, ignore_unknown, remove_self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_canonical_path(project, resource, offset): """Get the canonical path to an object. Given the offset of the object, this returns a list of (name, name_type) tuples representing the canonical path to the object. For example, the 'x' in the following code: class Foo(object): def bar(self): class Qux(object): def mux(self, x): pass we will return: [('Foo', 'CLASS'), ('bar', 'FUNCTION'), ('Qux', 'CLASS'), ('mux', 'FUNCTION'), ('x', 'PARAMETER')] `resource` is a `rope.base.resources.Resource` object. `offset` is the offset of the pyname you want the path to. """
# Retrieve the PyName. pymod = project.get_pymodule(resource) pyname = rope.base.evaluate.eval_location(pymod, offset) # Now get the location of the definition and its containing scope. defmod, lineno = pyname.get_definition_location() if not defmod: return None scope = defmod.get_scope().get_inner_scope_for_line(lineno) # Start with the name of the object we're interested in. names = [] if isinstance(pyname, pynamesdef.ParameterName): names = [(worder.get_name_at(pymod.get_resource(), offset), 'PARAMETER') ] elif isinstance(pyname, pynamesdef.AssignedName): names = [(worder.get_name_at(pymod.get_resource(), offset), 'VARIABLE')] # Collect scope names. while scope.parent: if isinstance(scope, pyscopes.FunctionScope): scope_type = 'FUNCTION' elif isinstance(scope, pyscopes.ClassScope): scope_type = 'CLASS' else: scope_type = None names.append((scope.pyobject.get_name(), scope_type)) scope = scope.parent names.append((defmod.get_resource().real_path, 'MODULE')) names.reverse() return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted_proposals(proposals, scopepref=None, typepref=None): """Sort a list of proposals Return a sorted list of the given `CodeAssistProposal`\s. `scopepref` can be a list of proposal scopes. Defaults to ``['parameter_keyword', 'local', 'global', 'imported', 'attribute', 'builtin', 'keyword']``. `typepref` can be a list of proposal types. Defaults to ``['class', 'function', 'instance', 'module', None]``. (`None` stands for completions with no type like keywords.) """
sorter = _ProposalSorter(proposals, scopepref, typepref) return sorter.get_sorted_proposal_list()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starting_expression(source_code, offset): """Return the expression to complete"""
word_finder = worder.Worder(source_code, True) expression, starting, starting_offset = \ word_finder.get_splitted_primary_before(offset) if expression: return expression + '.' + starting return starting
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parameters(self): """The names of the parameters the function takes. Returns None if this completion is not a function. """
pyname = self.pyname if isinstance(pyname, pynames.ImportedName): pyname = pyname._get_imported_pyname() if isinstance(pyname, pynames.DefinedName): pyobject = pyname.get_object() if isinstance(pyobject, pyobjects.AbstractFunction): return pyobject.get_param_names()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_doc(self): """Get the proposed object's docstring. Returns None if it can not be get. """
if not self.pyname: return None pyobject = self.pyname.get_object() if not hasattr(pyobject, 'get_doc'): return None return self.pyname.get_object().get_doc()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default(self): """Get a string representation of a param's default value. Returns None if there is no default value for this param. """
definfo = functionutils.DefinitionInfo.read(self._function) for arg, default in definfo.args_with_defaults: if self.argname == arg: return default return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sorted_proposal_list(self): """Return a list of `CodeAssistProposal`"""
proposals = {} for proposal in self.proposals: proposals.setdefault(proposal.scope, []).append(proposal) result = [] for scope in self.scopepref: scope_proposals = proposals.get(scope, []) scope_proposals = [proposal for proposal in scope_proposals if proposal.type in self.typerank] scope_proposals.sort(key=self._proposal_key) result.extend(scope_proposals) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_prefs(prefs): """This function is called before opening the project"""
# Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_files()`. # Note that ``?`` and ``*`` match all characters but slashes. # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc' # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc' # '.svn': matches 'pkg/.svn' and all of its children # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o' # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o' prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git', '.tox'] # Specifies which files should be considered python files. It is # useful when you have scripts inside your project. Only files # ending with ``.py`` are considered to be python files by # default. # prefs['python_files'] = ['*.py'] # Custom source folders: By default rope searches the project # for finding source folders (folders that should be searched # for finding modules). You can add paths to that list. Note # that rope guesses project source folders correctly most of the # time; use this if you have any problems. # The folders should be relative to project root and use '/' for # separating folders regardless of the platform rope is running on. # 'src/my_source_folder' for instance. # prefs.add('source_folders', 'src') # You can extend python path for looking up modules # prefs.add('python_path', '~/python/') # Should rope save object information or not. prefs['save_objectdb'] = True prefs['compress_objectdb'] = False # If `True`, rope analyzes each module when it is being saved. prefs['automatic_soa'] = True # The depth of calls to follow in static object analysis prefs['soa_followed_calls'] = 0 # If `False` when running modules or unit tests "dynamic object # analysis" is turned off. This makes them much faster. prefs['perform_doa'] = True # Rope can check the validity of its object DB when running. prefs['validate_objectdb'] = True # How many undos to hold? prefs['max_history_items'] = 32 # Shows whether to save history across sessions. prefs['save_history'] = True prefs['compress_history'] = False # Set the number spaces used for indenting. According to # :PEP:`8`, it is best to use 4 spaces. Since most of rope's # unit-tests use 4 spaces it is more reliable, too. prefs['indent_size'] = 4 # Builtin and c-extension modules that are allowed to be imported # and inspected by rope. prefs['extension_modules'] = [] # Add all standard c-extensions to extension_modules list. prefs['import_dynload_stdmods'] = True # If `True` modules with syntax errors are considered to be empty. # The default value is `False`; When `False` syntax errors raise # `rope.base.exceptions.ModuleSyntaxError` exception. prefs['ignore_syntax_errors'] = False # If `True`, rope ignores unresolvable imports. Otherwise, they # appear in the importing namespace. prefs['ignore_bad_imports'] = False # If `True`, rope will insert new module imports as # `from <package> import <module>` by default. prefs['prefer_module_from_imports'] = False # If `True`, rope will transform a comma list of imports into # multiple separate import statements when organizing # imports. prefs['split_imports'] = False # If `True`, rope will remove all top-level import statements and # reinsert them at the top of the module when making changes. prefs['pull_imports_to_top'] = True # If `True`, rope will sort imports alphabetically by module name instead # of alphabetically by import statement, with from imports after normal # imports. prefs['sort_imports_alphabetically'] = False # Location of implementation of # rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general # case, you don't have to change this value, unless you're an rope expert. # Change this value to inject you own implementations of interfaces # listed in module rope.base.oi.type_hinting.providers.interfaces # For example, you can add you own providers for Django Models, or disable # the search type-hinting in a class hierarchy, etc. prefs['type_hinting_factory'] = ( 'rope.base.oi.type_hinting.factory.default_type_hinting_factory')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_moved(self, resource, new_resource): """It is called when a resource is moved"""
if self.moved is not None: self.moved(resource, new_resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_resource(self, resource): """Add a resource to the list of interesting resources"""
if resource.exists(): self.resources[resource] = self.timekeeper.get_indicator(resource) else: self.resources[resource] = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_indicator(self, resource): """Return the modification time and size of a `Resource`."""
path = resource.real_path # on dos, mtime does not change for a folder when files are added if os.name != 'posix' and os.path.isdir(path): return (os.path.getmtime(path), len(os.listdir(path)), os.path.getsize(path)) return (os.path.getmtime(path), os.path.getsize(path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_to_resource(project, path, type=None): """Get the resource at path You only need to specify `type` if `path` does not exist. It can be either 'file' or 'folder'. If the type is `None` it is assumed that the resource already exists. Note that this function uses `Project.get_resource()`, `Project.get_file()`, and `Project.get_folder()` methods. """
project_path = path_relative_to_project_root(project, path) if project_path is None: project_path = rope.base.project._realpath(path) project = rope.base.project.get_no_project() if type is None: return project.get_resource(project_path) if type == 'file': return project.get_file(project_path) if type == 'folder': return project.get_folder(project_path) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report_change(project, path, old_content): """Report that the contents of file at `path` was changed The new contents of file is retrieved by reading the file. """
resource = path_to_resource(project, path) if resource is None: return for observer in list(project.observers): observer.resource_changed(resource) if project.pycore.automatic_soa: rope.base.pycore.perform_soa_on_changed_scopes(project, resource, old_content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()): """Perform static object analysis on all python files in the project Note that this might be really time consuming. """
resources = project.get_python_files() job_set = task_handle.create_jobset('Analyzing Modules', len(resources)) for resource in resources: job_set.started_job(resource.path) analyze_module(project, resource) job_set.finished_job()