code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if size is not None: data = self.rfile.readline(size) self.bytes_read += len(data) self._check_length() return data # User didn't specify a size ... # We read the line in chunks to make sure it's not a 100MB line ! res = [] ...
def readline(self, size=None)
Read a single line from rfile buffer and return it. Args: size (int): minimum amount of data to read Returns: bytes: One line from rfile.
3.680486
3.823936
0.962486
data = EMPTY if size == 0: return data while True: if size and len(data) >= size: return data if not self.buffer: self._fetch() if not self.buffer: # EOF return...
def read(self, size=None)
Read a chunk from rfile buffer and return it. Args: size (int): amount of data to read Returns: bytes: Chunk from rfile, limited by size if specified.
2.467748
2.890005
0.853891
data = EMPTY if size == 0: return data while True: if size and len(data) >= size: return data if not self.buffer: self._fetch() if not self.buffer: # EOF return...
def readline(self, size=None)
Read a single line from rfile buffer and return it. Args: size (int): minimum amount of data to read Returns: bytes: One line from rfile.
1.966955
2.147692
0.915846
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 rai...
def read_trailer_lines(self)
Read HTTP headers and yield them. Returns: Generator: yields CRLF separated lines.
4.444986
4.164444
1.067366
# then all the http headers try: self.header_reader(self.rfile, self.inheaders) except ValueError as ex: self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size try: cl = ...
def read_request_headers(self)
Read self.rfile into self.inheaders. Return success.
3.669054
3.578032
1.025439
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get(b'Content-Length', 0)) if mrbs and mrbs < cl: if not self.sent_headers: ...
def respond(self)
Call the gateway and write its iterable output.
4.622083
4.387043
1.053576
status = str(status) proto_status = '%s %s\r\n' % (self.server.protocol, status) content_length = 'Content-Length: %s\r\n' % len(msg) content_type = 'Content-Type: text/plain\r\n' buf = [ proto_status.encode('ISO-8859-1'), content_length.encode('I...
def simple_response(self, status, msg='')
Write a simple response back to the client.
3.424922
3.406885
1.005294
if self.chunked_write and chunk: chunk_size_hex = hex(len(chunk))[2:].encode('ascii') buf = [chunk_size_hex, CRLF, chunk, CRLF] self.conn.wfile.write(EMPTY.join(buf)) else: self.conn.wfile.write(chunk)
def write(self, chunk)
Write unbuffered data to the client.
3.687797
3.41799
1.078937
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 (inf...
def send_headers(self)
Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.
3.292131
3.2307
1.019015
request_seen = False try: while True: # (re)set req to None so that if something goes wrong in # the RequestHandlerClass constructor, the error doesn't # get written to the previous request. req = None r...
def communicate(self)
Read each request and respond appropriately.
5.345315
5.149406
1.038045
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)
def _conditional_error(self, req, response)
Respond with an error. Don't bother writing if a response has already started being written.
8.234344
7.781406
1.058208
self.rfile.close() if not self.linger: self._close_kernel_socket() self.socket.close() else: # On the other hand, sometimes we want to hang around for a bit # to make sure the client has a chance to read our entire # response....
def close(self)
Close the socket underlying this connection.
12.056458
11.346565
1.062565
raise NotImplementedError( 'SO_PEERCRED is only supported in Linux kernel and WSL', ) elif not self.peercreds_enabled: raise RuntimeError( 'Peer creds lookup is disabled within this server', ) try: peer_creds = ...
def get_peer_creds(self): # LRU cached on per-instance basis, see __init__ PEERCRED_STRUCT_DEF = '3i' if IS_WINDOWS or self.socket.family != socket.AF_UNIX
Return the PID/UID/GID tuple of the peer socket for UNIX sockets. This function uses SO_PEERCRED to query the UNIX PID, UID, GID of the peer, which is only available if the bind address is a UNIX domain socket. Raises: NotImplementedError: in case of unsupported socket type...
7.415126
6.554342
1.13133
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( ...
def resolve_peer_creds(self): # LRU cached on per-instance basis if not IS_UID_GID_RESOLVABLE
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
5.875578
4.698075
1.250635
if six.PY2 and hasattr(self.socket, '_sock'): self.socket._sock.close()
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 call...
5.496287
4.974021
1.104999
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 ...
def clear_stats(self)
Reset server stat counters..
2.411875
2.356169
1.023643
if self._start_time is None: return self._run_time else: return self._run_time + (time.time() - self._start_time)
def runtime(self)
Return server uptime.
3.272002
3.007063
1.088106
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 ...
def bind_addr(self, value)
Set the interface on which to listen for connections.
4.996041
4.882638
1.023226
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 ...
def safe_start(self)
Run the server forever, and stop it cleanly on exit.
5.175201
4.95408
1.044634
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 activati...
def prepare(self)
Prepare server to serving requests. It binds a socket's port, setups the socket to ``listen()`` and does other preparing things.
2.982574
2.873788
1.037855
while self.ready: try: self.tick() except (KeyboardInterrupt, SystemExit): raise except Exception: self.error_log( 'Error in HTTPServer.tick', level=logging.ERROR, traceback=True,...
def serve(self)
Serve requests, after invoking :func:`prepare()`.
5.559775
5.483487
1.013912
# 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()
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
4.386037
5.999669
0.731047
sock = self.prepare_socket( self.bind_addr, family, type, proto, self.nodelay, self.ssl_adapter, ) sock = self.socket = self.bind_socket(sock, self.bind_addr) self.bind_addr = self.resolve_real_bind_addr(sock) return sock
def bind(self, family, type, proto=0)
Create (or recreate) the actual socket object.
5.316588
5.404225
0.983784
if IS_WINDOWS: raise ValueError( # or RuntimeError? 'AF_UNIX sockets are not supported under Windows.', ) fs_permissions = 0o777 # TODO: allow changing mode try: # Make possible reusing the socket... os.unl...
def bind_unix_socket(self, bind_addr)
Create (or recreate) a UNIX socket object.
3.94514
3.932322
1.00326
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): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if ...
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter)
Create and prepare the socket object.
3.370959
3.41372
0.987474
# 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, ...
def resolve_real_bind_addr(socket_)
Retrieve actual bind addr from bound socket.
8.557335
8.00664
1.06878
try: s, addr = self.socket.accept() if self.stats['Enabled']: self.stats['Accepts'] += 1 if not self.ready: return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.ti...
def tick(self)
Accept a new connection and put it on the Queue.
4.098606
3.998963
1.024917
self._interrupt = True self.stop() self._interrupt = interrupt
def interrupt(self, interrupt)
Perform the shutdown of this server and save the exception.
8.970497
7.755051
1.15673
self.ready = False if self._start_time is not None: self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if not isinstance(self.bind_addr, six.string_types): # To...
def stop(self)
Gracefully shutdown a server that is serving forever.
3.884644
3.794996
1.023623
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 ...
def run(self)
Process incoming HTTP connections. Retrieves incoming connections from thread pool.
3.534935
3.344212
1.057031
self._queue.put(obj, block=True, timeout=self._queue_put_timeout) if obj is _SHUTDOWNREQUEST: return
def put(self, obj)
Put request into queue. Args: obj (cheroot.server.HTTPConnection): HTTP connection waiting to be processed
6.656611
8.126086
0.819166
if self.max > 0: budget = max(self.max - len(self._threads), 0) else: # self.max <= 0 indicates no maximum budget = float('inf') n_new = min(amount, budget) workers = [self._spawn_worker() for i in range(n_new)] while not all(worker....
def grow(self, amount)
Spawn new worker threads (not above self.max).
4.12277
3.386707
1.217339
# Grow/shrink the pool if necessary. # Remove any dead threads from our list for t in self._threads: if not t.isAlive(): self._threads.remove(t) amount -= 1 # calculate the number of threads above the minimum n_extra = max(len...
def shrink(self, amount)
Kill off worker threads (not below self.min).
5.515808
5.114064
1.078557
# 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.cu...
def stop(self, timeout=5)
Terminate all worker threads. Args: timeout (int): time to wait for threads to stop gracefully
4.856451
4.918696
0.987345
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_...
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 ...
3.920639
3.402422
1.152308
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 ...
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 w...
2.625901
2.769073
0.948296
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...
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. Eve...
1.764357
1.914756
0.921453
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...
def get_modules(paths, toplevel=True)
Take files from the command line even if they don't end with .py.
2.195931
2.060853
1.065545
return ( varname in IGNORED_VARIABLE_NAMES or (varname.startswith('_') and not varname.startswith('__')) or _is_special_name(varname))
def _ignore_variable(filename, varname)
Ignore _ (Python idiom), _x (pylint convention) and __x__ (special variable or method), but not __x.
4.280729
4.288848
0.998107
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...
def get_unused_code(self, min_confidence=0, sort_by_size=False)
Return ordered list of unused Item objects.
3.132479
2.940758
1.065194
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 sel...
def report(self, min_confidence=0, sort_by_size=False, make_whitelist=False)
Print ordered list of Item objects to stdout.
3.983023
3.794623
1.049649
assert isinstance(node, (ast.Import, ast.ImportFrom)) for name_and_alias in node.names: # Store only top-level module name ("os.path" -> "os"). # We can't easily detect when "os.path" is used. name = name_and_alias.name.partition('.')[0] alias = n...
def _add_aliases(self, node)
We delegate to this method instead of using visit_alias() to have access to line numbers and to filter imports from __future__.
5.813469
5.563484
1.044933
# Old format strings. self.used_names |= set(re.findall(r'\%\((\w+)\)', node.s)) def is_identifier(s): return bool(re.match(r'[a-zA-Z_][a-zA-Z0-9_]*', s)) # New format strings. parser = string.Formatter() try: names = [name for _, name, ...
def visit_Str(self, node)
Parse variable names in format strings: '%(my_var)s' % locals() '{my_var}'.format(**locals())
3.299778
3.086992
1.06893
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: contin...
def _handle_ast_list(self, ast_list)
Find unreachable nodes in the given sequence of ast nodes.
4.311241
3.839388
1.122898
for _, value in ast.iter_fields(node): if isinstance(value, list): self._handle_ast_list(value) for item in value: if isinstance(item, ast.AST): self.visit(item) elif isinstance(value, ast.AST): ...
def generic_visit(self, node)
Called if no explicit visitor function exists for a node.
2.294183
2.34431
0.978617
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, unsu...
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 ar...
6.928961
6.887112
1.006076
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 \ ...
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.
4.543427
4.390358
1.034865
fixer = fixsyntax.FixSyntax(project, code, resource, maxfixes) pyname = fixer.pyname_at(offset) if pyname is not None: module, lineno = pyname.get_definition_location() name = rope.base.worder.Worder(code).get_word_at(offset) if lineno is not None: start = module.lin...
def find_definition(project, code, offset, resource=None, maxfixes=1)
Return the definition location of the python name at `offset` A `Location` object is returned if the definition location can be determined, otherwise ``None`` is returned.
5.776089
5.46106
1.057686
pymodule = project.get_pymodule(resource) finder = _BadAccessFinder(pymodule) ast.walk(pymodule.get_ast(), finder) return finder.errors
def find_errors(project, resource)
Find possible bad name and attribute accesses It returns a list of `Error`\s.
7.703657
7.222857
1.066566
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',)
def transform(self, pyobject)
Transform a `PyObject` to textual form
3.35851
2.87961
1.166307
if textual is None: return None type = textual[0] try: method = getattr(self, type + '_to_pyobject') return method(textual) except AttributeError: return None
def transform(self, textual)
Transform an object from textual form to `PyObject`
4.271918
3.21376
1.329258
return patch_ast(ast.parse(source), source, sorted_children)
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.
5.187381
9.526042
0.544547
if hasattr(node, 'region'): return node walker = _PatchingASTWalker(source, children=sorted_children) ast.call_for_nodes(node, walker) return node
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 ch...
7.663242
8.324743
0.920538
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)
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.
2.433344
2.072146
1.174311
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_...
def _handle_parens(self, children, start, formats)
Changes `children` and returns new start
3.454901
3.368849
1.025543
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: r...
def _good_token(self, token, offset, start=None)
Checks whether consumed token is in comments
2.590503
2.354866
1.100064
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 compr...
def get_block_start(lines, lineno, maximum_indents=80)
Approximate block start
3.336843
3.25586
1.024873
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
def _init_logicals(self)
Should initialize _starts and _ends attributes
4.37719
3.308455
1.323031
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 \ isi...
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.
3.292477
2.922634
1.126544
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_m...
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 refactorin...
3.356292
3.202459
1.048036
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 'static...
def get_kind(self)
Get function type It returns one of 'function', 'method', 'staticmethod' or 'classmethod' strs.
4.062504
3.649673
1.113115
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. Gene...
def walk(node, walker)
Walk the syntax tree
4.095876
4.114665
0.995434
result = callback(node) if recursive and not result: for child in get_child_nodes(node): call_for_nodes(child, callback, recursive)
def call_for_nodes(node, callback, recursive=False)
If callback returns `True` the child nodes are skipped
2.80617
2.880458
0.974209
# 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...
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.realpa...
3.082964
3.139811
0.981895
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.isd...
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...
2.38893
2.18631
1.092677
# 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....
def get_module(self, name, folder=None)
Returns a `PyObject` if the module was found.
3.538385
3.3013
1.071816
if self.root is None: return [] result = list(self._custom_source_folders) result.extend(self.pycore._find_source_folders(self.root)) return result
def get_source_folders(self)
Returns project source folders
5.750186
5.253496
1.094545
for observer in list(self.observers): observer.validate(folder)
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.
8.953312
5.965432
1.500866
self.history.do(changes, task_handle=task_handle)
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.
5.527226
7.614398
0.725891
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...
def find_module(self, modname, folder=None)
Returns a resource corresponding to the given module returns None if it can not be found
1.930735
1.925003
1.002978
return [resource for resource in self.get_files() if self.pycore.is_python_file(resource)]
def get_python_files(self)
Returns all python files available in the project
8.691216
7.512955
1.156831
if self.lineno is None and self.assignments: self.lineno = self.assignments[0].get_lineno() return (self.module, self.lineno)
def get_definition_location(self)
Returns a (module, lineno) tuple
5.428199
3.476004
1.56162
return rope.base.oi.soi.get_passed_objects( self.pyfunction, self.index)
def get_objects(self)
Returns the list of objects passed as this parameter
39.343033
33.201466
1.184979
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
def get_all_changes(self, *args, **kwds)
Get a project to changes dict
4.211558
4.107675
1.02529
if resources is None: resources = self.project.get_python_files() changes = ChangeSet('Encapsulate field <%s>' % self.name) job_set = task_handle.create_jobset('Collecting Changes', len(resources)) if getter is None: ...
def get_changes(self, getter=None, setter=None, resources=None, task_handle=taskhandle.NullTaskHandle())
Get the changes this refactoring makes If `getter` is not `None`, that will be the name of the getter, otherwise ``get_${field_name}`` will be used. The same is true for `setter` and if it is None set_${field_name} is used. `resources` can be a list of `rope.base.resource.File...
4.125227
3.709591
1.112044
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
def saveit(func)
A decorator that caches the return value of a function
2.28031
2.178375
1.046794
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: ...
def prevent_recursion(default)
A decorator that returns the return value of `default` in recursions
2.318051
2.354192
0.984648
def _decorator(func): def newfunc(*args, **kwds): try: return func(*args, **kwds) except exception_class: pass return newfunc return _decorator
def ignore_exception(exception_class)
A decorator that ignores `exception_class` exceptions
2.359818
2.396544
0.984676
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 _decorat...
def deprecated(message=None)
A decorator for deprecated functions
2.301294
2.231344
1.031349
def decorator(func): cached_func = _Cached(func, size) return lambda *a, **kw: cached_func(*a, **kw) return decorator
def cached(size)
A caching decorator based on parameter objects
3.175643
2.945475
1.078143
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...
def resolve(str_or_obj)
Returns object from string
2.103806
2.063489
1.019538
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] ...
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)``.
3.46831
3.398316
1.020597
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(): ...
def get_splitted_primary_before(self, offset)
returns expression, starting, starting_offset This function is used in `rope.codeassist.assist` function.
2.570659
2.521506
1.019493
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...
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`.
3.385924
2.823276
1.199289
changes = ChangeSet('Inline method <%s>' % self.name) if resources is None: resources = self.project.get_python_files() if only_current: resources = [self.original] if remove: resources.append(self.resource) job_set = task_hand...
def get_changes(self, remove=True, only_current=False, resources=None, task_handle=taskhandle.NullTaskHandle())
Get the changes this refactoring makes If `remove` is `False` the definition will not be removed. If `only_current` is `True`, the the current occurrence will be inlined, only.
5.686137
5.619081
1.011934
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)
def get_imported_resource(self, context)
Get the imported resource Returns `None` if module was not found.
4.380127
3.858695
1.135132
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)
def get_imported_module(self, context)
Get the imported `PyModule` Raises `rope.base.exceptions.ModuleNotFoundError` if module could not be found.
3.735352
3.290571
1.135168
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()
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 ...
3.396779
4.625729
0.734323
word_finder = worder.Worder(source_code, True) expression, starting, starting_offset = \ word_finder.get_splitted_primary_before(offset) return starting_offset
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 f...
12.919349
15.98604
0.808164
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)
def get_doc(project, source_code, offset, resource=None, maxfixes=1)
Get the pydoc
5.111558
5.010873
1.020093
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)
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. ...
4.53531
6.646644
0.682346
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes) pyname = fixer.pyname_at(offset) if pyname is not None: module, lineno = pyname.get_definition_location() if module is not None: return module.get_module().get_resource(), lineno return (None, None)
def get_definition_location(project, source_code, offset, resource=None, maxfixes=1)
Return the definition location of the python name at `offset` Return a (`rope.base.resources.Resource`, lineno) tuple. If no `resource` is given and the definition is inside the same module, the first element of the returned tuple would be `None`. If the location cannot be determined ``(None, None)``...
4.196427
3.685237
1.138713
# 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....
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): ...
3.857073
3.548854
1.08685
sorter = _ProposalSorter(proposals, scopepref, typepref) return sorter.get_sorted_proposal_list()
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 `...
3.89703
5.724115
0.680809
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
def starting_expression(source_code, offset)
Return the expression to complete
10.23343
10.164968
1.006735
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): re...
def parameters(self)
The names of the parameters the function takes. Returns None if this completion is not a function.
4.228269
4.178563
1.011895
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()
def get_doc(self)
Get the proposed object's docstring. Returns None if it can not be get.
3.75011
3.352297
1.118669
definfo = functionutils.DefinitionInfo.read(self._function) for arg, default in definfo.args_with_defaults: if self.argname == arg: return default return None
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.
9.654617
10.189676
0.94749
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_prop...
def get_sorted_proposal_list(self)
Return a list of `CodeAssistProposal`
3.031667
2.833944
1.069769
if self.moved is not None: self.moved(resource, new_resource)
def resource_moved(self, resource, new_resource)
It is called when a resource is moved
4.264326
4.104096
1.039042