repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
python-rope/rope | rope/base/utils/__init__.py | ignore_exception | 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 | python | 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 | [
"def",
"ignore_exception",
"(",
"exception_class",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"def",
"newfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")"... | A decorator that ignores `exception_class` exceptions | [
"A",
"decorator",
"that",
"ignores",
"exception_class",
"exceptions"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/utils/__init__.py#L36-L45 | train | 205,800 |
python-rope/rope | rope/base/utils/__init__.py | deprecated | 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 | python | 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 | [
"def",
"deprecated",
"(",
"message",
"=",
"None",
")",
":",
"def",
"_decorator",
"(",
"func",
",",
"message",
"=",
"message",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"'%s is deprecated'",
"%",
"func",
".",
"__name__",
"def",
"newfun... | A decorator for deprecated functions | [
"A",
"decorator",
"for",
"deprecated",
"functions"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/utils/__init__.py#L48-L58 | train | 205,801 |
python-rope/rope | rope/base/utils/__init__.py | cached | 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 | python | 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 | [
"def",
"cached",
"(",
"size",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"cached_func",
"=",
"_Cached",
"(",
"func",
",",
"size",
")",
"return",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"cached_func",
"(",
"*",
"a",
",",
"*",
"*",
... | A caching decorator based on parameter objects | [
"A",
"caching",
"decorator",
"based",
"on",
"parameter",
"objects"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/utils/__init__.py#L61-L66 | train | 205,802 |
python-rope/rope | rope/base/utils/__init__.py | resolve | 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 | python | 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 | [
"def",
"resolve",
"(",
"str_or_obj",
")",
":",
"from",
"rope",
".",
"base",
".",
"utils",
".",
"pycompat",
"import",
"string_types",
"if",
"not",
"isinstance",
"(",
"str_or_obj",
",",
"string_types",
")",
":",
"return",
"str_or_obj",
"if",
"'.'",
"not",
"i... | Returns object from string | [
"Returns",
"object",
"from",
"string"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/utils/__init__.py#L88-L98 | train | 205,803 |
python-rope/rope | rope/base/worder.py | _RealFinder._find_primary_without_dot_start | 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 | python | 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 | [
"def",
"_find_primary_without_dot_start",
"(",
"self",
",",
"offset",
")",
":",
"last_atom",
"=",
"offset",
"offset",
"=",
"self",
".",
"_find_last_non_space_char",
"(",
"last_atom",
")",
"while",
"offset",
">",
"0",
"and",
"self",
".",
"code",
"[",
"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)``. | [
"It",
"tries",
"to",
"find",
"the",
"undotted",
"primary",
"start"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/worder.py#L197-L214 | train | 205,804 |
python-rope/rope | rope/base/worder.py | _RealFinder.get_splitted_primary_before | 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) | python | 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) | [
"def",
"get_splitted_primary_before",
"(",
"self",
",",
"offset",
")",
":",
"if",
"offset",
"==",
"0",
":",
"return",
"(",
"''",
",",
"''",
",",
"0",
")",
"end",
"=",
"offset",
"-",
"1",
"word_start",
"=",
"self",
".",
"_find_atom_start",
"(",
"end",
... | returns expression, starting, starting_offset
This function is used in `rope.codeassist.assist` function. | [
"returns",
"expression",
"starting",
"starting_offset"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/worder.py#L238-L270 | train | 205,805 |
python-rope/rope | rope/refactor/inline.py | create_inline | 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) | python | 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) | [
"def",
"create_inline",
"(",
"project",
",",
"resource",
",",
"offset",
")",
":",
"pyname",
"=",
"_get_pyname",
"(",
"project",
",",
"resource",
",",
"offset",
")",
"message",
"=",
"'Inline refactoring should be performed on '",
"'a method, local variable or parameter.'... | Create a refactoring object for inlining
Based on `resource` and `offset` it returns an instance of
`InlineMethod`, `InlineVariable` or `InlineParameter`. | [
"Create",
"a",
"refactoring",
"object",
"for",
"inlining"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/inline.py#L37-L58 | train | 205,806 |
python-rope/rope | rope/refactor/importutils/importinfo.py | FromImport.get_imported_resource | 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) | python | 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) | [
"def",
"get_imported_resource",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"level",
"==",
"0",
":",
"return",
"context",
".",
"project",
".",
"find_module",
"(",
"self",
".",
"module_name",
",",
"folder",
"=",
"context",
".",
"folder",
")"... | Get the imported resource
Returns `None` if module was not found. | [
"Get",
"the",
"imported",
"resource"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/importinfo.py#L144-L154 | train | 205,807 |
python-rope/rope | rope/refactor/importutils/importinfo.py | FromImport.get_imported_module | 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) | python | 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) | [
"def",
"get_imported_module",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"level",
"==",
"0",
":",
"return",
"context",
".",
"project",
".",
"get_module",
"(",
"self",
".",
"module_name",
",",
"context",
".",
"folder",
")",
"else",
":",
"... | Get the imported `PyModule`
Raises `rope.base.exceptions.ModuleNotFoundError` if module
could not be found. | [
"Get",
"the",
"imported",
"PyModule"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/importinfo.py#L156-L167 | train | 205,808 |
python-rope/rope | rope/contrib/codeassist.py | code_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 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() | python | 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() | [
"def",
"code_assist",
"(",
"project",
",",
"source_code",
",",
"offset",
",",
"resource",
"=",
"None",
",",
"templates",
"=",
"None",
",",
"maxfixes",
"=",
"1",
",",
"later_locals",
"=",
"True",
")",
":",
"if",
"templates",
"is",
"not",
"None",
":",
"w... | 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. | [
"Return",
"python",
"code",
"completions",
"as",
"a",
"list",
"of",
"CodeAssistProposal",
"\\",
"s"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L20-L40 | train | 205,809 |
python-rope/rope | rope/contrib/codeassist.py | 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 function.
"""
word_finder = worder.Worder(source_code, True)
expression, starting, starting_offset = \
word_finder.get_splitted_primary_before(offset)
return starting_offset | python | 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 | [
"def",
"starting_offset",
"(",
"source_code",
",",
"offset",
")",
":",
"word_finder",
"=",
"worder",
".",
"Worder",
"(",
"source_code",
",",
"True",
")",
"expression",
",",
"starting",
",",
"starting_offset",
"=",
"word_finder",
".",
"get_splitted_primary_before",... | 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. | [
"Return",
"the",
"offset",
"in",
"which",
"the",
"completion",
"should",
"be",
"inserted"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L43-L58 | train | 205,810 |
python-rope/rope | rope/contrib/codeassist.py | get_doc | 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) | python | 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) | [
"def",
"get_doc",
"(",
"project",
",",
"source_code",
",",
"offset",
",",
"resource",
"=",
"None",
",",
"maxfixes",
"=",
"1",
")",
":",
"fixer",
"=",
"fixsyntax",
".",
"FixSyntax",
"(",
"project",
",",
"source_code",
",",
"resource",
",",
"maxfixes",
")"... | Get the pydoc | [
"Get",
"the",
"pydoc"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L61-L68 | train | 205,811 |
python-rope/rope | rope/contrib/codeassist.py | get_calltip | 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) | python | 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) | [
"def",
"get_calltip",
"(",
"project",
",",
"source_code",
",",
"offset",
",",
"resource",
"=",
"None",
",",
"maxfixes",
"=",
"1",
",",
"ignore_unknown",
"=",
"False",
",",
"remove_self",
"=",
"False",
")",
":",
"fixer",
"=",
"fixsyntax",
".",
"FixSyntax",
... | 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. | [
"Get",
"the",
"calltip",
"of",
"a",
"function"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L71-L101 | train | 205,812 |
python-rope/rope | rope/contrib/codeassist.py | get_canonical_path | 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 | python | 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 | [
"def",
"get_canonical_path",
"(",
"project",
",",
"resource",
",",
"offset",
")",
":",
"# Retrieve the PyName.",
"pymod",
"=",
"project",
".",
"get_pymodule",
"(",
"resource",
")",
"pyname",
"=",
"rope",
".",
"base",
".",
"evaluate",
".",
"eval_location",
"(",... | 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. | [
"Get",
"the",
"canonical",
"path",
"to",
"an",
"object",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L130-L185 | train | 205,813 |
python-rope/rope | rope/contrib/codeassist.py | sorted_proposals | 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() | python | 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() | [
"def",
"sorted_proposals",
"(",
"proposals",
",",
"scopepref",
"=",
"None",
",",
"typepref",
"=",
"None",
")",
":",
"sorter",
"=",
"_ProposalSorter",
"(",
"proposals",
",",
"scopepref",
",",
"typepref",
")",
"return",
"sorter",
".",
"get_sorted_proposal_list",
... | 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.) | [
"Sort",
"a",
"list",
"of",
"proposals"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L317-L331 | train | 205,814 |
python-rope/rope | rope/contrib/codeassist.py | starting_expression | 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 | python | 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 | [
"def",
"starting_expression",
"(",
"source_code",
",",
"offset",
")",
":",
"word_finder",
"=",
"worder",
".",
"Worder",
"(",
"source_code",
",",
"True",
")",
"expression",
",",
"starting",
",",
"starting_offset",
"=",
"word_finder",
".",
"get_splitted_primary_befo... | Return the expression to complete | [
"Return",
"the",
"expression",
"to",
"complete"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L334-L341 | train | 205,815 |
python-rope/rope | rope/contrib/codeassist.py | CompletionProposal.parameters | 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() | python | 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() | [
"def",
"parameters",
"(",
"self",
")",
":",
"pyname",
"=",
"self",
".",
"pyname",
"if",
"isinstance",
"(",
"pyname",
",",
"pynames",
".",
"ImportedName",
")",
":",
"pyname",
"=",
"pyname",
".",
"_get_imported_pyname",
"(",
")",
"if",
"isinstance",
"(",
"... | The names of the parameters the function takes.
Returns None if this completion is not a function. | [
"The",
"names",
"of",
"the",
"parameters",
"the",
"function",
"takes",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L225-L236 | train | 205,816 |
python-rope/rope | rope/contrib/codeassist.py | CompletionProposal.get_doc | 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() | python | 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() | [
"def",
"get_doc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pyname",
":",
"return",
"None",
"pyobject",
"=",
"self",
".",
"pyname",
".",
"get_object",
"(",
")",
"if",
"not",
"hasattr",
"(",
"pyobject",
",",
"'get_doc'",
")",
":",
"return",
"N... | Get the proposed object's docstring.
Returns None if it can not be get. | [
"Get",
"the",
"proposed",
"object",
"s",
"docstring",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L269-L279 | train | 205,817 |
python-rope/rope | rope/contrib/codeassist.py | NamedParamProposal.get_default | 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 | python | 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 | [
"def",
"get_default",
"(",
"self",
")",
":",
"definfo",
"=",
"functionutils",
".",
"DefinitionInfo",
".",
"read",
"(",
"self",
".",
"_function",
")",
"for",
"arg",
",",
"default",
"in",
"definfo",
".",
"args_with_defaults",
":",
"if",
"self",
".",
"argname... | Get a string representation of a param's default value.
Returns None if there is no default value for this param. | [
"Get",
"a",
"string",
"representation",
"of",
"a",
"param",
"s",
"default",
"value",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L305-L314 | train | 205,818 |
python-rope/rope | rope/contrib/codeassist.py | _ProposalSorter.get_sorted_proposal_list | 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 | python | 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 | [
"def",
"get_sorted_proposal_list",
"(",
"self",
")",
":",
"proposals",
"=",
"{",
"}",
"for",
"proposal",
"in",
"self",
".",
"proposals",
":",
"proposals",
".",
"setdefault",
"(",
"proposal",
".",
"scope",
",",
"[",
"]",
")",
".",
"append",
"(",
"proposal... | Return a list of `CodeAssistProposal` | [
"Return",
"a",
"list",
"of",
"CodeAssistProposal"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L520-L532 | train | 205,819 |
python-rope/rope | rope/base/default_config.py | set_prefs | 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') | python | 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') | [
"def",
"set_prefs",
"(",
"prefs",
")",
":",
"# 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 slash... | This function is called before opening the project | [
"This",
"function",
"is",
"called",
"before",
"opening",
"the",
"project"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/default_config.py#L5-L109 | train | 205,820 |
python-rope/rope | rope/base/resourceobserver.py | ResourceObserver.resource_moved | 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) | python | 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) | [
"def",
"resource_moved",
"(",
"self",
",",
"resource",
",",
"new_resource",
")",
":",
"if",
"self",
".",
"moved",
"is",
"not",
"None",
":",
"self",
".",
"moved",
"(",
"resource",
",",
"new_resource",
")"
] | It is called when a resource is moved | [
"It",
"is",
"called",
"when",
"a",
"resource",
"is",
"moved"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/resourceobserver.py#L32-L35 | train | 205,821 |
python-rope/rope | rope/base/resourceobserver.py | FilteredResourceObserver.add_resource | 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 | python | 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 | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
")",
":",
"if",
"resource",
".",
"exists",
"(",
")",
":",
"self",
".",
"resources",
"[",
"resource",
"]",
"=",
"self",
".",
"timekeeper",
".",
"get_indicator",
"(",
"resource",
")",
"else",
":",
"sel... | Add a resource to the list of interesting resources | [
"Add",
"a",
"resource",
"to",
"the",
"list",
"of",
"interesting",
"resources"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/resourceobserver.py#L95-L100 | train | 205,822 |
python-rope/rope | rope/base/resourceobserver.py | ChangeIndicator.get_indicator | 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)) | python | 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)) | [
"def",
"get_indicator",
"(",
"self",
",",
"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",
"(",
... | Return the modification time and size of a `Resource`. | [
"Return",
"the",
"modification",
"time",
"and",
"size",
"of",
"a",
"Resource",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/resourceobserver.py#L246-L255 | train | 205,823 |
python-rope/rope | rope/base/libutils.py | path_to_resource | 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 | python | 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 | [
"def",
"path_to_resource",
"(",
"project",
",",
"path",
",",
"type",
"=",
"None",
")",
":",
"project_path",
"=",
"path_relative_to_project_root",
"(",
"project",
",",
"path",
")",
"if",
"project_path",
"is",
"None",
":",
"project_path",
"=",
"rope",
".",
"ba... | 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. | [
"Get",
"the",
"resource",
"at",
"path"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/libutils.py#L11-L32 | train | 205,824 |
python-rope/rope | rope/base/libutils.py | report_change | 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) | python | 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) | [
"def",
"report_change",
"(",
"project",
",",
"path",
",",
"old_content",
")",
":",
"resource",
"=",
"path_to_resource",
"(",
"project",
",",
"path",
")",
"if",
"resource",
"is",
"None",
":",
"return",
"for",
"observer",
"in",
"list",
"(",
"project",
".",
... | Report that the contents of file at `path` was changed
The new contents of file is retrieved by reading the file. | [
"Report",
"that",
"the",
"contents",
"of",
"file",
"at",
"path",
"was",
"changed"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/libutils.py#L48-L61 | train | 205,825 |
python-rope/rope | rope/base/libutils.py | analyze_modules | 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() | python | 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() | [
"def",
"analyze_modules",
"(",
"project",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"resources",
"=",
"project",
".",
"get_python_files",
"(",
")",
"job_set",
"=",
"task_handle",
".",
"create_jobset",
"(",
"'Analyzing Modu... | Perform static object analysis on all python files in the project
Note that this might be really time consuming. | [
"Perform",
"static",
"object",
"analysis",
"on",
"all",
"python",
"files",
"in",
"the",
"project"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/libutils.py#L72-L82 | train | 205,826 |
python-rope/rope | rope/refactor/importutils/module_imports.py | ModuleImports.force_single_imports | def force_single_imports(self):
"""force a single import per statement"""
for import_stmt in self.imports[:]:
import_info = import_stmt.import_info
if import_info.is_empty() or import_stmt.readonly:
continue
if len(import_info.names_and_aliases) > 1:
for name_and_alias in import_info.names_and_aliases:
if hasattr(import_info, "module_name"):
new_import = importinfo.FromImport(
import_info.module_name, import_info.level,
[name_and_alias])
else:
new_import = importinfo.NormalImport([name_and_alias])
self.add_import(new_import)
import_stmt.empty_import() | python | def force_single_imports(self):
"""force a single import per statement"""
for import_stmt in self.imports[:]:
import_info = import_stmt.import_info
if import_info.is_empty() or import_stmt.readonly:
continue
if len(import_info.names_and_aliases) > 1:
for name_and_alias in import_info.names_and_aliases:
if hasattr(import_info, "module_name"):
new_import = importinfo.FromImport(
import_info.module_name, import_info.level,
[name_and_alias])
else:
new_import = importinfo.NormalImport([name_and_alias])
self.add_import(new_import)
import_stmt.empty_import() | [
"def",
"force_single_imports",
"(",
"self",
")",
":",
"for",
"import_stmt",
"in",
"self",
".",
"imports",
"[",
":",
"]",
":",
"import_info",
"=",
"import_stmt",
".",
"import_info",
"if",
"import_info",
".",
"is_empty",
"(",
")",
"or",
"import_stmt",
".",
"... | force a single import per statement | [
"force",
"a",
"single",
"import",
"per",
"statement"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/module_imports.py#L179-L194 | train | 205,827 |
python-rope/rope | rope/refactor/importutils/module_imports.py | ModuleImports.remove_pyname | def remove_pyname(self, pyname):
"""Removes pyname when imported in ``from mod import x``"""
visitor = actions.RemovePyNameVisitor(self.project, self.pymodule,
pyname, self._current_folder())
for import_stmt in self.imports:
import_stmt.accept(visitor) | python | def remove_pyname(self, pyname):
"""Removes pyname when imported in ``from mod import x``"""
visitor = actions.RemovePyNameVisitor(self.project, self.pymodule,
pyname, self._current_folder())
for import_stmt in self.imports:
import_stmt.accept(visitor) | [
"def",
"remove_pyname",
"(",
"self",
",",
"pyname",
")",
":",
"visitor",
"=",
"actions",
".",
"RemovePyNameVisitor",
"(",
"self",
".",
"project",
",",
"self",
".",
"pymodule",
",",
"pyname",
",",
"self",
".",
"_current_folder",
"(",
")",
")",
"for",
"imp... | Removes pyname when imported in ``from mod import x`` | [
"Removes",
"pyname",
"when",
"imported",
"in",
"from",
"mod",
"import",
"x"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/module_imports.py#L294-L299 | train | 205,828 |
python-rope/rope | rope/base/arguments.py | create_arguments | def create_arguments(primary, pyfunction, call_node, scope):
"""A factory for creating `Arguments`"""
args = list(call_node.args)
args.extend(call_node.keywords)
called = call_node.func
# XXX: Handle constructors
if _is_method_call(primary, pyfunction) and \
isinstance(called, ast.Attribute):
args.insert(0, called.value)
return Arguments(args, scope) | python | def create_arguments(primary, pyfunction, call_node, scope):
"""A factory for creating `Arguments`"""
args = list(call_node.args)
args.extend(call_node.keywords)
called = call_node.func
# XXX: Handle constructors
if _is_method_call(primary, pyfunction) and \
isinstance(called, ast.Attribute):
args.insert(0, called.value)
return Arguments(args, scope) | [
"def",
"create_arguments",
"(",
"primary",
",",
"pyfunction",
",",
"call_node",
",",
"scope",
")",
":",
"args",
"=",
"list",
"(",
"call_node",
".",
"args",
")",
"args",
".",
"extend",
"(",
"call_node",
".",
"keywords",
")",
"called",
"=",
"call_node",
".... | A factory for creating `Arguments` | [
"A",
"factory",
"for",
"creating",
"Arguments"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/arguments.py#L44-L53 | train | 205,829 |
python-rope/rope | rope/base/prefs.py | Prefs.set | def set(self, key, value):
"""Set the value of `key` preference to `value`."""
if key in self.callbacks:
self.callbacks[key](value)
else:
self.prefs[key] = value | python | def set(self, key, value):
"""Set the value of `key` preference to `value`."""
if key in self.callbacks:
self.callbacks[key](value)
else:
self.prefs[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"self",
".",
"callbacks",
":",
"self",
".",
"callbacks",
"[",
"key",
"]",
"(",
"value",
")",
"else",
":",
"self",
".",
"prefs",
"[",
"key",
"]",
"=",
"value"
] | Set the value of `key` preference to `value`. | [
"Set",
"the",
"value",
"of",
"key",
"preference",
"to",
"value",
"."
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/prefs.py#L7-L12 | train | 205,830 |
python-rope/rope | rope/base/prefs.py | Prefs.add | def add(self, key, value):
"""Add an entry to a list preference
Add `value` to the list of entries for the `key` preference.
"""
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | python | def add(self, key, value):
"""Add an entry to a list preference
Add `value` to the list of entries for the `key` preference.
"""
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"key",
"in",
"self",
".",
"prefs",
":",
"self",
".",
"prefs",
"[",
"key",
"]",
"=",
"[",
"]",
"self",
".",
"prefs",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")"
... | Add an entry to a list preference
Add `value` to the list of entries for the `key` preference. | [
"Add",
"an",
"entry",
"to",
"a",
"list",
"preference"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/prefs.py#L14-L22 | train | 205,831 |
python-rope/rope | rope/refactor/sourceutils.py | fix_indentation | def fix_indentation(code, new_indents):
"""Change the indentation of `code` to `new_indents`"""
min_indents = find_minimum_indents(code)
return indent_lines(code, new_indents - min_indents) | python | def fix_indentation(code, new_indents):
"""Change the indentation of `code` to `new_indents`"""
min_indents = find_minimum_indents(code)
return indent_lines(code, new_indents - min_indents) | [
"def",
"fix_indentation",
"(",
"code",
",",
"new_indents",
")",
":",
"min_indents",
"=",
"find_minimum_indents",
"(",
"code",
")",
"return",
"indent_lines",
"(",
"code",
",",
"new_indents",
"-",
"min_indents",
")"
] | Change the indentation of `code` to `new_indents` | [
"Change",
"the",
"indentation",
"of",
"code",
"to",
"new_indents"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/sourceutils.py#L35-L38 | train | 205,832 |
python-rope/rope | rope/refactor/sourceutils.py | get_body | def get_body(pyfunction):
"""Return unindented function body"""
# FIXME scope = pyfunction.get_scope()
pymodule = pyfunction.get_module()
start, end = get_body_region(pyfunction)
return fix_indentation(pymodule.source_code[start:end], 0) | python | def get_body(pyfunction):
"""Return unindented function body"""
# FIXME scope = pyfunction.get_scope()
pymodule = pyfunction.get_module()
start, end = get_body_region(pyfunction)
return fix_indentation(pymodule.source_code[start:end], 0) | [
"def",
"get_body",
"(",
"pyfunction",
")",
":",
"# FIXME scope = pyfunction.get_scope()",
"pymodule",
"=",
"pyfunction",
".",
"get_module",
"(",
")",
"start",
",",
"end",
"=",
"get_body_region",
"(",
"pyfunction",
")",
"return",
"fix_indentation",
"(",
"pymodule",
... | Return unindented function body | [
"Return",
"unindented",
"function",
"body"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/sourceutils.py#L59-L64 | train | 205,833 |
python-rope/rope | rope/refactor/sourceutils.py | get_body_region | def get_body_region(defined):
"""Return the start and end offsets of function body"""
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno
elif len(node.body) > 1:
start_line = node.body[1].lineno
start = lines.get_line_start(start_line)
scope_start = pymodule.logical_lines.logical_line_in(scope.start)
if scope_start[1] >= start_line:
# a one-liner!
# XXX: what if colon appears in a string
start = pymodule.source_code.index(':', start) + 1
while pymodule.source_code[start].isspace():
start += 1
end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code))
return start, end | python | def get_body_region(defined):
"""Return the start and end offsets of function body"""
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno
elif len(node.body) > 1:
start_line = node.body[1].lineno
start = lines.get_line_start(start_line)
scope_start = pymodule.logical_lines.logical_line_in(scope.start)
if scope_start[1] >= start_line:
# a one-liner!
# XXX: what if colon appears in a string
start = pymodule.source_code.index(':', start) + 1
while pymodule.source_code[start].isspace():
start += 1
end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code))
return start, end | [
"def",
"get_body_region",
"(",
"defined",
")",
":",
"scope",
"=",
"defined",
".",
"get_scope",
"(",
")",
"pymodule",
"=",
"defined",
".",
"get_module",
"(",
")",
"lines",
"=",
"pymodule",
".",
"lines",
"node",
"=",
"defined",
".",
"get_ast",
"(",
")",
... | Return the start and end offsets of function body | [
"Return",
"the",
"start",
"and",
"end",
"offsets",
"of",
"function",
"body"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/sourceutils.py#L67-L87 | train | 205,834 |
python-rope/rope | rope/base/history.py | History.do | def do(self, changes, task_handle=taskhandle.NullTaskHandle()):
"""Perform the change and add it to the `self.undo_list`
Note that uninteresting changes (changes to ignored files)
will not be appended to `self.undo_list`.
"""
try:
self.current_change = changes
changes.do(change.create_job_set(task_handle, changes))
finally:
self.current_change = None
if self._is_change_interesting(changes):
self.undo_list.append(changes)
self._remove_extra_items()
del self.redo_list[:] | python | def do(self, changes, task_handle=taskhandle.NullTaskHandle()):
"""Perform the change and add it to the `self.undo_list`
Note that uninteresting changes (changes to ignored files)
will not be appended to `self.undo_list`.
"""
try:
self.current_change = changes
changes.do(change.create_job_set(task_handle, changes))
finally:
self.current_change = None
if self._is_change_interesting(changes):
self.undo_list.append(changes)
self._remove_extra_items()
del self.redo_list[:] | [
"def",
"do",
"(",
"self",
",",
"changes",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"current_change",
"=",
"changes",
"changes",
".",
"do",
"(",
"change",
".",
"create_job_set",
"(",
"task_... | Perform the change and add it to the `self.undo_list`
Note that uninteresting changes (changes to ignored files)
will not be appended to `self.undo_list`. | [
"Perform",
"the",
"change",
"and",
"add",
"it",
"to",
"the",
"self",
".",
"undo_list"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/history.py#L27-L42 | train | 205,835 |
python-rope/rope | rope/base/history.py | History.undo | def undo(self, change=None, drop=False,
task_handle=taskhandle.NullTaskHandle()):
"""Redo done changes from the history
When `change` is `None`, the last done change will be undone.
If change is not `None` it should be an item from
`self.undo_list`; this change and all changes that depend on
it will be undone. In both cases the list of undone changes
will be returned.
If `drop` is `True`, the undone change will not be appended to
the redo list.
"""
if not self._undo_list:
raise exceptions.HistoryError('Undo list is empty')
if change is None:
change = self.undo_list[-1]
dependencies = self._find_dependencies(self.undo_list, change)
self._move_front(self.undo_list, dependencies)
self._perform_undos(len(dependencies), task_handle)
result = self.redo_list[-len(dependencies):]
if drop:
del self.redo_list[-len(dependencies):]
return result | python | def undo(self, change=None, drop=False,
task_handle=taskhandle.NullTaskHandle()):
"""Redo done changes from the history
When `change` is `None`, the last done change will be undone.
If change is not `None` it should be an item from
`self.undo_list`; this change and all changes that depend on
it will be undone. In both cases the list of undone changes
will be returned.
If `drop` is `True`, the undone change will not be appended to
the redo list.
"""
if not self._undo_list:
raise exceptions.HistoryError('Undo list is empty')
if change is None:
change = self.undo_list[-1]
dependencies = self._find_dependencies(self.undo_list, change)
self._move_front(self.undo_list, dependencies)
self._perform_undos(len(dependencies), task_handle)
result = self.redo_list[-len(dependencies):]
if drop:
del self.redo_list[-len(dependencies):]
return result | [
"def",
"undo",
"(",
"self",
",",
"change",
"=",
"None",
",",
"drop",
"=",
"False",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"_undo_list",
":",
"raise",
"exceptions",
".",
"HistoryError",
... | Redo done changes from the history
When `change` is `None`, the last done change will be undone.
If change is not `None` it should be an item from
`self.undo_list`; this change and all changes that depend on
it will be undone. In both cases the list of undone changes
will be returned.
If `drop` is `True`, the undone change will not be appended to
the redo list. | [
"Redo",
"done",
"changes",
"from",
"the",
"history"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/history.py#L54-L78 | train | 205,836 |
python-rope/rope | rope/base/history.py | History.redo | def redo(self, change=None, task_handle=taskhandle.NullTaskHandle()):
"""Redo undone changes from the history
When `change` is `None`, the last undone change will be
redone. If change is not `None` it should be an item from
`self.redo_list`; this change and all changes that depend on
it will be redone. In both cases the list of redone changes
will be returned.
"""
if not self.redo_list:
raise exceptions.HistoryError('Redo list is empty')
if change is None:
change = self.redo_list[-1]
dependencies = self._find_dependencies(self.redo_list, change)
self._move_front(self.redo_list, dependencies)
self._perform_redos(len(dependencies), task_handle)
return self.undo_list[-len(dependencies):] | python | def redo(self, change=None, task_handle=taskhandle.NullTaskHandle()):
"""Redo undone changes from the history
When `change` is `None`, the last undone change will be
redone. If change is not `None` it should be an item from
`self.redo_list`; this change and all changes that depend on
it will be redone. In both cases the list of redone changes
will be returned.
"""
if not self.redo_list:
raise exceptions.HistoryError('Redo list is empty')
if change is None:
change = self.redo_list[-1]
dependencies = self._find_dependencies(self.redo_list, change)
self._move_front(self.redo_list, dependencies)
self._perform_redos(len(dependencies), task_handle)
return self.undo_list[-len(dependencies):] | [
"def",
"redo",
"(",
"self",
",",
"change",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"redo_list",
":",
"raise",
"exceptions",
".",
"HistoryError",
"(",
"'Redo list is empty'",
"... | Redo undone changes from the history
When `change` is `None`, the last undone change will be
redone. If change is not `None` it should be an item from
`self.redo_list`; this change and all changes that depend on
it will be redone. In both cases the list of redone changes
will be returned. | [
"Redo",
"undone",
"changes",
"from",
"the",
"history"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/history.py#L80-L97 | train | 205,837 |
python-rope/rope | rope/base/pycore.py | PyCore.get_string_scope | def get_string_scope(self, code, resource=None):
"""Returns a `Scope` object for the given code"""
return rope.base.libutils.get_string_scope(code, resource) | python | def get_string_scope(self, code, resource=None):
"""Returns a `Scope` object for the given code"""
return rope.base.libutils.get_string_scope(code, resource) | [
"def",
"get_string_scope",
"(",
"self",
",",
"code",
",",
"resource",
"=",
"None",
")",
":",
"return",
"rope",
".",
"base",
".",
"libutils",
".",
"get_string_scope",
"(",
"code",
",",
"resource",
")"
] | Returns a `Scope` object for the given code | [
"Returns",
"a",
"Scope",
"object",
"for",
"the",
"given",
"code"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L107-L109 | train | 205,838 |
python-rope/rope | rope/base/pycore.py | PyCore.run_module | def run_module(self, resource, args=None, stdin=None, stdout=None):
"""Run `resource` module
Returns a `rope.base.oi.doa.PythonFileRunner` object for
controlling the process.
"""
perform_doa = self.project.prefs.get('perform_doi', True)
perform_doa = self.project.prefs.get('perform_doa', perform_doa)
receiver = self.object_info.doa_data_received
if not perform_doa:
receiver = None
runner = rope.base.oi.doa.PythonFileRunner(
self, resource, args, stdin, stdout, receiver)
runner.add_finishing_observer(self.module_cache.forget_all_data)
runner.run()
return runner | python | def run_module(self, resource, args=None, stdin=None, stdout=None):
"""Run `resource` module
Returns a `rope.base.oi.doa.PythonFileRunner` object for
controlling the process.
"""
perform_doa = self.project.prefs.get('perform_doi', True)
perform_doa = self.project.prefs.get('perform_doa', perform_doa)
receiver = self.object_info.doa_data_received
if not perform_doa:
receiver = None
runner = rope.base.oi.doa.PythonFileRunner(
self, resource, args, stdin, stdout, receiver)
runner.add_finishing_observer(self.module_cache.forget_all_data)
runner.run()
return runner | [
"def",
"run_module",
"(",
"self",
",",
"resource",
",",
"args",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
")",
":",
"perform_doa",
"=",
"self",
".",
"project",
".",
"prefs",
".",
"get",
"(",
"'perform_doi'",
",",
"True",
")"... | Run `resource` module
Returns a `rope.base.oi.doa.PythonFileRunner` object for
controlling the process. | [
"Run",
"resource",
"module"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L169-L185 | train | 205,839 |
python-rope/rope | rope/base/pycore.py | PyCore.analyze_module | def analyze_module(self, resource, should_analyze=lambda py: True,
search_subscopes=lambda py: True, followed_calls=None):
"""Analyze `resource` module for static object inference
This function forces rope to analyze this module to collect
information about function calls. `should_analyze` is a
function that is called with a `PyDefinedObject` argument. If
it returns `True` the element is analyzed. If it is `None` or
returns `False` the element is not analyzed.
`search_subscopes` is like `should_analyze`; The difference is
that if it returns `False` the sub-scopes are all ignored.
That is it is assumed that `should_analyze` returns `False`
for all of its subscopes.
`followed_calls` override the value of ``soa_followed_calls``
project config.
"""
if followed_calls is None:
followed_calls = self.project.prefs.get('soa_followed_calls', 0)
pymodule = self.resource_to_pyobject(resource)
self.module_cache.forget_all_data()
rope.base.oi.soa.analyze_module(
self, pymodule, should_analyze, search_subscopes, followed_calls) | python | def analyze_module(self, resource, should_analyze=lambda py: True,
search_subscopes=lambda py: True, followed_calls=None):
"""Analyze `resource` module for static object inference
This function forces rope to analyze this module to collect
information about function calls. `should_analyze` is a
function that is called with a `PyDefinedObject` argument. If
it returns `True` the element is analyzed. If it is `None` or
returns `False` the element is not analyzed.
`search_subscopes` is like `should_analyze`; The difference is
that if it returns `False` the sub-scopes are all ignored.
That is it is assumed that `should_analyze` returns `False`
for all of its subscopes.
`followed_calls` override the value of ``soa_followed_calls``
project config.
"""
if followed_calls is None:
followed_calls = self.project.prefs.get('soa_followed_calls', 0)
pymodule = self.resource_to_pyobject(resource)
self.module_cache.forget_all_data()
rope.base.oi.soa.analyze_module(
self, pymodule, should_analyze, search_subscopes, followed_calls) | [
"def",
"analyze_module",
"(",
"self",
",",
"resource",
",",
"should_analyze",
"=",
"lambda",
"py",
":",
"True",
",",
"search_subscopes",
"=",
"lambda",
"py",
":",
"True",
",",
"followed_calls",
"=",
"None",
")",
":",
"if",
"followed_calls",
"is",
"None",
"... | Analyze `resource` module for static object inference
This function forces rope to analyze this module to collect
information about function calls. `should_analyze` is a
function that is called with a `PyDefinedObject` argument. If
it returns `True` the element is analyzed. If it is `None` or
returns `False` the element is not analyzed.
`search_subscopes` is like `should_analyze`; The difference is
that if it returns `False` the sub-scopes are all ignored.
That is it is assumed that `should_analyze` returns `False`
for all of its subscopes.
`followed_calls` override the value of ``soa_followed_calls``
project config. | [
"Analyze",
"resource",
"module",
"for",
"static",
"object",
"inference"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L187-L210 | train | 205,840 |
python-rope/rope | rope/base/pycore.py | _TextChangeDetector.is_changed | def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1.
"""
left, right = self._get_changed(start, end)
if left < right:
return True
return False | python | def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1.
"""
left, right = self._get_changed(start, end)
if left < right:
return True
return False | [
"def",
"is_changed",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"left",
",",
"right",
"=",
"self",
".",
"_get_changed",
"(",
"start",
",",
"end",
")",
"if",
"left",
"<",
"right",
":",
"return",
"True",
"return",
"False"
] | Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1. | [
"Tell",
"whether",
"any",
"of",
"start",
"till",
"end",
"lines",
"have",
"changed"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L326-L334 | train | 205,841 |
python-rope/rope | rope/base/pycore.py | _TextChangeDetector.consume_changes | def consume_changes(self, start, end):
"""Clear the changed status of lines from start till end"""
left, right = self._get_changed(start, end)
if left < right:
del self.lines[left:right]
return left < right | python | def consume_changes(self, start, end):
"""Clear the changed status of lines from start till end"""
left, right = self._get_changed(start, end)
if left < right:
del self.lines[left:right]
return left < right | [
"def",
"consume_changes",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"left",
",",
"right",
"=",
"self",
".",
"_get_changed",
"(",
"start",
",",
"end",
")",
"if",
"left",
"<",
"right",
":",
"del",
"self",
".",
"lines",
"[",
"left",
":",
"right... | Clear the changed status of lines from start till end | [
"Clear",
"the",
"changed",
"status",
"of",
"lines",
"from",
"start",
"till",
"end"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L336-L341 | train | 205,842 |
python-rope/rope | rope/base/pyscopes.py | Scope.get_name | def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[name] | python | def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[name] | [
"def",
"get_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"get_names",
"(",
")",
":",
"raise",
"exceptions",
".",
"NameNotFoundError",
"(",
"'name %s not found'",
"%",
"name",
")",
"return",
"self",
".",
"get_names",
... | Return name `PyName` defined in this scope | [
"Return",
"name",
"PyName",
"defined",
"in",
"this",
"scope"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pyscopes.py#L22-L26 | train | 205,843 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.get_modules | def get_modules(self, name):
"""Return the list of modules that have global `name`"""
result = []
for module in self.names:
if name in self.names[module]:
result.append(module)
return result | python | def get_modules(self, name):
"""Return the list of modules that have global `name`"""
result = []
for module in self.names:
if name in self.names[module]:
result.append(module)
return result | [
"def",
"get_modules",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"[",
"]",
"for",
"module",
"in",
"self",
".",
"names",
":",
"if",
"name",
"in",
"self",
".",
"names",
"[",
"module",
"]",
":",
"result",
".",
"append",
"(",
"module",
")",
"... | Return the list of modules that have global `name` | [
"Return",
"the",
"list",
"of",
"modules",
"that",
"have",
"global",
"name"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L56-L62 | train | 205,844 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.get_all_names | def get_all_names(self):
"""Return the list of all cached global names"""
result = set()
for module in self.names:
result.update(set(self.names[module]))
return result | python | def get_all_names(self):
"""Return the list of all cached global names"""
result = set()
for module in self.names:
result.update(set(self.names[module]))
return result | [
"def",
"get_all_names",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"module",
"in",
"self",
".",
"names",
":",
"result",
".",
"update",
"(",
"set",
"(",
"self",
".",
"names",
"[",
"module",
"]",
")",
")",
"return",
"result"
] | Return the list of all cached global names | [
"Return",
"the",
"list",
"of",
"all",
"cached",
"global",
"names"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L64-L69 | train | 205,845 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.generate_cache | def generate_cache(self, resources=None, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for project files
If `resources` is a list of `rope.base.resource.File`\s, only
those files are searched; otherwise all python modules in the
project are cached.
"""
if resources is None:
resources = self.project.get_python_files()
job_set = task_handle.create_jobset(
'Generatig autoimport cache', len(resources))
for file in resources:
job_set.started_job('Working on <%s>' % file.path)
self.update_resource(file, underlined)
job_set.finished_job() | python | def generate_cache(self, resources=None, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for project files
If `resources` is a list of `rope.base.resource.File`\s, only
those files are searched; otherwise all python modules in the
project are cached.
"""
if resources is None:
resources = self.project.get_python_files()
job_set = task_handle.create_jobset(
'Generatig autoimport cache', len(resources))
for file in resources:
job_set.started_job('Working on <%s>' % file.path)
self.update_resource(file, underlined)
job_set.finished_job() | [
"def",
"generate_cache",
"(",
"self",
",",
"resources",
"=",
"None",
",",
"underlined",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"if",
"resources",
"is",
"None",
":",
"resources",
"=",
"self",
".",
"p... | Generate global name cache for project files
If `resources` is a list of `rope.base.resource.File`\s, only
those files are searched; otherwise all python modules in the
project are cached. | [
"Generate",
"global",
"name",
"cache",
"for",
"project",
"files"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L89-L105 | train | 205,846 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.generate_modules_cache | def generate_modules_cache(self, modules, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for modules listed in `modules`"""
job_set = task_handle.create_jobset(
'Generatig autoimport cache for modules', len(modules))
for modname in modules:
job_set.started_job('Working on <%s>' % modname)
if modname.endswith('.*'):
mod = self.project.find_module(modname[:-2])
if mod:
for sub in submodules(mod):
self.update_resource(sub, underlined)
else:
self.update_module(modname, underlined)
job_set.finished_job() | python | def generate_modules_cache(self, modules, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for modules listed in `modules`"""
job_set = task_handle.create_jobset(
'Generatig autoimport cache for modules', len(modules))
for modname in modules:
job_set.started_job('Working on <%s>' % modname)
if modname.endswith('.*'):
mod = self.project.find_module(modname[:-2])
if mod:
for sub in submodules(mod):
self.update_resource(sub, underlined)
else:
self.update_module(modname, underlined)
job_set.finished_job() | [
"def",
"generate_modules_cache",
"(",
"self",
",",
"modules",
",",
"underlined",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"job_set",
"=",
"task_handle",
".",
"create_jobset",
"(",
"'Generatig autoimport cache f... | Generate global name cache for modules listed in `modules` | [
"Generate",
"global",
"name",
"cache",
"for",
"modules",
"listed",
"in",
"modules"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L107-L121 | train | 205,847 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.find_insertion_line | def find_insertion_line(self, code):
"""Guess at what line the new import should be inserted"""
match = re.search(r'^(def|class)\s+', code)
if match is not None:
code = code[:match.start()]
try:
pymodule = libutils.get_string_module(self.project, code)
except exceptions.ModuleSyntaxError:
return 1
testmodname = '__rope_testmodule_rope'
importinfo = importutils.NormalImport(((testmodname, None),))
module_imports = importutils.get_module_imports(self.project,
pymodule)
module_imports.add_import(importinfo)
code = module_imports.get_changed_source()
offset = code.index(testmodname)
lineno = code.count('\n', 0, offset) + 1
return lineno | python | def find_insertion_line(self, code):
"""Guess at what line the new import should be inserted"""
match = re.search(r'^(def|class)\s+', code)
if match is not None:
code = code[:match.start()]
try:
pymodule = libutils.get_string_module(self.project, code)
except exceptions.ModuleSyntaxError:
return 1
testmodname = '__rope_testmodule_rope'
importinfo = importutils.NormalImport(((testmodname, None),))
module_imports = importutils.get_module_imports(self.project,
pymodule)
module_imports.add_import(importinfo)
code = module_imports.get_changed_source()
offset = code.index(testmodname)
lineno = code.count('\n', 0, offset) + 1
return lineno | [
"def",
"find_insertion_line",
"(",
"self",
",",
"code",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'^(def|class)\\s+'",
",",
"code",
")",
"if",
"match",
"is",
"not",
"None",
":",
"code",
"=",
"code",
"[",
":",
"match",
".",
"start",
"(",
")"... | Guess at what line the new import should be inserted | [
"Guess",
"at",
"what",
"line",
"the",
"new",
"import",
"should",
"be",
"inserted"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L132-L149 | train | 205,848 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.update_resource | def update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`"""
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleSyntaxError:
pass | python | def update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`"""
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleSyntaxError:
pass | [
"def",
"update_resource",
"(",
"self",
",",
"resource",
",",
"underlined",
"=",
"None",
")",
":",
"try",
":",
"pymodule",
"=",
"self",
".",
"project",
".",
"get_pymodule",
"(",
"resource",
")",
"modname",
"=",
"self",
".",
"_module_name",
"(",
"resource",
... | Update the cache for global names in `resource` | [
"Update",
"the",
"cache",
"for",
"global",
"names",
"in",
"resource"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L151-L158 | train | 205,849 |
python-rope/rope | rope/contrib/autoimport.py | AutoImport.update_module | def update_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module
`modname` is the name of a module.
"""
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleNotFoundError:
pass | python | def update_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module
`modname` is the name of a module.
"""
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleNotFoundError:
pass | [
"def",
"update_module",
"(",
"self",
",",
"modname",
",",
"underlined",
"=",
"None",
")",
":",
"try",
":",
"pymodule",
"=",
"self",
".",
"project",
".",
"get_module",
"(",
"modname",
")",
"self",
".",
"_add_names",
"(",
"pymodule",
",",
"modname",
",",
... | Update the cache for global names in `modname` module
`modname` is the name of a module. | [
"Update",
"the",
"cache",
"for",
"global",
"names",
"in",
"modname",
"module"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L160-L169 | train | 205,850 |
python-rope/rope | rope/refactor/restructure.py | replace | def replace(code, pattern, goal):
"""used by other refactorings"""
finder = similarfinder.RawSimilarFinder(code)
matches = list(finder.get_matches(pattern))
ast = patchedast.get_patched_ast(code)
lines = codeanalyze.SourceLinesAdapter(code)
template = similarfinder.CodeTemplate(goal)
computer = _ChangeComputer(code, ast, lines, template, matches)
result = computer.get_changed()
if result is None:
return code
return result | python | def replace(code, pattern, goal):
"""used by other refactorings"""
finder = similarfinder.RawSimilarFinder(code)
matches = list(finder.get_matches(pattern))
ast = patchedast.get_patched_ast(code)
lines = codeanalyze.SourceLinesAdapter(code)
template = similarfinder.CodeTemplate(goal)
computer = _ChangeComputer(code, ast, lines, template, matches)
result = computer.get_changed()
if result is None:
return code
return result | [
"def",
"replace",
"(",
"code",
",",
"pattern",
",",
"goal",
")",
":",
"finder",
"=",
"similarfinder",
".",
"RawSimilarFinder",
"(",
"code",
")",
"matches",
"=",
"list",
"(",
"finder",
".",
"get_matches",
"(",
"pattern",
")",
")",
"ast",
"=",
"patchedast"... | used by other refactorings | [
"used",
"by",
"other",
"refactorings"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/restructure.py#L210-L221 | train | 205,851 |
python-rope/rope | rope/refactor/restructure.py | Restructure.get_changes | def get_changes(self, checks=None, imports=None, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed by this restructuring
`resources` can be a list of `rope.base.resources.File`\s to
apply the restructuring on. If `None`, the restructuring will
be applied to all python files.
`checks` argument has been deprecated. Use the `args` argument
of the constructor. The usage of::
strchecks = {'obj1.type': 'mod.A', 'obj2': 'mod.B',
'obj3.object': 'mod.C'}
checks = restructuring.make_checks(strchecks)
can be replaced with::
args = {'obj1': 'type=mod.A', 'obj2': 'name=mod.B',
'obj3': 'object=mod.C'}
where obj1, obj2 and obj3 are wildcard names that appear
in restructuring pattern.
"""
if checks is not None:
warnings.warn(
'The use of checks parameter is deprecated; '
'use the args parameter of the constructor instead.',
DeprecationWarning, stacklevel=2)
for name, value in checks.items():
self.args[name] = similarfinder._pydefined_to_str(value)
if imports is not None:
warnings.warn(
'The use of imports parameter is deprecated; '
'use imports parameter of the constructor, instead.',
DeprecationWarning, stacklevel=2)
self.imports = imports
changes = change.ChangeSet('Restructuring <%s> to <%s>' %
(self.pattern, self.goal))
if resources is not None:
files = [resource for resource in resources
if libutils.is_python_file(self.project, resource)]
else:
files = self.project.get_python_files()
job_set = task_handle.create_jobset('Collecting Changes', len(files))
for resource in files:
job_set.started_job(resource.path)
pymodule = self.project.get_pymodule(resource)
finder = similarfinder.SimilarFinder(pymodule,
wildcards=self.wildcards)
matches = list(finder.get_matches(self.pattern, self.args))
computer = self._compute_changes(matches, pymodule)
result = computer.get_changed()
if result is not None:
imported_source = self._add_imports(resource, result,
self.imports)
changes.add_change(change.ChangeContents(resource,
imported_source))
job_set.finished_job()
return changes | python | def get_changes(self, checks=None, imports=None, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed by this restructuring
`resources` can be a list of `rope.base.resources.File`\s to
apply the restructuring on. If `None`, the restructuring will
be applied to all python files.
`checks` argument has been deprecated. Use the `args` argument
of the constructor. The usage of::
strchecks = {'obj1.type': 'mod.A', 'obj2': 'mod.B',
'obj3.object': 'mod.C'}
checks = restructuring.make_checks(strchecks)
can be replaced with::
args = {'obj1': 'type=mod.A', 'obj2': 'name=mod.B',
'obj3': 'object=mod.C'}
where obj1, obj2 and obj3 are wildcard names that appear
in restructuring pattern.
"""
if checks is not None:
warnings.warn(
'The use of checks parameter is deprecated; '
'use the args parameter of the constructor instead.',
DeprecationWarning, stacklevel=2)
for name, value in checks.items():
self.args[name] = similarfinder._pydefined_to_str(value)
if imports is not None:
warnings.warn(
'The use of imports parameter is deprecated; '
'use imports parameter of the constructor, instead.',
DeprecationWarning, stacklevel=2)
self.imports = imports
changes = change.ChangeSet('Restructuring <%s> to <%s>' %
(self.pattern, self.goal))
if resources is not None:
files = [resource for resource in resources
if libutils.is_python_file(self.project, resource)]
else:
files = self.project.get_python_files()
job_set = task_handle.create_jobset('Collecting Changes', len(files))
for resource in files:
job_set.started_job(resource.path)
pymodule = self.project.get_pymodule(resource)
finder = similarfinder.SimilarFinder(pymodule,
wildcards=self.wildcards)
matches = list(finder.get_matches(self.pattern, self.args))
computer = self._compute_changes(matches, pymodule)
result = computer.get_changed()
if result is not None:
imported_source = self._add_imports(resource, result,
self.imports)
changes.add_change(change.ChangeContents(resource,
imported_source))
job_set.finished_job()
return changes | [
"def",
"get_changes",
"(",
"self",
",",
"checks",
"=",
"None",
",",
"imports",
"=",
"None",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"if",
"checks",
"is",
"not",
"None",
":",
"warn... | Get the changes needed by this restructuring
`resources` can be a list of `rope.base.resources.File`\s to
apply the restructuring on. If `None`, the restructuring will
be applied to all python files.
`checks` argument has been deprecated. Use the `args` argument
of the constructor. The usage of::
strchecks = {'obj1.type': 'mod.A', 'obj2': 'mod.B',
'obj3.object': 'mod.C'}
checks = restructuring.make_checks(strchecks)
can be replaced with::
args = {'obj1': 'type=mod.A', 'obj2': 'name=mod.B',
'obj3': 'object=mod.C'}
where obj1, obj2 and obj3 are wildcard names that appear
in restructuring pattern. | [
"Get",
"the",
"changes",
"needed",
"by",
"this",
"restructuring"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/restructure.py#L94-L153 | train | 205,852 |
python-rope/rope | rope/refactor/restructure.py | Restructure.make_checks | def make_checks(self, string_checks):
"""Convert str to str dicts to str to PyObject dicts
This function is here to ease writing a UI.
"""
checks = {}
for key, value in string_checks.items():
is_pyname = not key.endswith('.object') and \
not key.endswith('.type')
evaluated = self._evaluate(value, is_pyname=is_pyname)
if evaluated is not None:
checks[key] = evaluated
return checks | python | def make_checks(self, string_checks):
"""Convert str to str dicts to str to PyObject dicts
This function is here to ease writing a UI.
"""
checks = {}
for key, value in string_checks.items():
is_pyname = not key.endswith('.object') and \
not key.endswith('.type')
evaluated = self._evaluate(value, is_pyname=is_pyname)
if evaluated is not None:
checks[key] = evaluated
return checks | [
"def",
"make_checks",
"(",
"self",
",",
"string_checks",
")",
":",
"checks",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"string_checks",
".",
"items",
"(",
")",
":",
"is_pyname",
"=",
"not",
"key",
".",
"endswith",
"(",
"'.object'",
")",
"and",
... | Convert str to str dicts to str to PyObject dicts
This function is here to ease writing a UI. | [
"Convert",
"str",
"to",
"str",
"dicts",
"to",
"str",
"to",
"PyObject",
"dicts"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/restructure.py#L177-L190 | train | 205,853 |
python-rope/rope | rope/refactor/extract.py | _ExtractInfo.returned | def returned(self):
"""Does the extracted piece contain return statement"""
if self._returned is None:
node = _parse_text(self.extracted)
self._returned = usefunction._returns_last(node)
return self._returned | python | def returned(self):
"""Does the extracted piece contain return statement"""
if self._returned is None:
node = _parse_text(self.extracted)
self._returned = usefunction._returns_last(node)
return self._returned | [
"def",
"returned",
"(",
"self",
")",
":",
"if",
"self",
".",
"_returned",
"is",
"None",
":",
"node",
"=",
"_parse_text",
"(",
"self",
".",
"extracted",
")",
"self",
".",
"_returned",
"=",
"usefunction",
".",
"_returns_last",
"(",
"node",
")",
"return",
... | Does the extracted piece contain return statement | [
"Does",
"the",
"extracted",
"piece",
"contain",
"return",
"statement"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/extract.py#L188-L193 | train | 205,854 |
python-rope/rope | rope/contrib/fixsyntax.py | FixSyntax.get_pymodule | def get_pymodule(self):
"""Get a `PyModule`"""
msg = None
code = self.code
tries = 0
while True:
try:
if tries == 0 and self.resource is not None and \
self.resource.read() == code:
return self.project.get_pymodule(self.resource,
force_errors=True)
return libutils.get_string_module(
self.project, code, resource=self.resource,
force_errors=True)
except exceptions.ModuleSyntaxError as e:
if msg is None:
msg = '%s:%s %s' % (e.filename, e.lineno, e.message_)
if tries < self.maxfixes:
tries += 1
self.commenter.comment(e.lineno)
code = '\n'.join(self.commenter.lines)
else:
raise exceptions.ModuleSyntaxError(
e.filename, e.lineno,
'Failed to fix error: {0}'.format(msg)) | python | def get_pymodule(self):
"""Get a `PyModule`"""
msg = None
code = self.code
tries = 0
while True:
try:
if tries == 0 and self.resource is not None and \
self.resource.read() == code:
return self.project.get_pymodule(self.resource,
force_errors=True)
return libutils.get_string_module(
self.project, code, resource=self.resource,
force_errors=True)
except exceptions.ModuleSyntaxError as e:
if msg is None:
msg = '%s:%s %s' % (e.filename, e.lineno, e.message_)
if tries < self.maxfixes:
tries += 1
self.commenter.comment(e.lineno)
code = '\n'.join(self.commenter.lines)
else:
raise exceptions.ModuleSyntaxError(
e.filename, e.lineno,
'Failed to fix error: {0}'.format(msg)) | [
"def",
"get_pymodule",
"(",
"self",
")",
":",
"msg",
"=",
"None",
"code",
"=",
"self",
".",
"code",
"tries",
"=",
"0",
"while",
"True",
":",
"try",
":",
"if",
"tries",
"==",
"0",
"and",
"self",
".",
"resource",
"is",
"not",
"None",
"and",
"self",
... | Get a `PyModule` | [
"Get",
"a",
"PyModule"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/fixsyntax.py#L19-L43 | train | 205,855 |
python-rope/rope | rope/base/change.py | _handle_job_set | def _handle_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s.
"""
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
job_set.finished_job()
return call | python | def _handle_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s.
"""
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
job_set.finished_job()
return call | [
"def",
"_handle_job_set",
"(",
"function",
")",
":",
"def",
"call",
"(",
"self",
",",
"job_set",
"=",
"taskhandle",
".",
"NullJobSet",
"(",
")",
")",
":",
"job_set",
".",
"started_job",
"(",
"str",
"(",
"self",
")",
")",
"function",
"(",
"self",
")",
... | A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s. | [
"A",
"decorator",
"for",
"handling",
"taskhandle",
".",
"JobSet",
"\\",
"s"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/change.py#L118-L128 | train | 205,856 |
python-rope/rope | rope/base/change.py | count_changes | def count_changes(change):
"""Counts the number of basic changes a `Change` will make"""
if isinstance(change, ChangeSet):
result = 0
for child in change.changes:
result += count_changes(child)
return result
return 1 | python | def count_changes(change):
"""Counts the number of basic changes a `Change` will make"""
if isinstance(change, ChangeSet):
result = 0
for child in change.changes:
result += count_changes(child)
return result
return 1 | [
"def",
"count_changes",
"(",
"change",
")",
":",
"if",
"isinstance",
"(",
"change",
",",
"ChangeSet",
")",
":",
"result",
"=",
"0",
"for",
"child",
"in",
"change",
".",
"changes",
":",
"result",
"+=",
"count_changes",
"(",
"child",
")",
"return",
"result... | Counts the number of basic changes a `Change` will make | [
"Counts",
"the",
"number",
"of",
"basic",
"changes",
"a",
"Change",
"will",
"make"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/change.py#L304-L311 | train | 205,857 |
python-rope/rope | rope/base/oi/soa.py | analyze_module | def analyze_module(pycore, pymodule, should_analyze,
search_subscopes, followed_calls):
"""Analyze `pymodule` for static object inference
Analyzes scopes for collecting object information. The analysis
starts from inner scopes.
"""
_analyze_node(pycore, pymodule, should_analyze,
search_subscopes, followed_calls) | python | def analyze_module(pycore, pymodule, should_analyze,
search_subscopes, followed_calls):
"""Analyze `pymodule` for static object inference
Analyzes scopes for collecting object information. The analysis
starts from inner scopes.
"""
_analyze_node(pycore, pymodule, should_analyze,
search_subscopes, followed_calls) | [
"def",
"analyze_module",
"(",
"pycore",
",",
"pymodule",
",",
"should_analyze",
",",
"search_subscopes",
",",
"followed_calls",
")",
":",
"_analyze_node",
"(",
"pycore",
",",
"pymodule",
",",
"should_analyze",
",",
"search_subscopes",
",",
"followed_calls",
")"
] | Analyze `pymodule` for static object inference
Analyzes scopes for collecting object information. The analysis
starts from inner scopes. | [
"Analyze",
"pymodule",
"for",
"static",
"object",
"inference"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/soa.py#L7-L16 | train | 205,858 |
python-rope/rope | rope/refactor/change_signature.py | ChangeSignature.get_changes | def get_changes(self, changers, in_hierarchy=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`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.
"""
function_changer = _FunctionChangers(self.pyname.get_object(),
self._definfo(), changers)
return self._change_calls(function_changer, in_hierarchy,
resources, task_handle) | python | def get_changes(self, changers, in_hierarchy=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`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.
"""
function_changer = _FunctionChangers(self.pyname.get_object(),
self._definfo(), changers)
return self._change_calls(function_changer, in_hierarchy,
resources, task_handle) | [
"def",
"get_changes",
"(",
"self",
",",
"changers",
",",
"in_hierarchy",
"=",
"False",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"function_changer",
"=",
"_FunctionChangers",
"(",
"self",
... | Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`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. | [
"Get",
"changes",
"caused",
"by",
"this",
"refactoring"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/change_signature.py#L126-L141 | train | 205,859 |
python-rope/rope | rope/contrib/fixmodnames.py | FixModuleNames.get_changes | def get_changes(self, fixer=str.lower,
task_handle=taskhandle.NullTaskHandle()):
"""Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name.
"""
stack = changestack.ChangeStack(self.project, 'Fixing module names')
jobset = task_handle.create_jobset('Fixing module names',
self._count_fixes(fixer) + 1)
try:
while True:
for resource in self._tobe_fixed(fixer):
jobset.started_job(resource.path)
renamer = rename.Rename(self.project, resource)
changes = renamer.get_changes(fixer(self._name(resource)))
stack.push(changes)
jobset.finished_job()
break
else:
break
finally:
jobset.started_job('Reverting to original state')
stack.pop_all()
jobset.finished_job()
return stack.merged() | python | def get_changes(self, fixer=str.lower,
task_handle=taskhandle.NullTaskHandle()):
"""Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name.
"""
stack = changestack.ChangeStack(self.project, 'Fixing module names')
jobset = task_handle.create_jobset('Fixing module names',
self._count_fixes(fixer) + 1)
try:
while True:
for resource in self._tobe_fixed(fixer):
jobset.started_job(resource.path)
renamer = rename.Rename(self.project, resource)
changes = renamer.get_changes(fixer(self._name(resource)))
stack.push(changes)
jobset.finished_job()
break
else:
break
finally:
jobset.started_job('Reverting to original state')
stack.pop_all()
jobset.finished_job()
return stack.merged() | [
"def",
"get_changes",
"(",
"self",
",",
"fixer",
"=",
"str",
".",
"lower",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"stack",
"=",
"changestack",
".",
"ChangeStack",
"(",
"self",
".",
"project",
",",
"'Fixing module ... | Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name. | [
"Fix",
"module",
"names"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/fixmodnames.py#L28-L54 | train | 205,860 |
python-rope/rope | rope/base/oi/soi.py | infer_returned_object | def infer_returned_object(pyfunction, args):
"""Infer the `PyObject` this `PyFunction` returns after calling"""
object_info = pyfunction.pycore.object_info
result = object_info.get_exact_returned(pyfunction, args)
if result is not None:
return result
result = _infer_returned(pyfunction, args)
if result is not None:
if args and pyfunction.get_module().get_resource() is not None:
params = args.get_arguments(
pyfunction.get_param_names(special_args=False))
object_info.function_called(pyfunction, params, result)
return result
result = object_info.get_returned(pyfunction, args)
if result is not None:
return result
hint_return = get_type_hinting_factory(pyfunction.pycore.project).make_return_provider()
type_ = hint_return(pyfunction)
if type_ is not None:
return rope.base.pyobjects.PyObject(type_) | python | def infer_returned_object(pyfunction, args):
"""Infer the `PyObject` this `PyFunction` returns after calling"""
object_info = pyfunction.pycore.object_info
result = object_info.get_exact_returned(pyfunction, args)
if result is not None:
return result
result = _infer_returned(pyfunction, args)
if result is not None:
if args and pyfunction.get_module().get_resource() is not None:
params = args.get_arguments(
pyfunction.get_param_names(special_args=False))
object_info.function_called(pyfunction, params, result)
return result
result = object_info.get_returned(pyfunction, args)
if result is not None:
return result
hint_return = get_type_hinting_factory(pyfunction.pycore.project).make_return_provider()
type_ = hint_return(pyfunction)
if type_ is not None:
return rope.base.pyobjects.PyObject(type_) | [
"def",
"infer_returned_object",
"(",
"pyfunction",
",",
"args",
")",
":",
"object_info",
"=",
"pyfunction",
".",
"pycore",
".",
"object_info",
"result",
"=",
"object_info",
".",
"get_exact_returned",
"(",
"pyfunction",
",",
"args",
")",
"if",
"result",
"is",
"... | Infer the `PyObject` this `PyFunction` returns after calling | [
"Infer",
"the",
"PyObject",
"this",
"PyFunction",
"returns",
"after",
"calling"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/soi.py#L19-L38 | train | 205,861 |
python-rope/rope | rope/base/oi/soi.py | infer_parameter_objects | def infer_parameter_objects(pyfunction):
"""Infer the `PyObject`\s of parameters of this `PyFunction`"""
object_info = pyfunction.pycore.object_info
result = object_info.get_parameter_objects(pyfunction)
if result is None:
result = _parameter_objects(pyfunction)
_handle_first_parameter(pyfunction, result)
return result | python | def infer_parameter_objects(pyfunction):
"""Infer the `PyObject`\s of parameters of this `PyFunction`"""
object_info = pyfunction.pycore.object_info
result = object_info.get_parameter_objects(pyfunction)
if result is None:
result = _parameter_objects(pyfunction)
_handle_first_parameter(pyfunction, result)
return result | [
"def",
"infer_parameter_objects",
"(",
"pyfunction",
")",
":",
"object_info",
"=",
"pyfunction",
".",
"pycore",
".",
"object_info",
"result",
"=",
"object_info",
".",
"get_parameter_objects",
"(",
"pyfunction",
")",
"if",
"result",
"is",
"None",
":",
"result",
"... | Infer the `PyObject`\s of parameters of this `PyFunction` | [
"Infer",
"the",
"PyObject",
"\\",
"s",
"of",
"parameters",
"of",
"this",
"PyFunction"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/soi.py#L42-L49 | train | 205,862 |
python-rope/rope | rope/base/stdmods.py | normalize_so_name | def normalize_so_name(name):
"""
Handle different types of python installations
"""
if "cpython" in name:
return os.path.splitext(os.path.splitext(name)[0])[0]
# XXX: Special handling for Fedora python2 distribution
# See: https://github.com/python-rope/rope/issues/211
if name == "timemodule.so":
return "time"
return os.path.splitext(name)[0] | python | def normalize_so_name(name):
"""
Handle different types of python installations
"""
if "cpython" in name:
return os.path.splitext(os.path.splitext(name)[0])[0]
# XXX: Special handling for Fedora python2 distribution
# See: https://github.com/python-rope/rope/issues/211
if name == "timemodule.so":
return "time"
return os.path.splitext(name)[0] | [
"def",
"normalize_so_name",
"(",
"name",
")",
":",
"if",
"\"cpython\"",
"in",
"name",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"# XXX: Special han... | Handle different types of python installations | [
"Handle",
"different",
"types",
"of",
"python",
"installations"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/stdmods.py#L40-L50 | train | 205,863 |
python-rope/rope | rope/base/oi/doa.py | PythonFileRunner.run | def run(self):
"""Execute the process"""
env = dict(os.environ)
file_path = self.file.real_path
path_folders = self.pycore.project.get_source_folders() + \
self.pycore.project.get_python_path_folders()
env['PYTHONPATH'] = os.pathsep.join(folder.real_path
for folder in path_folders)
runmod_path = self.pycore.project.find_module('rope.base.oi.runmod').real_path
self.receiver = None
self._init_data_receiving()
send_info = '-'
if self.receiver:
send_info = self.receiver.get_send_info()
args = [sys.executable, runmod_path, send_info,
self.pycore.project.address, self.file.real_path]
if self.analyze_data is None:
del args[1:4]
if self.args is not None:
args.extend(self.args)
self.process = subprocess.Popen(
executable=sys.executable, args=args, env=env,
cwd=os.path.split(file_path)[0], stdin=self.stdin,
stdout=self.stdout, stderr=self.stdout, close_fds=os.name != 'nt') | python | def run(self):
"""Execute the process"""
env = dict(os.environ)
file_path = self.file.real_path
path_folders = self.pycore.project.get_source_folders() + \
self.pycore.project.get_python_path_folders()
env['PYTHONPATH'] = os.pathsep.join(folder.real_path
for folder in path_folders)
runmod_path = self.pycore.project.find_module('rope.base.oi.runmod').real_path
self.receiver = None
self._init_data_receiving()
send_info = '-'
if self.receiver:
send_info = self.receiver.get_send_info()
args = [sys.executable, runmod_path, send_info,
self.pycore.project.address, self.file.real_path]
if self.analyze_data is None:
del args[1:4]
if self.args is not None:
args.extend(self.args)
self.process = subprocess.Popen(
executable=sys.executable, args=args, env=env,
cwd=os.path.split(file_path)[0], stdin=self.stdin,
stdout=self.stdout, stderr=self.stdout, close_fds=os.name != 'nt') | [
"def",
"run",
"(",
"self",
")",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"file_path",
"=",
"self",
".",
"file",
".",
"real_path",
"path_folders",
"=",
"self",
".",
"pycore",
".",
"project",
".",
"get_source_folders",
"(",
")",
"+",
"s... | Execute the process | [
"Execute",
"the",
"process"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/doa.py#L52-L75 | train | 205,864 |
python-rope/rope | rope/base/oi/doa.py | PythonFileRunner.kill_process | def kill_process(self):
"""Stop the process"""
if self.process.poll() is not None:
return
try:
if hasattr(self.process, 'terminate'):
self.process.terminate()
elif os.name != 'nt':
os.kill(self.process.pid, 9)
else:
import ctypes
handle = int(self.process._handle)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
except OSError:
pass | python | def kill_process(self):
"""Stop the process"""
if self.process.poll() is not None:
return
try:
if hasattr(self.process, 'terminate'):
self.process.terminate()
elif os.name != 'nt':
os.kill(self.process.pid, 9)
else:
import ctypes
handle = int(self.process._handle)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
except OSError:
pass | [
"def",
"kill_process",
"(",
"self",
")",
":",
"if",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"return",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"process",
",",
"'terminate'",
")",
":",
"self",
".",
"process",
"... | Stop the process | [
"Stop",
"the",
"process"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/doa.py#L107-L121 | train | 205,865 |
python-rope/rope | rope/refactor/similarfinder.py | RawSimilarFinder.get_matches | def get_matches(self, code, start=0, end=None, skip=None):
"""Search for `code` in source and return a list of `Match`\es
`code` can contain wildcards. ``${name}`` matches normal
names and ``${?name} can match any expression. You can use
`Match.get_ast()` for getting the node that has matched a
given pattern.
"""
if end is None:
end = len(self.source)
for match in self._get_matched_asts(code):
match_start, match_end = match.get_region()
if start <= match_start and match_end <= end:
if skip is not None and (skip[0] < match_end and
skip[1] > match_start):
continue
yield match | python | def get_matches(self, code, start=0, end=None, skip=None):
"""Search for `code` in source and return a list of `Match`\es
`code` can contain wildcards. ``${name}`` matches normal
names and ``${?name} can match any expression. You can use
`Match.get_ast()` for getting the node that has matched a
given pattern.
"""
if end is None:
end = len(self.source)
for match in self._get_matched_asts(code):
match_start, match_end = match.get_region()
if start <= match_start and match_end <= end:
if skip is not None and (skip[0] < match_end and
skip[1] > match_start):
continue
yield match | [
"def",
"get_matches",
"(",
"self",
",",
"code",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"len",
"(",
"self",
".",
"source",
")",
"for",
"match",
"in",
"self... | Search for `code` in source and return a list of `Match`\es
`code` can contain wildcards. ``${name}`` matches normal
names and ``${?name} can match any expression. You can use
`Match.get_ast()` for getting the node that has matched a
given pattern. | [
"Search",
"for",
"code",
"in",
"source",
"and",
"return",
"a",
"list",
"of",
"Match",
"\\",
"es"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/similarfinder.py#L90-L107 | train | 205,866 |
python-rope/rope | rope/refactor/similarfinder.py | _ASTMatcher._get_children | def _get_children(self, node):
"""Return not `ast.expr_context` children of `node`"""
children = ast.get_children(node)
return [child for child in children
if not isinstance(child, ast.expr_context)] | python | def _get_children(self, node):
"""Return not `ast.expr_context` children of `node`"""
children = ast.get_children(node)
return [child for child in children
if not isinstance(child, ast.expr_context)] | [
"def",
"_get_children",
"(",
"self",
",",
"node",
")",
":",
"children",
"=",
"ast",
".",
"get_children",
"(",
"node",
")",
"return",
"[",
"child",
"for",
"child",
"in",
"children",
"if",
"not",
"isinstance",
"(",
"child",
",",
"ast",
".",
"expr_context",... | Return not `ast.expr_context` children of `node` | [
"Return",
"not",
"ast",
".",
"expr_context",
"children",
"of",
"node"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/similarfinder.py#L211-L215 | train | 205,867 |
python-rope/rope | rope/refactor/importutils/__init__.py | get_imports | def get_imports(project, pydefined):
"""A shortcut for getting the `ImportInfo`\s used in a scope"""
pymodule = pydefined.get_module()
module = module_imports.ModuleImports(project, pymodule)
if pymodule == pydefined:
return [stmt.import_info for stmt in module.imports]
return module.get_used_imports(pydefined) | python | def get_imports(project, pydefined):
"""A shortcut for getting the `ImportInfo`\s used in a scope"""
pymodule = pydefined.get_module()
module = module_imports.ModuleImports(project, pymodule)
if pymodule == pydefined:
return [stmt.import_info for stmt in module.imports]
return module.get_used_imports(pydefined) | [
"def",
"get_imports",
"(",
"project",
",",
"pydefined",
")",
":",
"pymodule",
"=",
"pydefined",
".",
"get_module",
"(",
")",
"module",
"=",
"module_imports",
".",
"ModuleImports",
"(",
"project",
",",
"pymodule",
")",
"if",
"pymodule",
"==",
"pydefined",
":"... | A shortcut for getting the `ImportInfo`\s used in a scope | [
"A",
"shortcut",
"for",
"getting",
"the",
"ImportInfo",
"\\",
"s",
"used",
"in",
"a",
"scope"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/__init__.py#L263-L269 | train | 205,868 |
python-rope/rope | rope/refactor/importutils/__init__.py | ImportTools.get_from_import | def get_from_import(self, resource, name):
"""The from import statement for `name` in `resource`"""
module_name = libutils.modname(resource)
names = []
if isinstance(name, list):
names = [(imported, None) for imported in name]
else:
names = [(name, None), ]
return FromImport(module_name, 0, tuple(names)) | python | def get_from_import(self, resource, name):
"""The from import statement for `name` in `resource`"""
module_name = libutils.modname(resource)
names = []
if isinstance(name, list):
names = [(imported, None) for imported in name]
else:
names = [(name, None), ]
return FromImport(module_name, 0, tuple(names)) | [
"def",
"get_from_import",
"(",
"self",
",",
"resource",
",",
"name",
")",
":",
"module_name",
"=",
"libutils",
".",
"modname",
"(",
"resource",
")",
"names",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"name",
",",
"list",
")",
":",
"names",
"=",
"[",
"(... | The from import statement for `name` in `resource` | [
"The",
"from",
"import",
"statement",
"for",
"name",
"in",
"resource"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/importutils/__init__.py#L77-L85 | train | 205,869 |
python-rope/rope | rope/refactor/occurrences.py | create_finder | def create_finder(project, name, pyname, only_calls=False, imports=True,
unsure=None, docs=False, instance=None, in_hierarchy=False,
keywords=True):
"""A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered.
"""
pynames_ = set([pyname])
filters = []
if only_calls:
filters.append(CallsFilter())
if not imports:
filters.append(NoImportsFilter())
if not keywords:
filters.append(NoKeywordsFilter())
if isinstance(instance, pynames.ParameterName):
for pyobject in instance.get_objects():
try:
pynames_.add(pyobject[name])
except exceptions.AttributeNotFoundError:
pass
for pyname in pynames_:
filters.append(PyNameFilter(pyname))
if in_hierarchy:
filters.append(InHierarchyFilter(pyname))
if unsure:
filters.append(UnsureFilter(unsure))
return Finder(project, name, filters=filters, docs=docs) | python | def create_finder(project, name, pyname, only_calls=False, imports=True,
unsure=None, docs=False, instance=None, in_hierarchy=False,
keywords=True):
"""A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered.
"""
pynames_ = set([pyname])
filters = []
if only_calls:
filters.append(CallsFilter())
if not imports:
filters.append(NoImportsFilter())
if not keywords:
filters.append(NoKeywordsFilter())
if isinstance(instance, pynames.ParameterName):
for pyobject in instance.get_objects():
try:
pynames_.add(pyobject[name])
except exceptions.AttributeNotFoundError:
pass
for pyname in pynames_:
filters.append(PyNameFilter(pyname))
if in_hierarchy:
filters.append(InHierarchyFilter(pyname))
if unsure:
filters.append(UnsureFilter(unsure))
return Finder(project, name, filters=filters, docs=docs) | [
"def",
"create_finder",
"(",
"project",
",",
"name",
",",
"pyname",
",",
"only_calls",
"=",
"False",
",",
"imports",
"=",
"True",
",",
"unsure",
"=",
"None",
",",
"docs",
"=",
"False",
",",
"instance",
"=",
"None",
",",
"in_hierarchy",
"=",
"False",
",... | A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered. | [
"A",
"factory",
"for",
"Finder"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/occurrences.py#L87-L117 | train | 205,870 |
python-rope/rope | rope/refactor/occurrences.py | same_pyname | def same_pyname(expected, pyname):
"""Check whether `expected` and `pyname` are the same"""
if expected is None or pyname is None:
return False
if expected == pyname:
return True
if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \
and type(pyname) not in \
(pynames.ImportedModule, pynames.ImportedName):
return False
return expected.get_definition_location() == \
pyname.get_definition_location() and \
expected.get_object() == pyname.get_object() | python | def same_pyname(expected, pyname):
"""Check whether `expected` and `pyname` are the same"""
if expected is None or pyname is None:
return False
if expected == pyname:
return True
if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \
and type(pyname) not in \
(pynames.ImportedModule, pynames.ImportedName):
return False
return expected.get_definition_location() == \
pyname.get_definition_location() and \
expected.get_object() == pyname.get_object() | [
"def",
"same_pyname",
"(",
"expected",
",",
"pyname",
")",
":",
"if",
"expected",
"is",
"None",
"or",
"pyname",
"is",
"None",
":",
"return",
"False",
"if",
"expected",
"==",
"pyname",
":",
"return",
"True",
"if",
"type",
"(",
"expected",
")",
"not",
"i... | Check whether `expected` and `pyname` are the same | [
"Check",
"whether",
"expected",
"and",
"pyname",
"are",
"the",
"same"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/occurrences.py#L184-L196 | train | 205,871 |
python-rope/rope | rope/refactor/occurrences.py | unsure_pyname | def unsure_pyname(pyname, unbound=True):
"""Return `True` if we don't know what this name references"""
if pyname is None:
return True
if unbound and not isinstance(pyname, pynames.UnboundName):
return False
if pyname.get_object() == pyobjects.get_unknown():
return True | python | def unsure_pyname(pyname, unbound=True):
"""Return `True` if we don't know what this name references"""
if pyname is None:
return True
if unbound and not isinstance(pyname, pynames.UnboundName):
return False
if pyname.get_object() == pyobjects.get_unknown():
return True | [
"def",
"unsure_pyname",
"(",
"pyname",
",",
"unbound",
"=",
"True",
")",
":",
"if",
"pyname",
"is",
"None",
":",
"return",
"True",
"if",
"unbound",
"and",
"not",
"isinstance",
"(",
"pyname",
",",
"pynames",
".",
"UnboundName",
")",
":",
"return",
"False"... | Return `True` if we don't know what this name references | [
"Return",
"True",
"if",
"we",
"don",
"t",
"know",
"what",
"this",
"name",
"references"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/occurrences.py#L199-L206 | train | 205,872 |
python-rope/rope | rope/refactor/occurrences.py | Finder.find_occurrences | def find_occurrences(self, resource=None, pymodule=None):
"""Generate `Occurrence` instances"""
tools = _OccurrenceToolsCreator(self.project, resource=resource,
pymodule=pymodule, docs=self.docs)
for offset in self._textual_finder.find_offsets(tools.source_code):
occurrence = Occurrence(tools, offset)
for filter in self.filters:
result = filter(occurrence)
if result is None:
continue
if result:
yield occurrence
break | python | def find_occurrences(self, resource=None, pymodule=None):
"""Generate `Occurrence` instances"""
tools = _OccurrenceToolsCreator(self.project, resource=resource,
pymodule=pymodule, docs=self.docs)
for offset in self._textual_finder.find_offsets(tools.source_code):
occurrence = Occurrence(tools, offset)
for filter in self.filters:
result = filter(occurrence)
if result is None:
continue
if result:
yield occurrence
break | [
"def",
"find_occurrences",
"(",
"self",
",",
"resource",
"=",
"None",
",",
"pymodule",
"=",
"None",
")",
":",
"tools",
"=",
"_OccurrenceToolsCreator",
"(",
"self",
".",
"project",
",",
"resource",
"=",
"resource",
",",
"pymodule",
"=",
"pymodule",
",",
"do... | Generate `Occurrence` instances | [
"Generate",
"Occurrence",
"instances"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/occurrences.py#L72-L84 | train | 205,873 |
python-rope/rope | rope/contrib/generate.py | create_generate | def create_generate(kind, project, resource, offset):
"""A factory for creating `Generate` objects
`kind` can be 'variable', 'function', 'class', 'module' or
'package'.
"""
generate = eval('Generate' + kind.title())
return generate(project, resource, offset) | python | def create_generate(kind, project, resource, offset):
"""A factory for creating `Generate` objects
`kind` can be 'variable', 'function', 'class', 'module' or
'package'.
"""
generate = eval('Generate' + kind.title())
return generate(project, resource, offset) | [
"def",
"create_generate",
"(",
"kind",
",",
"project",
",",
"resource",
",",
"offset",
")",
":",
"generate",
"=",
"eval",
"(",
"'Generate'",
"+",
"kind",
".",
"title",
"(",
")",
")",
"return",
"generate",
"(",
"project",
",",
"resource",
",",
"offset",
... | A factory for creating `Generate` objects
`kind` can be 'variable', 'function', 'class', 'module' or
'package'. | [
"A",
"factory",
"for",
"creating",
"Generate",
"objects"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/generate.py#L8-L16 | train | 205,874 |
python-rope/rope | rope/contrib/generate.py | create_module | def create_module(project, name, sourcefolder=None):
"""Creates a module and returns a `rope.base.resources.File`"""
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
return parent.create_file(packages[-1] + '.py') | python | def create_module(project, name, sourcefolder=None):
"""Creates a module and returns a `rope.base.resources.File`"""
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
return parent.create_file(packages[-1] + '.py') | [
"def",
"create_module",
"(",
"project",
",",
"name",
",",
"sourcefolder",
"=",
"None",
")",
":",
"if",
"sourcefolder",
"is",
"None",
":",
"sourcefolder",
"=",
"project",
".",
"root",
"packages",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"parent",
"=",
... | Creates a module and returns a `rope.base.resources.File` | [
"Creates",
"a",
"module",
"and",
"returns",
"a",
"rope",
".",
"base",
".",
"resources",
".",
"File"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/generate.py#L19-L27 | train | 205,875 |
python-rope/rope | rope/contrib/generate.py | create_package | def create_package(project, name, sourcefolder=None):
"""Creates a package and returns a `rope.base.resources.Folder`"""
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
made_packages = parent.create_folder(packages[-1])
made_packages.create_file('__init__.py')
return made_packages | python | def create_package(project, name, sourcefolder=None):
"""Creates a package and returns a `rope.base.resources.Folder`"""
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
made_packages = parent.create_folder(packages[-1])
made_packages.create_file('__init__.py')
return made_packages | [
"def",
"create_package",
"(",
"project",
",",
"name",
",",
"sourcefolder",
"=",
"None",
")",
":",
"if",
"sourcefolder",
"is",
"None",
":",
"sourcefolder",
"=",
"project",
".",
"root",
"packages",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"parent",
"=",... | Creates a package and returns a `rope.base.resources.Folder` | [
"Creates",
"a",
"package",
"and",
"returns",
"a",
"rope",
".",
"base",
".",
"resources",
".",
"Folder"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/generate.py#L30-L40 | train | 205,876 |
python-rope/rope | rope/refactor/rename.py | rename_in_module | def rename_in_module(occurrences_finder, new_name, resource=None,
pymodule=None, replace_primary=False, region=None,
reads=True, writes=True):
"""Returns the changed source or `None` if there is no changes"""
if resource is not None:
source_code = resource.read()
else:
source_code = pymodule.source_code
change_collector = codeanalyze.ChangeCollector(source_code)
for occurrence in occurrences_finder.find_occurrences(resource, pymodule):
if replace_primary and occurrence.is_a_fixed_primary():
continue
if replace_primary:
start, end = occurrence.get_primary_range()
else:
start, end = occurrence.get_word_range()
if (not reads and not occurrence.is_written()) or \
(not writes and occurrence.is_written()):
continue
if region is None or region[0] <= start < region[1]:
change_collector.add_change(start, end, new_name)
return change_collector.get_changed() | python | def rename_in_module(occurrences_finder, new_name, resource=None,
pymodule=None, replace_primary=False, region=None,
reads=True, writes=True):
"""Returns the changed source or `None` if there is no changes"""
if resource is not None:
source_code = resource.read()
else:
source_code = pymodule.source_code
change_collector = codeanalyze.ChangeCollector(source_code)
for occurrence in occurrences_finder.find_occurrences(resource, pymodule):
if replace_primary and occurrence.is_a_fixed_primary():
continue
if replace_primary:
start, end = occurrence.get_primary_range()
else:
start, end = occurrence.get_word_range()
if (not reads and not occurrence.is_written()) or \
(not writes and occurrence.is_written()):
continue
if region is None or region[0] <= start < region[1]:
change_collector.add_change(start, end, new_name)
return change_collector.get_changed() | [
"def",
"rename_in_module",
"(",
"occurrences_finder",
",",
"new_name",
",",
"resource",
"=",
"None",
",",
"pymodule",
"=",
"None",
",",
"replace_primary",
"=",
"False",
",",
"region",
"=",
"None",
",",
"reads",
"=",
"True",
",",
"writes",
"=",
"True",
")",... | Returns the changed source or `None` if there is no changes | [
"Returns",
"the",
"changed",
"source",
"or",
"None",
"if",
"there",
"is",
"no",
"changes"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/rename.py#L186-L207 | train | 205,877 |
python-rope/rope | rope/refactor/rename.py | Rename.get_changes | def get_changes(self, new_name, in_file=None, in_hierarchy=False,
unsure=None, docs=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed for this refactoring
Parameters:
- `in_hierarchy`: when renaming a method this keyword forces
to rename all matching methods in the hierarchy
- `docs`: when `True` rename refactoring will rename
occurrences in comments and strings where the name is
visible. Setting it will make renames faster, too.
- `unsure`: decides what to do about unsure occurrences.
If `None`, they are ignored. Otherwise `unsure` is
called with an instance of `occurrence.Occurrence` as
parameter. If it returns `True`, the occurrence is
considered to be a match.
- `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.
- `in_file`: this argument has been deprecated; use
`resources` instead.
"""
if unsure in (True, False):
warnings.warn(
'unsure parameter should be a function that returns '
'True or False', DeprecationWarning, stacklevel=2)
def unsure_func(value=unsure):
return value
unsure = unsure_func
if in_file is not None:
warnings.warn(
'`in_file` argument has been deprecated; use `resources` '
'instead. ', DeprecationWarning, stacklevel=2)
if in_file:
resources = [self.resource]
if _is_local(self.old_pyname):
resources = [self.resource]
if resources is None:
resources = self.project.get_python_files()
changes = ChangeSet('Renaming <%s> to <%s>' %
(self.old_name, new_name))
finder = occurrences.create_finder(
self.project, self.old_name, self.old_pyname, unsure=unsure,
docs=docs, instance=self.old_instance,
in_hierarchy=in_hierarchy and self.is_method())
job_set = task_handle.create_jobset('Collecting Changes',
len(resources))
for file_ in resources:
job_set.started_job(file_.path)
new_content = rename_in_module(finder, new_name, resource=file_)
if new_content is not None:
changes.add_change(ChangeContents(file_, new_content))
job_set.finished_job()
if self._is_renaming_a_module():
resource = self.old_pyname.get_object().get_resource()
if self._is_allowed_to_move(resources, resource):
self._rename_module(resource, new_name, changes)
return changes | python | def get_changes(self, new_name, in_file=None, in_hierarchy=False,
unsure=None, docs=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed for this refactoring
Parameters:
- `in_hierarchy`: when renaming a method this keyword forces
to rename all matching methods in the hierarchy
- `docs`: when `True` rename refactoring will rename
occurrences in comments and strings where the name is
visible. Setting it will make renames faster, too.
- `unsure`: decides what to do about unsure occurrences.
If `None`, they are ignored. Otherwise `unsure` is
called with an instance of `occurrence.Occurrence` as
parameter. If it returns `True`, the occurrence is
considered to be a match.
- `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.
- `in_file`: this argument has been deprecated; use
`resources` instead.
"""
if unsure in (True, False):
warnings.warn(
'unsure parameter should be a function that returns '
'True or False', DeprecationWarning, stacklevel=2)
def unsure_func(value=unsure):
return value
unsure = unsure_func
if in_file is not None:
warnings.warn(
'`in_file` argument has been deprecated; use `resources` '
'instead. ', DeprecationWarning, stacklevel=2)
if in_file:
resources = [self.resource]
if _is_local(self.old_pyname):
resources = [self.resource]
if resources is None:
resources = self.project.get_python_files()
changes = ChangeSet('Renaming <%s> to <%s>' %
(self.old_name, new_name))
finder = occurrences.create_finder(
self.project, self.old_name, self.old_pyname, unsure=unsure,
docs=docs, instance=self.old_instance,
in_hierarchy=in_hierarchy and self.is_method())
job_set = task_handle.create_jobset('Collecting Changes',
len(resources))
for file_ in resources:
job_set.started_job(file_.path)
new_content = rename_in_module(finder, new_name, resource=file_)
if new_content is not None:
changes.add_change(ChangeContents(file_, new_content))
job_set.finished_job()
if self._is_renaming_a_module():
resource = self.old_pyname.get_object().get_resource()
if self._is_allowed_to_move(resources, resource):
self._rename_module(resource, new_name, changes)
return changes | [
"def",
"get_changes",
"(",
"self",
",",
"new_name",
",",
"in_file",
"=",
"None",
",",
"in_hierarchy",
"=",
"False",
",",
"unsure",
"=",
"None",
",",
"docs",
"=",
"False",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTas... | Get the changes needed for this refactoring
Parameters:
- `in_hierarchy`: when renaming a method this keyword forces
to rename all matching methods in the hierarchy
- `docs`: when `True` rename refactoring will rename
occurrences in comments and strings where the name is
visible. Setting it will make renames faster, too.
- `unsure`: decides what to do about unsure occurrences.
If `None`, they are ignored. Otherwise `unsure` is
called with an instance of `occurrence.Occurrence` as
parameter. If it returns `True`, the occurrence is
considered to be a match.
- `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.
- `in_file`: this argument has been deprecated; use
`resources` instead. | [
"Get",
"the",
"changes",
"needed",
"for",
"this",
"refactoring"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/rename.py#L45-L105 | train | 205,878 |
python-rope/rope | rope/base/simplify.py | real_code | def real_code(source):
"""Simplify `source` for analysis
It replaces:
* comments with spaces
* strs with a new str filled with spaces
* implicit and explicit continuations with spaces
* tabs and semicolons with spaces
The resulting code is a lot easier to analyze if we are interested
only in offsets.
"""
collector = codeanalyze.ChangeCollector(source)
for start, end in ignored_regions(source):
if source[start] == '#':
replacement = ' ' * (end - start)
else:
replacement = '"%s"' % (' ' * (end - start - 2))
collector.add_change(start, end, replacement)
source = collector.get_changed() or source
collector = codeanalyze.ChangeCollector(source)
parens = 0
for match in _parens.finditer(source):
i = match.start()
c = match.group()
if c in '({[':
parens += 1
if c in ')}]':
parens -= 1
if c == '\n' and parens > 0:
collector.add_change(i, i + 1, ' ')
source = collector.get_changed() or source
return source.replace('\\\n', ' ').replace('\t', ' ').replace(';', '\n') | python | def real_code(source):
"""Simplify `source` for analysis
It replaces:
* comments with spaces
* strs with a new str filled with spaces
* implicit and explicit continuations with spaces
* tabs and semicolons with spaces
The resulting code is a lot easier to analyze if we are interested
only in offsets.
"""
collector = codeanalyze.ChangeCollector(source)
for start, end in ignored_regions(source):
if source[start] == '#':
replacement = ' ' * (end - start)
else:
replacement = '"%s"' % (' ' * (end - start - 2))
collector.add_change(start, end, replacement)
source = collector.get_changed() or source
collector = codeanalyze.ChangeCollector(source)
parens = 0
for match in _parens.finditer(source):
i = match.start()
c = match.group()
if c in '({[':
parens += 1
if c in ')}]':
parens -= 1
if c == '\n' and parens > 0:
collector.add_change(i, i + 1, ' ')
source = collector.get_changed() or source
return source.replace('\\\n', ' ').replace('\t', ' ').replace(';', '\n') | [
"def",
"real_code",
"(",
"source",
")",
":",
"collector",
"=",
"codeanalyze",
".",
"ChangeCollector",
"(",
"source",
")",
"for",
"start",
",",
"end",
"in",
"ignored_regions",
"(",
"source",
")",
":",
"if",
"source",
"[",
"start",
"]",
"==",
"'#'",
":",
... | Simplify `source` for analysis
It replaces:
* comments with spaces
* strs with a new str filled with spaces
* implicit and explicit continuations with spaces
* tabs and semicolons with spaces
The resulting code is a lot easier to analyze if we are interested
only in offsets. | [
"Simplify",
"source",
"for",
"analysis"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/simplify.py#L11-L44 | train | 205,879 |
python-rope/rope | rope/base/simplify.py | ignored_regions | def ignored_regions(source):
"""Return ignored regions like strings and comments in `source` """
return [(match.start(), match.end()) for match in _str.finditer(source)] | python | def ignored_regions(source):
"""Return ignored regions like strings and comments in `source` """
return [(match.start(), match.end()) for match in _str.finditer(source)] | [
"def",
"ignored_regions",
"(",
"source",
")",
":",
"return",
"[",
"(",
"match",
".",
"start",
"(",
")",
",",
"match",
".",
"end",
"(",
")",
")",
"for",
"match",
"in",
"_str",
".",
"finditer",
"(",
"source",
")",
"]"
] | Return ignored regions like strings and comments in `source` | [
"Return",
"ignored",
"regions",
"like",
"strings",
"and",
"comments",
"in",
"source"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/simplify.py#L48-L50 | train | 205,880 |
python-rope/rope | rope/base/resources.py | Resource.move | def move(self, new_location):
"""Move resource to `new_location`"""
self._perform_change(change.MoveResource(self, new_location),
'Moving <%s> to <%s>' % (self.path, new_location)) | python | def move(self, new_location):
"""Move resource to `new_location`"""
self._perform_change(change.MoveResource(self, new_location),
'Moving <%s> to <%s>' % (self.path, new_location)) | [
"def",
"move",
"(",
"self",
",",
"new_location",
")",
":",
"self",
".",
"_perform_change",
"(",
"change",
".",
"MoveResource",
"(",
"self",
",",
"new_location",
")",
",",
"'Moving <%s> to <%s>'",
"%",
"(",
"self",
".",
"path",
",",
"new_location",
")",
")"... | Move resource to `new_location` | [
"Move",
"resource",
"to",
"new_location"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/resources.py#L44-L47 | train | 205,881 |
python-rope/rope | rope/base/resources.py | Folder.get_children | def get_children(self):
"""Return the children of this folder"""
try:
children = os.listdir(self.real_path)
except OSError:
return []
result = []
for name in children:
try:
child = self.get_child(name)
except exceptions.ResourceNotFoundError:
continue
if not self.project.is_ignored(child):
result.append(self.get_child(name))
return result | python | def get_children(self):
"""Return the children of this folder"""
try:
children = os.listdir(self.real_path)
except OSError:
return []
result = []
for name in children:
try:
child = self.get_child(name)
except exceptions.ResourceNotFoundError:
continue
if not self.project.is_ignored(child):
result.append(self.get_child(name))
return result | [
"def",
"get_children",
"(",
"self",
")",
":",
"try",
":",
"children",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"real_path",
")",
"except",
"OSError",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"children",
":",
"try",
... | Return the children of this folder | [
"Return",
"the",
"children",
"of",
"this",
"folder"
] | 1c9f9cd5964b099a99a9111e998f0dc728860688 | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/resources.py#L147-L161 | train | 205,882 |
edx/event-tracking | eventtracking/backends/mongodb.py | MongoBackend._create_indexes | def _create_indexes(self):
"""Ensures the proper fields are indexed"""
# WARNING: The collection will be locked during the index
# creation. If the collection has a large number of
# documents in it, the operation can take a long time.
# TODO: The creation of indexes can be moved to a Django
# management command or equivalent. There is also an option to
# run the indexing on the background, without locking.
self.collection.ensure_index([('time', pymongo.DESCENDING)])
self.collection.ensure_index('name') | python | def _create_indexes(self):
"""Ensures the proper fields are indexed"""
# WARNING: The collection will be locked during the index
# creation. If the collection has a large number of
# documents in it, the operation can take a long time.
# TODO: The creation of indexes can be moved to a Django
# management command or equivalent. There is also an option to
# run the indexing on the background, without locking.
self.collection.ensure_index([('time', pymongo.DESCENDING)])
self.collection.ensure_index('name') | [
"def",
"_create_indexes",
"(",
"self",
")",
":",
"# WARNING: The collection will be locked during the index",
"# creation. If the collection has a large number of",
"# documents in it, the operation can take a long time.",
"# TODO: The creation of indexes can be moved to a Django",
"# management... | Ensures the proper fields are indexed | [
"Ensures",
"the",
"proper",
"fields",
"are",
"indexed"
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/mongodb.py#L75-L85 | train | 205,883 |
edx/event-tracking | eventtracking/backends/mongodb.py | MongoBackend.send | def send(self, event):
"""Insert the event in to the Mongo collection"""
try:
self.collection.insert(event, manipulate=False)
except (PyMongoError, BSONError):
# The event will be lost in case of a connection error or any error
# that occurs when trying to insert the event into Mongo.
# pymongo will re-connect/re-authenticate automatically
# during the next event.
msg = 'Error inserting to MongoDB event tracker backend'
log.exception(msg) | python | def send(self, event):
"""Insert the event in to the Mongo collection"""
try:
self.collection.insert(event, manipulate=False)
except (PyMongoError, BSONError):
# The event will be lost in case of a connection error or any error
# that occurs when trying to insert the event into Mongo.
# pymongo will re-connect/re-authenticate automatically
# during the next event.
msg = 'Error inserting to MongoDB event tracker backend'
log.exception(msg) | [
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"collection",
".",
"insert",
"(",
"event",
",",
"manipulate",
"=",
"False",
")",
"except",
"(",
"PyMongoError",
",",
"BSONError",
")",
":",
"# The event will be lost in case of a co... | Insert the event in to the Mongo collection | [
"Insert",
"the",
"event",
"in",
"to",
"the",
"Mongo",
"collection"
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/mongodb.py#L87-L97 | train | 205,884 |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.create_backends_from_settings | def create_backends_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
'endpoint': 'http://something/event'
}
},
'another_engine': {
'ENGINE': 'some.arbitrary.OtherBackend',
'OPTIONS': {
'user': 'foo'
}
},
}
"""
config = getattr(settings, DJANGO_BACKEND_SETTING_NAME, {})
backends = self.instantiate_objects(config)
return backends | python | def create_backends_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
'endpoint': 'http://something/event'
}
},
'another_engine': {
'ENGINE': 'some.arbitrary.OtherBackend',
'OPTIONS': {
'user': 'foo'
}
},
}
"""
config = getattr(settings, DJANGO_BACKEND_SETTING_NAME, {})
backends = self.instantiate_objects(config)
return backends | [
"def",
"create_backends_from_settings",
"(",
"self",
")",
":",
"config",
"=",
"getattr",
"(",
"settings",
",",
"DJANGO_BACKEND_SETTING_NAME",
",",
"{",
"}",
")",
"backends",
"=",
"self",
".",
"instantiate_objects",
"(",
"config",
")",
"return",
"backends"
] | Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
'endpoint': 'http://something/event'
}
},
'another_engine': {
'ENGINE': 'some.arbitrary.OtherBackend',
'OPTIONS': {
'user': 'foo'
}
},
} | [
"Expects",
"the",
"Django",
"setting",
"EVENT_TRACKING_BACKENDS",
"to",
"be",
"defined",
"and",
"point",
"to",
"a",
"dictionary",
"of",
"backend",
"engine",
"configurations",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L31-L57 | train | 205,885 |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.instantiate_objects | def instantiate_objects(self, node):
"""
Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated
Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the
special "ENGINE" key which indicates that a class of that type should be instantiated and passed all key-value
pairs found in the sibling "OPTIONS" dictionary as keyword arguments.
For example::
tree = {
'a': {
'b': {
'first_obj': {
'ENGINE': 'mypackage.mymodule.Clazz',
'OPTIONS': {
'size': 10,
'foo': 'bar'
}
}
},
'c': [
{
'ENGINE': 'mypackage.mymodule.Clazz2',
'OPTIONS': {
'more_objects': {
'd': {'ENGINE': 'mypackage.foo.Bar'}
}
}
}
]
}
}
root = self.instantiate_objects(tree)
That structure of dicts, lists, and strings will end up with (this example assumes that all keyword arguments to
constructors were saved as attributes of the same name):
assert type(root['a']['b']['first_obj']) == <type 'mypackage.mymodule.Clazz'>
assert root['a']['b']['first_obj'].size == 10
assert root['a']['b']['first_obj'].foo == 'bar'
assert type(root['a']['c'][0]) == <type 'mypackage.mymodule.Clazz2'>
assert type(root['a']['c'][0].more_objects['d']) == <type 'mypackage.foo.Bar'>
"""
result = node
if isinstance(node, dict):
if 'ENGINE' in node:
result = self.instantiate_from_dict(node)
else:
result = {}
for key, value in six.iteritems(node):
result[key] = self.instantiate_objects(value)
elif isinstance(node, list):
result = []
for child in node:
result.append(self.instantiate_objects(child))
return result | python | def instantiate_objects(self, node):
"""
Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated
Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the
special "ENGINE" key which indicates that a class of that type should be instantiated and passed all key-value
pairs found in the sibling "OPTIONS" dictionary as keyword arguments.
For example::
tree = {
'a': {
'b': {
'first_obj': {
'ENGINE': 'mypackage.mymodule.Clazz',
'OPTIONS': {
'size': 10,
'foo': 'bar'
}
}
},
'c': [
{
'ENGINE': 'mypackage.mymodule.Clazz2',
'OPTIONS': {
'more_objects': {
'd': {'ENGINE': 'mypackage.foo.Bar'}
}
}
}
]
}
}
root = self.instantiate_objects(tree)
That structure of dicts, lists, and strings will end up with (this example assumes that all keyword arguments to
constructors were saved as attributes of the same name):
assert type(root['a']['b']['first_obj']) == <type 'mypackage.mymodule.Clazz'>
assert root['a']['b']['first_obj'].size == 10
assert root['a']['b']['first_obj'].foo == 'bar'
assert type(root['a']['c'][0]) == <type 'mypackage.mymodule.Clazz2'>
assert type(root['a']['c'][0].more_objects['d']) == <type 'mypackage.foo.Bar'>
"""
result = node
if isinstance(node, dict):
if 'ENGINE' in node:
result = self.instantiate_from_dict(node)
else:
result = {}
for key, value in six.iteritems(node):
result[key] = self.instantiate_objects(value)
elif isinstance(node, list):
result = []
for child in node:
result.append(self.instantiate_objects(child))
return result | [
"def",
"instantiate_objects",
"(",
"self",
",",
"node",
")",
":",
"result",
"=",
"node",
"if",
"isinstance",
"(",
"node",
",",
"dict",
")",
":",
"if",
"'ENGINE'",
"in",
"node",
":",
"result",
"=",
"self",
".",
"instantiate_from_dict",
"(",
"node",
")",
... | Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated
Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the
special "ENGINE" key which indicates that a class of that type should be instantiated and passed all key-value
pairs found in the sibling "OPTIONS" dictionary as keyword arguments.
For example::
tree = {
'a': {
'b': {
'first_obj': {
'ENGINE': 'mypackage.mymodule.Clazz',
'OPTIONS': {
'size': 10,
'foo': 'bar'
}
}
},
'c': [
{
'ENGINE': 'mypackage.mymodule.Clazz2',
'OPTIONS': {
'more_objects': {
'd': {'ENGINE': 'mypackage.foo.Bar'}
}
}
}
]
}
}
root = self.instantiate_objects(tree)
That structure of dicts, lists, and strings will end up with (this example assumes that all keyword arguments to
constructors were saved as attributes of the same name):
assert type(root['a']['b']['first_obj']) == <type 'mypackage.mymodule.Clazz'>
assert root['a']['b']['first_obj'].size == 10
assert root['a']['b']['first_obj'].foo == 'bar'
assert type(root['a']['c'][0]) == <type 'mypackage.mymodule.Clazz2'>
assert type(root['a']['c'][0].more_objects['d']) == <type 'mypackage.foo.Bar'> | [
"Recursively",
"traverse",
"a",
"structure",
"to",
"identify",
"dictionaries",
"that",
"represent",
"objects",
"that",
"need",
"to",
"be",
"instantiated"
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L59-L116 | train | 205,886 |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.instantiate_from_dict | def instantiate_from_dict(self, values):
"""
Constructs an object given a dictionary containing an "ENGINE" key
which contains the full module path to the class, and an "OPTIONS"
key which contains a dictionary that will be passed in to the
constructor as keyword args.
"""
name = values['ENGINE']
options = values.get('OPTIONS', {})
# Parse the name
parts = name.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
# Get the class
try:
module = import_module(module_name)
cls = getattr(module, class_name)
except (ValueError, AttributeError, TypeError, ImportError):
raise ValueError('Cannot find class %s' % name)
options = self.instantiate_objects(options)
return cls(**options) | python | def instantiate_from_dict(self, values):
"""
Constructs an object given a dictionary containing an "ENGINE" key
which contains the full module path to the class, and an "OPTIONS"
key which contains a dictionary that will be passed in to the
constructor as keyword args.
"""
name = values['ENGINE']
options = values.get('OPTIONS', {})
# Parse the name
parts = name.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
# Get the class
try:
module = import_module(module_name)
cls = getattr(module, class_name)
except (ValueError, AttributeError, TypeError, ImportError):
raise ValueError('Cannot find class %s' % name)
options = self.instantiate_objects(options)
return cls(**options) | [
"def",
"instantiate_from_dict",
"(",
"self",
",",
"values",
")",
":",
"name",
"=",
"values",
"[",
"'ENGINE'",
"]",
"options",
"=",
"values",
".",
"get",
"(",
"'OPTIONS'",
",",
"{",
"}",
")",
"# Parse the name",
"parts",
"=",
"name",
".",
"split",
"(",
... | Constructs an object given a dictionary containing an "ENGINE" key
which contains the full module path to the class, and an "OPTIONS"
key which contains a dictionary that will be passed in to the
constructor as keyword args. | [
"Constructs",
"an",
"object",
"given",
"a",
"dictionary",
"containing",
"an",
"ENGINE",
"key",
"which",
"contains",
"the",
"full",
"module",
"path",
"to",
"the",
"class",
"and",
"an",
"OPTIONS",
"key",
"which",
"contains",
"a",
"dictionary",
"that",
"will",
... | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L118-L143 | train | 205,887 |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.create_processors_from_settings | def create_processors_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.Processor'
},
{
'ENGINE': 'some.arbitrary.OtherProcessor',
'OPTIONS': {
'user': 'foo'
}
},
]
"""
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors | python | def create_processors_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.Processor'
},
{
'ENGINE': 'some.arbitrary.OtherProcessor',
'OPTIONS': {
'user': 'foo'
}
},
]
"""
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors | [
"def",
"create_processors_from_settings",
"(",
"self",
")",
":",
"config",
"=",
"getattr",
"(",
"settings",
",",
"DJANGO_PROCESSOR_SETTING_NAME",
",",
"[",
"]",
")",
"processors",
"=",
"self",
".",
"instantiate_objects",
"(",
"config",
")",
"return",
"processors"
... | Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.Processor'
},
{
'ENGINE': 'some.arbitrary.OtherProcessor',
'OPTIONS': {
'user': 'foo'
}
},
] | [
"Expects",
"the",
"Django",
"setting",
"EVENT_TRACKING_PROCESSORS",
"to",
"be",
"defined",
"and",
"point",
"to",
"a",
"list",
"of",
"backend",
"engine",
"configurations",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L145-L168 | train | 205,888 |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.register_backend | def register_backend(self, name, backend):
"""
Register a new backend that will be called for each processed event.
Note that backends are called in the order that they are registered.
"""
if not hasattr(backend, 'send') or not callable(backend.send):
raise ValueError('Backend %s does not have a callable "send" method.' % backend.__class__.__name__)
else:
self.backends[name] = backend | python | def register_backend(self, name, backend):
"""
Register a new backend that will be called for each processed event.
Note that backends are called in the order that they are registered.
"""
if not hasattr(backend, 'send') or not callable(backend.send):
raise ValueError('Backend %s does not have a callable "send" method.' % backend.__class__.__name__)
else:
self.backends[name] = backend | [
"def",
"register_backend",
"(",
"self",
",",
"name",
",",
"backend",
")",
":",
"if",
"not",
"hasattr",
"(",
"backend",
",",
"'send'",
")",
"or",
"not",
"callable",
"(",
"backend",
".",
"send",
")",
":",
"raise",
"ValueError",
"(",
"'Backend %s does not hav... | Register a new backend that will be called for each processed event.
Note that backends are called in the order that they are registered. | [
"Register",
"a",
"new",
"backend",
"that",
"will",
"be",
"called",
"for",
"each",
"processed",
"event",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L55-L64 | train | 205,889 |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.register_processor | def register_processor(self, processor):
"""
Register a new processor.
Note that processors are called in the order that they are registered.
"""
if not callable(processor):
raise ValueError('Processor %s is not callable.' % processor.__class__.__name__)
else:
self.processors.append(processor) | python | def register_processor(self, processor):
"""
Register a new processor.
Note that processors are called in the order that they are registered.
"""
if not callable(processor):
raise ValueError('Processor %s is not callable.' % processor.__class__.__name__)
else:
self.processors.append(processor) | [
"def",
"register_processor",
"(",
"self",
",",
"processor",
")",
":",
"if",
"not",
"callable",
"(",
"processor",
")",
":",
"raise",
"ValueError",
"(",
"'Processor %s is not callable.'",
"%",
"processor",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"se... | Register a new processor.
Note that processors are called in the order that they are registered. | [
"Register",
"a",
"new",
"processor",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L66-L75 | train | 205,890 |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.send | def send(self, event):
"""
Process the event using all registered processors and send it to all registered backends.
Logs and swallows all `Exception`.
"""
try:
processed_event = self.process_event(event)
except EventEmissionExit:
return
else:
self.send_to_backends(processed_event) | python | def send(self, event):
"""
Process the event using all registered processors and send it to all registered backends.
Logs and swallows all `Exception`.
"""
try:
processed_event = self.process_event(event)
except EventEmissionExit:
return
else:
self.send_to_backends(processed_event) | [
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"processed_event",
"=",
"self",
".",
"process_event",
"(",
"event",
")",
"except",
"EventEmissionExit",
":",
"return",
"else",
":",
"self",
".",
"send_to_backends",
"(",
"processed_event",
")"
] | Process the event using all registered processors and send it to all registered backends.
Logs and swallows all `Exception`. | [
"Process",
"the",
"event",
"using",
"all",
"registered",
"processors",
"and",
"send",
"it",
"to",
"all",
"registered",
"backends",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L77-L88 | train | 205,891 |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.send_to_backends | def send_to_backends(self, event):
"""
Sends the event to all registered backends.
Logs and swallows all `Exception`.
"""
for name, backend in six.iteritems(self.backends):
try:
backend.send(event)
except Exception: # pylint: disable=broad-except
LOG.exception(
'Unable to send event to backend: %s', name
) | python | def send_to_backends(self, event):
"""
Sends the event to all registered backends.
Logs and swallows all `Exception`.
"""
for name, backend in six.iteritems(self.backends):
try:
backend.send(event)
except Exception: # pylint: disable=broad-except
LOG.exception(
'Unable to send event to backend: %s', name
) | [
"def",
"send_to_backends",
"(",
"self",
",",
"event",
")",
":",
"for",
"name",
",",
"backend",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"backends",
")",
":",
"try",
":",
"backend",
".",
"send",
"(",
"event",
")",
"except",
"Exception",
":",
"... | Sends the event to all registered backends.
Logs and swallows all `Exception`. | [
"Sends",
"the",
"event",
"to",
"all",
"registered",
"backends",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L121-L134 | train | 205,892 |
edx/event-tracking | eventtracking/tracker.py | Tracker.emit | def emit(self, name=None, data=None):
"""
Emit an event annotated with the UTC time when this function was called.
`name` is a unique identification string for an event that has
already been registered.
`data` is a dictionary mapping field names to the value to include in the event.
Note that all values provided must be serializable.
"""
event = {
'name': name or UNKNOWN_EVENT_TYPE,
'timestamp': datetime.now(UTC),
'data': data or {},
'context': self.resolve_context()
}
self.routing_backend.send(event) | python | def emit(self, name=None, data=None):
"""
Emit an event annotated with the UTC time when this function was called.
`name` is a unique identification string for an event that has
already been registered.
`data` is a dictionary mapping field names to the value to include in the event.
Note that all values provided must be serializable.
"""
event = {
'name': name or UNKNOWN_EVENT_TYPE,
'timestamp': datetime.now(UTC),
'data': data or {},
'context': self.resolve_context()
}
self.routing_backend.send(event) | [
"def",
"emit",
"(",
"self",
",",
"name",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"event",
"=",
"{",
"'name'",
":",
"name",
"or",
"UNKNOWN_EVENT_TYPE",
",",
"'timestamp'",
":",
"datetime",
".",
"now",
"(",
"UTC",
")",
",",
"'data'",
":",
"d... | Emit an event annotated with the UTC time when this function was called.
`name` is a unique identification string for an event that has
already been registered.
`data` is a dictionary mapping field names to the value to include in the event.
Note that all values provided must be serializable. | [
"Emit",
"an",
"event",
"annotated",
"with",
"the",
"UTC",
"time",
"when",
"this",
"function",
"was",
"called",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L65-L82 | train | 205,893 |
edx/event-tracking | eventtracking/tracker.py | Tracker.resolve_context | def resolve_context(self):
"""
Create a new dictionary that corresponds to the union of all of the
contexts that have been entered but not exited at this point.
"""
merged = dict()
for context in self.located_context.values():
merged.update(context)
return merged | python | def resolve_context(self):
"""
Create a new dictionary that corresponds to the union of all of the
contexts that have been entered but not exited at this point.
"""
merged = dict()
for context in self.located_context.values():
merged.update(context)
return merged | [
"def",
"resolve_context",
"(",
"self",
")",
":",
"merged",
"=",
"dict",
"(",
")",
"for",
"context",
"in",
"self",
".",
"located_context",
".",
"values",
"(",
")",
":",
"merged",
".",
"update",
"(",
"context",
")",
"return",
"merged"
] | Create a new dictionary that corresponds to the union of all of the
contexts that have been entered but not exited at this point. | [
"Create",
"a",
"new",
"dictionary",
"that",
"corresponds",
"to",
"the",
"union",
"of",
"all",
"of",
"the",
"contexts",
"that",
"have",
"been",
"entered",
"but",
"not",
"exited",
"at",
"this",
"point",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L84-L92 | train | 205,894 |
edx/event-tracking | eventtracking/tracker.py | Tracker.context | def context(self, name, ctx):
"""
Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context.
"""
self.enter_context(name, ctx)
try:
yield
finally:
self.exit_context(name) | python | def context(self, name, ctx):
"""
Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context.
"""
self.enter_context(name, ctx)
try:
yield
finally:
self.exit_context(name) | [
"def",
"context",
"(",
"self",
",",
"name",
",",
"ctx",
")",
":",
"self",
".",
"enter_context",
"(",
"name",
",",
"ctx",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"exit_context",
"(",
"name",
")"
] | Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context. | [
"Execute",
"the",
"block",
"with",
"the",
"given",
"context",
"applied",
".",
"This",
"manager",
"ensures",
"that",
"the",
"context",
"is",
"removed",
"even",
"if",
"an",
"exception",
"is",
"raised",
"within",
"the",
"context",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L111-L121 | train | 205,895 |
edx/event-tracking | eventtracking/locator.py | ThreadLocalContextLocator.get | def get(self):
"""Return a reference to a thread-specific context"""
if not self.thread_local_data:
self.thread_local_data = threading.local()
if not hasattr(self.thread_local_data, 'context'):
self.thread_local_data.context = OrderedDict()
return self.thread_local_data.context | python | def get(self):
"""Return a reference to a thread-specific context"""
if not self.thread_local_data:
self.thread_local_data = threading.local()
if not hasattr(self.thread_local_data, 'context'):
self.thread_local_data.context = OrderedDict()
return self.thread_local_data.context | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"thread_local_data",
":",
"self",
".",
"thread_local_data",
"=",
"threading",
".",
"local",
"(",
")",
"if",
"not",
"hasattr",
"(",
"self",
".",
"thread_local_data",
",",
"'context'",
")",
":"... | Return a reference to a thread-specific context | [
"Return",
"a",
"reference",
"to",
"a",
"thread",
"-",
"specific",
"context"
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/locator.py#L47-L55 | train | 205,896 |
edx/event-tracking | eventtracking/backends/logger.py | LoggerBackend.send | def send(self, event):
"""Send the event to the standard python logger"""
event_str = json.dumps(event, cls=DateTimeJSONEncoder)
# TODO: do something smarter than simply dropping the event on
# the floor.
if self.max_event_size is None or len(event_str) <= self.max_event_size:
self.log(event_str) | python | def send(self, event):
"""Send the event to the standard python logger"""
event_str = json.dumps(event, cls=DateTimeJSONEncoder)
# TODO: do something smarter than simply dropping the event on
# the floor.
if self.max_event_size is None or len(event_str) <= self.max_event_size:
self.log(event_str) | [
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"event_str",
"=",
"json",
".",
"dumps",
"(",
"event",
",",
"cls",
"=",
"DateTimeJSONEncoder",
")",
"# TODO: do something smarter than simply dropping the event on",
"# the floor.",
"if",
"self",
".",
"max_event_siz... | Send the event to the standard python logger | [
"Send",
"the",
"event",
"to",
"the",
"standard",
"python",
"logger"
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/logger.py#L35-L42 | train | 205,897 |
edx/event-tracking | eventtracking/backends/logger.py | DateTimeJSONEncoder.default | def default(self, obj): # lint-amnesty, pylint: disable=arguments-differ, method-hidden
"""
Serialize datetime and date objects of iso format.
datatime objects are converted to UTC.
"""
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj) # pylint: disable=no-value-for-parameter
else:
# Convert to UTC datetime objects from other timezones
obj = obj.astimezone(UTC)
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
return super(DateTimeJSONEncoder, self).default(obj) | python | def default(self, obj): # lint-amnesty, pylint: disable=arguments-differ, method-hidden
"""
Serialize datetime and date objects of iso format.
datatime objects are converted to UTC.
"""
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj) # pylint: disable=no-value-for-parameter
else:
# Convert to UTC datetime objects from other timezones
obj = obj.astimezone(UTC)
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
return super(DateTimeJSONEncoder, self).default(obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"# lint-amnesty, pylint: disable=arguments-differ, method-hidden",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
")",
":",
"if",
"obj",
".",
"tzinfo",
"is",
"None",
":",
"# Localize to UTC naive datetime objects"... | Serialize datetime and date objects of iso format.
datatime objects are converted to UTC. | [
"Serialize",
"datetime",
"and",
"date",
"objects",
"of",
"iso",
"format",
"."
] | 8f993560545061d77f11615f5e3865b3916d5ea9 | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/logger.py#L48-L66 | train | 205,898 |
ryan-roemer/sphinx-bootstrap-theme | sphinx_bootstrap_theme/__init__.py | get_html_theme_path | def get_html_theme_path():
"""Return list of HTML theme paths."""
theme_path = os.path.abspath(os.path.dirname(__file__))
return [theme_path] | python | def get_html_theme_path():
"""Return list of HTML theme paths."""
theme_path = os.path.abspath(os.path.dirname(__file__))
return [theme_path] | [
"def",
"get_html_theme_path",
"(",
")",
":",
"theme_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"[",
"theme_path",
"]"
] | Return list of HTML theme paths. | [
"Return",
"list",
"of",
"HTML",
"theme",
"paths",
"."
] | 69585281a300116fa9da37c29c333ab1cc5462ce | https://github.com/ryan-roemer/sphinx-bootstrap-theme/blob/69585281a300116fa9da37c29c333ab1cc5462ce/sphinx_bootstrap_theme/__init__.py#L9-L12 | train | 205,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.