text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _listen(self):
"""Listen for messages passed from parent This method distributes messages received via stdin to their corresponding channel. Based on the format of the incoming message, the message is forwarded to its corresponding channel to be processed by its corresponding handler. """ |
def _listen():
"""This runs in a thread"""
for line in iter(sys.stdin.readline, b""):
try:
response = json.loads(line)
except Exception as e:
# The parent has passed on a message that
# isn't formatted in any particular way.
# This is likely a bug.
raise e
else:
if response.get("header") == "pyblish-qml:popen.response":
self.channels["response"].put(line)
elif response.get("header") == "pyblish-qml:popen.parent":
self.channels["parent"].put(line)
elif response.get("header") == "pyblish-qml:server.pulse":
self._kill.cancel() # reset timer
self._self_destruct()
else:
# The parent has passed on a message that
# is JSON, but not in any format we recognise.
# This is likely a bug.
raise Exception("Unhandled message "
"passed to Popen, '%s'" % line)
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dispatch(self, func, args=None):
"""Send message to parent process Arguments: func (str):
Name of function for parent to call args (list, optional):
Arguments passed to function when called """ |
data = json.dumps(
{
"header": "pyblish-qml:popen.request",
"payload": {
"name": func,
"args": args or list(),
}
}
)
# This should never happen. Each request is immediately
# responded to, always. If it isn't the next line will block.
# If multiple responses were made, then this will fail.
# Both scenarios are bugs.
assert self.channels["response"].empty(), (
"There were pending messages in the response channel")
sys.stdout.write(data + "\n")
sys.stdout.flush()
try:
message = self.channels["response"].get()
if six.PY3:
response = json.loads(message)
else:
response = _byteify(json.loads(message, object_hook=_byteify))
except TypeError as e:
raise e
else:
assert response["header"] == "pyblish-qml:popen.response", response
return response["payload"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, plugin):
"""Build PluginProxy object from incoming dictionary Emulate a plug-in by providing access to attributes in the same way they are accessed using the remote object. This allows for it to be used by members of :mod:`pyblish.logic`. """ |
process = None
repair = None
name = plugin["name"] + "Proxy"
cls = type(name, (cls,), plugin)
# Emulate function
for name in ("process", "repair"):
args = ", ".join(plugin["process"]["args"])
func = "def {name}({args}): pass".format(name=name,
args=args)
exec(func)
cls.process = process
cls.repair = repair
cls.__orig__ = plugin
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Item(**kwargs):
"""Factory function for QAbstractListModel items Any class attributes are converted into pyqtProperties and must be declared with its type as value. Special keyword "parent" is not passed as object properties but instead passed to the QObject constructor. Usage: """ |
parent = kwargs.pop("parent", None)
cls = type("Item", (AbstractItem,), kwargs.copy())
self = cls(parent)
self.json = kwargs # Store as json
for key, value in kwargs.items():
if hasattr(self, key):
key = PropertyType.prefix + key
setattr(self, key, value)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, item):
"""Add new item to model Each keyword argument is passed to the :func:Item factory function. """ |
self.beginInsertRows(QtCore.QModelIndex(),
self.rowCount(),
self.rowCount())
item["parent"] = self
item = Item(**item)
self.items.append(item)
self.endInsertRows()
item.__datachanged__.connect(self._dataChanged)
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_item(self, item):
"""Remove item from model""" |
index = self.items.index(item)
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.items.remove(item)
self.endRemoveRows() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dataChanged(self, item):
"""Explicitly emit dataChanged upon item changing""" |
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_plugin(self, plugin):
"""Append `plugin` to model Arguments: plugin (dict):
Serialised plug-in from pyblish-rpc Schema: plugin.json """ |
item = {}
item.update(defaults["common"])
item.update(defaults["plugin"])
for member in ["pre11",
"name",
"label",
"optional",
"category",
"actions",
"id",
"order",
"doc",
"type",
"module",
"match",
"hasRepair",
"families",
"contextEnabled",
"instanceEnabled",
"__instanceEnabled__",
"path"]:
item[member] = plugin[member]
# Visualised in Perspective
item["familiesConcatenated"] = ", ".join(plugin["families"])
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if item["doc"] and re.search(pattern, item["doc"]):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
item["doc"] = re.sub(pattern, html, item["doc"])
# Append GUI-only data
item["itemType"] = "plugin"
item["hasCompatible"] = True
item["isToggled"] = plugin.get("active", True)
item["verb"] = {
"Selector": "Collect",
"Collector": "Collect",
"Validator": "Validate",
"Extractor": "Extract",
"Integrator": "Integrate",
"Conformer": "Integrate",
}.get(item["type"], "Other")
for action in item["actions"]:
if action["on"] == "all":
item["actionsIconVisible"] = True
self.add_section(item["verb"])
item = self.add_item(item)
self.plugins.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_instance(self, instance):
"""Append `instance` to model Arguments: instance (dict):
Serialised instance Schema: instance.json """ |
assert isinstance(instance, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(instance["data"])
item.update(instance)
item["itemType"] = "instance"
item["isToggled"] = instance["data"].get("publish", True)
item["hasCompatible"] = True
item["category"] = item["category"] or item["family"]
self.add_section(item["category"])
# Visualised in Perspective
families = [instance["data"]["family"]]
families.extend(instance["data"].get("families", []))
item["familiesConcatenated"] += ", ".join(families)
item = self.add_item(item)
self.instances.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_instance(self, item):
"""Remove `instance` from model""" |
self.instances.remove(item)
self.remove_item(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_section(self, name):
"""Append `section` to model Arguments: name (str):
Name of section """ |
assert isinstance(name, str)
# Skip existing sections
for section in self.sections:
if section.name == name:
return section
item = defaults["common"].copy()
item["name"] = name
item["itemType"] = "section"
item = self.add_item(item)
self.sections.append(item)
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_context(self, context, label=None):
"""Append `context` to model Arguments: context (dict):
Serialised to add Schema: context.json """ |
assert isinstance(context, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(context)
item["family"] = None
item["label"] = context["data"].get("label") or settings.ContextLabel
item["itemType"] = "instance"
item["isToggled"] = True
item["optional"] = False
item["hasCompatible"] = True
item = self.add_item(item)
self.instances.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_with_result(self, result):
"""Update item-model with result from host State is sent from host after processing had taken place and represents the events that took place; including log messages and completion status. Arguments: result (dict):
Dictionary following the Result schema """ |
assert isinstance(result, dict), "%s is not a dictionary" % result
for type in ("instance", "plugin"):
id = (result[type] or {}).get("id")
is_context = not id
if is_context:
item = self.instances[0]
else:
item = self.items.get(id)
if item is None:
# If an item isn't there yet
# no worries. It's probably because
# reset is still running and the
# item in question is a new instance
# not yet added to the model.
continue
item.isProcessing = False
item.currentProgress = 1
item.processed = True
item.hasWarning = item.hasWarning or any([
record["levelno"] == logging.WARNING
for record in result["records"]
])
if result.get("error"):
item.hasError = True
item.amountFailed += 1
else:
item.succeeded = True
item.amountPassed += 1
item.duration += result["duration"]
item.finishedAt = time.time()
if item.itemType == "plugin" and not item.actionsIconVisible:
actions = list(item.actions)
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if actions:
item.actionsIconVisible = True
# Update section item
class DummySection(object):
hasWarning = False
hasError = False
succeeded = False
section_item = DummySection()
for section in self.sections:
if item.itemType == "plugin" and section.name == item.verb:
section_item = section
if (item.itemType == "instance" and
section.name == item.category):
section_item = section
section_item.hasWarning = (
section_item.hasWarning or item.hasWarning
)
section_item.hasError = section_item.hasError or item.hasError
section_item.succeeded = section_item.succeeded or item.succeeded
section_item.isProcessing = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_status(self):
"""Reset progress bars""" |
for item in self.items:
item.isProcessing = False
item.currentProgress = 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_exclusion(self, role, value):
"""Exclude item if `role` equals `value` Attributes: role (int, string):
Qt role or name to compare `value` to value (object):
Value to exclude """ |
self._add_rule(self.excludes, role, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_inclusion(self, role, value):
"""Include item if `role` equals `value` Attributes: role (int):
Qt role to compare `value` to value (object):
Value to exclude """ |
self._add_rule(self.includes, role, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_records(records):
"""Serialise multiple records""" |
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_record(record):
"""Serialise LogRecord instance""" |
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
"thread",
"created",
"process",
"processName",
"args",
"module",
"filename",
"levelno",
"exc_text",
"pathname",
"lineno",
"msg",
"exc_info",
"funcName",
"relativeCreated",
"levelname",
"msecs")
)
# Humanise output and conform to Exceptions
record["message"] = str(record.pop("msg"))
if os.getenv("PYBLISH_SAFE"):
schema.validate(record, "record")
return record |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_plugins(plugins):
"""Serialise multiple plug-in Returns: List of JSON-compatible plug-ins """ |
formatted = []
for plugin_ in plugins:
formatted_plugin = format_plugin(plugin_)
formatted.append(formatted_plugin)
return formatted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterator(plugins, context):
"""An iterator for plug-in and instance pairs""" |
test = pyblish.logic.registered_test()
state = {
"nextOrder": None,
"ordersWithError": set()
}
for plugin in plugins:
state["nextOrder"] = plugin.order
message = test(**state)
if message:
raise StopIteration("Stopped due to %s" % message)
instances = pyblish.api.instances_by_plugin(context, plugin)
if plugin.__instanceEnabled__:
for instance in instances:
yield plugin, instance
else:
yield plugin, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPluginActions(self, index):
"""Return actions from plug-in at `index` Arguments: index (int):
Index at which item is located in model """ |
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, QtCore.QModelIndex())).row()
item = self.data["models"]["item"].items[index]
# Inject reference to the original index
actions = [
dict(action, **{"index": index})
for action in item.actions
]
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if action["on"] == "notProcessed" and item.processed:
actions.remove(action)
# Discard empty categories, separators
remaining_actions = list()
index = 0
try:
action = actions[index]
except IndexError:
pass
else:
while action:
try:
action = actions[index]
except IndexError:
break
isempty = False
if action["__type__"] in ("category", "separator"):
try:
next_ = actions[index + 1]
if next_["__type__"] != "action":
isempty = True
except IndexError:
isempty = True
if not isempty:
remaining_actions.append(action)
index += 1
return remaining_actions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exclude(self, target, operation, role, value):
"""Exclude a `role` of `value` at `target` Arguments: target (str):
Destination proxy model operation (str):
"add" or "remove" exclusion role (str):
Role to exclude value (str):
Value of `role` to exclude """ |
target = {"result": self.data["proxies"]["result"],
"instance": self.data["proxies"]["instance"],
"plugin": self.data["proxies"]["plugin"]}[target]
if operation == "add":
target.add_exclusion(role, value)
elif operation == "remove":
target.remove_exclusion(role, value)
else:
raise TypeError("operation must be either `add` or `remove`") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __item_data(self, model, index):
"""Return item data as dict""" |
item = model.items[index]
data = {
"name": item.name,
"data": item.data,
"doc": getattr(item, "doc", None),
"path": getattr(item, "path", None),
}
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment_sync(self, comment):
"""Update comments to host and notify subscribers""" |
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_commenting(self, comment):
"""The user is entering a comment""" |
def update():
context = self.host.cached_context
context.data["comment"] = comment
self.data["comment"] = comment
# Notify subscribers of the comment
self.comment_sync(comment)
self.commented.emit()
# Update local cache a little later
util.schedule(update, 100, channel="commenting") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self):
"""Start asynchonous publishing Publishing takes into account all available and currently toggled plug-ins and instances. """ |
def get_data():
model = self.data["models"]["item"]
# Communicate with host to retrieve current plugins and instances
# This can potentially take a very long time; it is run
# asynchronously and initiates processing once complete.
host_plugins = dict((p.id, p) for p in self.host.cached_discover)
host_context = dict((i.id, i) for i in self.host.cached_context)
plugins = list()
instances = list()
for plugin in models.ItemIterator(model.plugins):
# Exclude Collectors
if pyblish.lib.inrange(
number=plugin.order,
base=pyblish.api.Collector.order):
continue
plugins.append(host_plugins[plugin.id])
for instance in models.ItemIterator(model.instances):
instances.append(host_context[instance.id])
return plugins, instances
def on_data_received(args):
self.run(*args, callback=on_finished)
def on_finished():
self.host.emit("published", context=None)
util.defer(get_data, callback=on_data_received) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(settings):
"""Apply settings from dictionary Arguments: settings (dict):
Settings in the form of a dictionary """ |
assert isinstance(settings, dict), "`settings` must be of type dict"
for key, value in settings.items():
setattr(self, key, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, **kwargs):
"""Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.""" |
if _is_list(spec):
# can't pass a list instance to the mock constructor as it will be
# interpreted as a list of strings
spec = type(spec)
is_type = isinstance(spec, ClassTypes)
_kwargs = {'spec': spec}
if spec_set:
_kwargs = {'spec_set': spec}
elif spec is None:
# None we mock with a normal mock without a spec
_kwargs = {}
_kwargs.update(kwargs)
Klass = MagicMock
if type(spec) in DescriptorTypes:
# descriptors don't have a spec
# because we don't know what type they return
_kwargs = {}
elif not _callable(spec):
Klass = NonCallableMagicMock
elif is_type and instance and not _instance_callable(spec):
Klass = NonCallableMagicMock
_new_name = _name
if _parent is None:
# for a top level object no _new_name should be set
_new_name = ''
mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
name=_name, **_kwargs)
if isinstance(spec, FunctionTypes):
# should only happen at the top level because we don't
# recurse for functions
mock = _set_signature(mock, spec)
else:
_check_signature(spec, mock, is_type, instance)
if _parent is not None and not instance:
_parent._mock_children[_name] = mock
if is_type and not instance and 'return_value' not in kwargs:
mock.return_value = create_autospec(spec, spec_set, instance=True,
_name='()', _parent=mock)
for entry in dir(spec):
if _is_magic(entry):
# MagicMock already does the useful magic methods for us
continue
if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
# allow a mock to actually be a function
continue
# XXXX do we need a better way of getting attributes without
# triggering code execution (?) Probably not - we need the actual
# object to mock it so we would rather trigger a property than mock
# the property descriptor. Likewise we want to mock out dynamically
# provided attributes.
# XXXX what about attributes that raise exceptions other than
# AttributeError on being fetched?
# we could be resilient against it, or catch and propagate the
# exception when the attribute is fetched from the mock
try:
original = getattr(spec, entry)
except AttributeError:
continue
kwargs = {'spec': original}
if spec_set:
kwargs = {'spec_set': original}
if not isinstance(original, FunctionTypes):
new = _SpecState(original, spec_set, mock, entry, instance)
mock._mock_children[entry] = new
else:
parent = mock
if isinstance(spec, FunctionTypes):
parent = mock.mock
new = MagicMock(parent=parent, name=entry, _new_name=entry,
_new_parent=parent, **kwargs)
mock._mock_children[entry] = new
skipfirst = _must_skip(spec, entry, is_type)
_check_signature(original, new, skipfirst=skipfirst)
# so functions created with _set_signature become instance attributes,
# *plus* their underlying mock exists in _mock_children of the parent
# mock. Adding to _mock_children may be unnecessary where we are also
# setting as an instance attribute?
if isinstance(new, FunctionTypes):
setattr(mock, entry, new)
return mock |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_mock(self, mock, attribute):
""" Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" |
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_mock(self, **kwargs):
"""Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: |
for arg, val in sorted(kwargs.items(),
# we sort on the number of dots so that
# attributes are set before we set attributes on
# attributes
key=lambda entry: entry[0].count('.')):
args = arg.split('.')
final = args.pop()
obj = self
for entry in args:
obj = getattr(obj, entry)
setattr(obj, final, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_child_mock(self, **kw):
"""Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).""" |
_type = type(self)
if not issubclass(_type, CallableMixin):
if issubclass(_type, NonCallableMagicMock):
klass = MagicMock
elif issubclass(_type, NonCallableMock) :
klass = Mock
else:
klass = _type.__mro__[1]
return klass(**kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" |
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_list(self):
"""For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.""" |
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_dispatch_wrapper(wrapper):
"""Register a dispatch wrapper for servers The wrapper must have this exact signature: (func, *args, **kwargs) """ |
signature = inspect.getargspec(wrapper)
if any([len(signature.args) != 1,
signature.varargs is None,
signature.keywords is None]):
raise TypeError("Wrapper signature mismatch")
def _wrapper(func, *args, **kwargs):
"""Exception handling"""
try:
return wrapper(func, *args, **kwargs)
except Exception as e:
# Kill subprocess
_state["currentServer"].stop()
traceback.print_exc()
raise e
_state["dispatchWrapper"] = _wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(modal):
"""Perform first time install""" |
if _state.get("installed"):
sys.stdout.write("Already installed, uninstalling..\n")
uninstall()
use_threaded_wrapper = not modal
install_callbacks()
install_host(use_threaded_wrapper)
_state["installed"] = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(parent=None, targets=[], modal=None, auto_publish=False, auto_validate=False):
"""Attempt to show GUI Requires install() to have been run first, and a live instance of Pyblish QML in the background. Arguments: parent (None, optional):
Deprecated targets (list, optional):
Publishing targets modal (bool, optional):
Block interactions to parent """ |
# Get modal mode from environment
if modal is None:
modal = bool(os.environ.get("PYBLISH_QML_MODAL", False))
# Automatically install if not already installed.
install(modal)
show_settings = settings.to_dict()
show_settings['autoPublish'] = auto_publish
show_settings['autoValidate'] = auto_validate
# Show existing GUI
if _state.get("currentServer"):
server = _state["currentServer"]
proxy = ipc.server.Proxy(server)
try:
proxy.show(show_settings)
return server
except IOError:
# The running instance has already been closed.
_state.pop("currentServer")
if not host.is_headless():
host.splash()
try:
service = ipc.service.Service()
server = ipc.server.Server(service, targets=targets, modal=modal)
except Exception:
# If for some reason, the GUI fails to show.
traceback.print_exc()
return host.desplash()
proxy = ipc.server.Proxy(server)
proxy.show(show_settings)
# Store reference to server for future calls
_state["currentServer"] = server
log.info("Success. QML server available as "
"pyblish_qml.api.current_server()")
server.listen()
return server |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_host(use_threaded_wrapper):
"""Install required components into supported hosts An unsupported host will still run, but may encounter issues, especially with threading. """ |
for install in (_install_maya,
_install_houdini,
_install_nuke,
_install_nukeassist,
_install_hiero,
_install_nukestudio,
_install_blender):
try:
install(use_threaded_wrapper)
except ImportError:
pass
else:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_googleapiclient():
"""Check if the compatibility must be maintained The Maya 2018 version tries to import the `http` module from Maya2018\plug-ins\MASH\scripts\googleapiclient\http.py in stead of the module from six.py. This import conflict causes a crash Avalon's publisher. This is due to Autodesk adding paths to the PYTHONPATH environment variable which contain modules instead of only packages. """ |
keyword = "googleapiclient"
# reconstruct python paths
python_paths = os.environ["PYTHONPATH"].split(os.pathsep)
paths = [path for path in python_paths if keyword not in path]
os.environ["PYTHONPATH"] = os.pathsep.join(paths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_maya(use_threaded_wrapper):
"""Helper function to Autodesk Maya support""" |
from maya import utils, cmds
def threaded_wrapper(func, *args, **kwargs):
return utils.executeInMainThreadWithResult(
func, *args, **kwargs)
sys.stdout.write("Setting up Pyblish QML in Maya\n")
if cmds.about(version=True) == "2018":
_remove_googleapiclient()
_common_setup("Maya", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_houdini(use_threaded_wrapper):
"""Helper function to SideFx Houdini support""" |
import hdefereval
def threaded_wrapper(func, *args, **kwargs):
return hdefereval.executeInMainThreadWithResult(
func, *args, **kwargs)
_common_setup("Houdini", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_nuke(use_threaded_wrapper):
"""Helper function to The Foundry Nuke support""" |
import nuke
not_nuke_launch = (
"--hiero" in nuke.rawArgs or
"--studio" in nuke.rawArgs or
"--nukeassist" in nuke.rawArgs
)
if not_nuke_launch:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Nuke", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_nukeassist(use_threaded_wrapper):
"""Helper function to The Foundry NukeAssist support""" |
import nuke
if "--nukeassist" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("NukeAssist", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_hiero(use_threaded_wrapper):
"""Helper function to The Foundry Hiero support""" |
import hiero
import nuke
if "--hiero" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return hiero.core.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Hiero", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _install_blender(use_threaded_wrapper):
"""Blender is a special snowflake It doesn't have a mechanism with which to call commands from a thread other than the main thread. So what's happening below is we run a polling command every 10 milliseconds to see whether QML has any tasks for us. If it does, then Blender runs this command (blocking while it does it), and passes the result back to QML when ready. The consequence of this is that we're polling even though nothing is expected to arrive. The cost of polling is expected to be neglible, but it's worth keeping in mind and ideally optimise away. E.g. only poll when the QML window is actually open. """ |
import bpy
qml_to_blender = queue.Queue()
blender_to_qml = queue.Queue()
def threaded_wrapper(func, *args, **kwargs):
qml_to_blender.put((func, args, kwargs))
return blender_to_qml.get()
class PyblishQMLOperator(bpy.types.Operator):
"""Operator which runs its self from a timer"""
bl_idname = "wm.pyblish_qml_timer"
bl_label = "Pyblish QML Timer Operator"
_timer = None
def modal(self, context, event):
if event.type == 'TIMER':
try:
func, args, kwargs = qml_to_blender.get_nowait()
except queue.Empty:
pass
else:
result = func(*args, **kwargs)
blender_to_qml.put(result)
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
# Check the queue ever 10 ms
# The cost of checking the queue is neglible, but it
# does mean having Python execute a command all the time,
# even as the artist is working normally and is nowhere
# near publishing anything.
self._timer = wm.event_timer_add(0.01, context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
log.info("Registering Blender + Pyblish operator")
bpy.utils.register_class(PyblishQMLOperator)
# Start the timer
bpy.ops.wm.pyblish_qml_timer()
# Expose externally, for debugging. It enables you to
# pause the timer, and add/remove commands by hand.
_state["QmlToBlenderQueue"] = qml_to_blender
_state["BlenderToQmlQueue"] = blender_to_qml
_common_setup("Blender", threaded_wrapper, use_threaded_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, host):
"""Setup common to all Qt-based hosts""" |
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
log.info("Headless host")
return
print("aboutToQuit..")
self.app.aboutToQuit.connect(self._on_application_quit)
if host == "Maya":
print("Maya host..")
window = {
widget.objectName(): widget
for widget in self.app.topLevelWidgets()
}["MayaWindow"]
else:
window = self.find_window()
# Install event filter
print("event filter..")
event_filter = self.EventFilter(window)
window.installEventFilter(event_filter)
for signal in SIGNALS_TO_REMOVE_EVENT_FILTER:
pyblish.api.register_callback(signal, self.uninstall)
log.info("Installed event filter")
self.window = window
self._state["installed"] = True
self._state["eventFilter"] = event_filter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_window(self):
"""Get top window in host""" |
window = self.app.activeWindow()
while True:
parent_window = window.parent()
if parent_window:
window = parent_window
else:
break
return window |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tab_should_insert_whitespace():
""" When the 'tab' key is pressed with only whitespace character before the cursor, do autocompletion. Otherwise, insert indentation. Except for the first character at the first line. Then always do a completion. It doesn't make sense to start the first line with indentation. """ |
b = get_app().current_buffer
before_cursor = b.document.current_line_before_cursor
return bool(b.text and (not before_cursor or before_cursor.isspace())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_sidebar_bindings(python_input):
""" Load bindings for the navigation in the sidebar. """ |
bindings = KeyBindings()
handle = bindings.add
sidebar_visible = Condition(lambda: python_input.show_sidebar)
@handle('up', filter=sidebar_visible)
@handle('c-p', filter=sidebar_visible)
@handle('k', filter=sidebar_visible)
def _(event):
" Go to previous option. "
python_input.selected_option_index = (
(python_input.selected_option_index - 1) % python_input.option_count)
@handle('down', filter=sidebar_visible)
@handle('c-n', filter=sidebar_visible)
@handle('j', filter=sidebar_visible)
def _(event):
" Go to next option. "
python_input.selected_option_index = (
(python_input.selected_option_index + 1) % python_input.option_count)
@handle('right', filter=sidebar_visible)
@handle('l', filter=sidebar_visible)
@handle(' ', filter=sidebar_visible)
def _(event):
" Select next value for current option. "
option = python_input.selected_option
option.activate_next()
@handle('left', filter=sidebar_visible)
@handle('h', filter=sidebar_visible)
def _(event):
" Select previous value for current option. "
option = python_input.selected_option
option.activate_previous()
@handle('c-c', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('enter', filter=sidebar_visible)
@handle('escape', filter=sidebar_visible)
def _(event):
" Hide sidebar. "
python_input.show_sidebar = False
event.app.layout.focus_last()
return bindings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_newline(buffer):
r""" Insert \n at the cursor position. Also add necessary padding. """ |
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
# When we are in the middle of a line. Always insert a newline.
insert_text('\n')
else:
# Go to new line, but also add indentation.
current_line = buffer.document.current_line_before_cursor.rstrip()
insert_text('\n')
# Unident if the last line ends with 'pass', remove four spaces.
unindent = current_line.rstrip().endswith(' pass')
# Copy whitespace from current line
current_line2 = current_line[4:] if unindent else current_line
for c in current_line2:
if c.isspace():
insert_text(c)
else:
break
# If the last line ends with a colon, add four extra spaces.
if current_line[-1:] == ':':
for x in range(4):
insert_text(' ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _path_completer_grammar(self):
""" Return the grammar for matching paths inside strings inside Python code. """ |
# We make this lazy, because it delays startup time a little bit.
# This way, the grammar is build during the first completion.
if self._path_completer_grammar_cache is None:
self._path_completer_grammar_cache = self._create_path_completer_grammar()
return self._path_completer_grammar_cache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_completions(self, document, complete_event):
""" Get Python completions. """ |
# Do Path completions
if complete_event.completion_requested or self._complete_path_while_typing(document):
for c in self._path_completer.get_completions(document, complete_event):
yield c
# If we are inside a string, Don't do Jedi completion.
if self._path_completer_grammar.match(document.text_before_cursor):
return
# Do Jedi Python completions.
if complete_event.completion_requested or self._complete_python_while_typing(document):
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
if script:
try:
completions = script.completions()
except TypeError:
# Issue #9: bad syntax causes completions() to fail in jedi.
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/9
pass
except UnicodeDecodeError:
# Issue #43: UnicodeDecodeError on OpenBSD
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/43
pass
except AttributeError:
# Jedi issue #513: https://github.com/davidhalter/jedi/issues/513
pass
except ValueError:
# Jedi issue: "ValueError: invalid \x escape"
pass
except KeyError:
# Jedi issue: "KeyError: u'a_lambda'."
# https://github.com/jonathanslenders/ptpython/issues/89
pass
except IOError:
# Jedi issue: "IOError: No such file or directory."
# https://github.com/jonathanslenders/ptpython/issues/71
pass
except AssertionError:
# In jedi.parser.__init__.py: 227, in remove_last_newline,
# the assertion "newline.value.endswith('\n')" can fail.
pass
except SystemError:
# In jedi.api.helpers.py: 144, in get_stack_at_position
# raise SystemError("This really shouldn't happen. There's a bug in Jedi.")
pass
except NotImplementedError:
# See: https://github.com/jonathanslenders/ptpython/issues/223
pass
except Exception:
# Supress all other Jedi exceptions.
pass
else:
for c in completions:
yield Completion(c.name_with_symbols, len(c.complete) - len(c.name_with_symbols),
display=c.name_with_symbols) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inputhook_tk(inputhook_context):
""" Inputhook for Tk. Run the Tk eventloop until prompt-toolkit needs to process the next input. """ |
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wait_using_filehandler():
"""
Run the TK eventloop until the file handler that we got from the
inputhook becomes readable.
"""
# Add a handler that sets the stop flag when `prompt-toolkit` has input
# to process.
stop = [False]
def done(*a):
stop[0] = True
root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
# Run the TK event loop as long as we don't receive input.
while root.dooneevent(_tkinter.ALL_EVENTS):
if stop[0]:
break
root.deletefilehandler(inputhook_context.fileno())
def wait_using_polling():
"""
Windows TK doesn't support 'createfilehandler'.
So, run the TK eventloop and poll until input is ready.
"""
while not inputhook_context.input_is_ready():
while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
pass
# Sleep to make the CPU idle, but not too long, so that the UI
# stays responsive.
time.sleep(.01)
if root is not None:
if hasattr(root, 'createfilehandler'):
wait_using_filehandler()
else:
wait_using_polling() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_config(repl, config_file='~/.ptpython/config.py'):
""" Execute REPL config file. :param repl: `PythonInput` instance. :param config_file: Path of the configuration file. """ |
assert isinstance(repl, PythonInput)
assert isinstance(config_file, six.text_type)
# Expand tildes.
config_file = os.path.expanduser(config_file)
def enter_to_continue():
six.moves.input('\nPress ENTER to continue...')
# Check whether this file exists.
if not os.path.exists(config_file):
print('Impossible to read %r' % config_file)
enter_to_continue()
return
# Run the config file in an empty namespace.
try:
namespace = {}
with open(config_file, 'rb') as f:
code = compile(f.read(), config_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with the repl as an argument.
if 'configure' in namespace:
namespace['configure'](repl)
except Exception:
traceback.print_exc()
enter_to_continue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _load_start_paths(self):
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, 'rb') as f:
code = compile(f.read(), path, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
else:
output = self.app.output
output.write('WARNING | File not found: {}\n\n'.format(path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _execute(self, line):
""" Evaluate the line and print the result. """ |
output = self.app.output
# WORKAROUND: Due to a bug in Jedi, the current directory is removed
# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
if '' not in sys.path:
sys.path.insert(0, '')
def compile_with_flags(code, mode):
" Compile code with the right compiler flags. "
return compile(code, '<stdin>', mode,
flags=self.get_compiler_flags(),
dont_inherit=True)
if line.lstrip().startswith('\x1a'):
# When the input starts with Ctrl-Z, quit the REPL.
self.app.exit()
elif line.lstrip().startswith('!'):
# Run as shell command
os.system(line[1:])
else:
# Try eval first
try:
code = compile_with_flags(line, 'eval')
result = eval(code, self.get_globals(), self.get_locals())
locals = self.get_locals()
locals['_'] = locals['_%i' % self.current_statement_index] = result
if result is not None:
out_prompt = self.get_output_prompt()
try:
result_str = '%r\n' % (result, )
except UnicodeDecodeError:
# In Python 2: `__repr__` should return a bytestring,
# so to put it in a unicode context could raise an
# exception that the 'ascii' codec can't decode certain
# characters. Decode as utf-8 in that case.
result_str = '%s\n' % repr(result).decode('utf-8')
# Align every line to the first one.
line_sep = '\n' + ' ' * fragment_list_width(out_prompt)
result_str = line_sep.join(result_str.splitlines()) + '\n'
# Write output tokens.
if self.enable_syntax_highlighting:
formatted_output = merge_formatted_text([
out_prompt,
PygmentsTokens(list(_lex_python_result(result_str))),
])
else:
formatted_output = FormattedText(
out_prompt + [('', result_str)])
print_formatted_text(
formatted_output, style=self._current_style,
style_transformation=self.style_transformation,
include_default_pygments_style=False)
# If not a valid `eval` expression, run using `exec` instead.
except SyntaxError:
code = compile_with_flags(line, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
output.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interactive_shell():
""" Coroutine that starts a Python REPL from which we can access the global counter variable. """ |
print('You should be able to read and update the "counter[0]" variable from this shell.')
try:
yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)
except EOFError:
# Stop the loop when quitting the repl. (Ctrl-D press.)
loop.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, document):
""" Check input for Python syntax errors. """ |
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python REPL.
if document.text.startswith('\x1a'):
return
try:
if self.get_compiler_flags:
flags = self.get_compiler_flags()
else:
flags = 0
compile(document.text, '<input>', 'exec', flags=flags, dont_inherit=True)
except SyntaxError as e:
# Note, the 'or 1' for offset is required because Python 2.7
# gives `None` as offset in case of '4=4' as input. (Looks like
# fixed in Python 3.)
index = document.translate_row_col_to_index(e.lineno - 1, (e.offset or 1) - 1)
raise ValidationError(index, 'Syntax Error')
except TypeError as e:
# e.g. "compile() expected string without null bytes"
raise ValidationError(0, str(e))
except ValueError as e:
# In Python 2, compiling "\x9" (an invalid escape sequence) raises
# ValueError instead of SyntaxError.
raise ValidationError(0, 'Syntax Error: %s' % e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(port=8222):
""" Example that starts the REPL through an SSH server. """ |
loop = asyncio.get_event_loop()
# Namespace exposed in the REPL.
environ = {'hello': 'world'}
# Start SSH server.
def create_server():
return MySSHServer(lambda: environ)
print('Listening on :%i' % port)
print('To connect, do "ssh localhost -p %i"' % port)
loop.run_until_complete(
asyncssh.create_server(create_server, '', port,
server_host_keys=['/etc/ssh/ssh_host_dsa_key']))
# Run eventloop.
loop.run_forever() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_size(self):
""" Callable that returns the current `Size`, required by Vt100_Output. """ |
if self._chan is None:
return Size(rows=20, columns=79)
else:
width, height, pixwidth, pixheight = self._chan.get_terminal_size()
return Size(rows=height, columns=width) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connection_made(self, chan):
""" Client connected, run repl in coroutine. """ |
self._chan = chan
# Run REPL interface.
f = asyncio.ensure_future(self.cli.run_async())
# Close channel when done.
def done(_):
chan.close()
self._chan = None
f.add_done_callback(done) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(repl):
""" Configuration method. This is called during the start-up of ptpython. :param repl: `PythonRepl` instance. """ |
# Show function signature (bool).
repl.show_signature = True
# Show docstring (bool).
repl.show_docstring = False
# Show the "[Meta+Enter] Execute" message when pressing [Enter] only
# inserts a newline instead of executing the code.
repl.show_meta_enter_message = True
# Show completions. (NONE, POP_UP, MULTI_COLUMN or TOOLBAR)
repl.completion_visualisation = CompletionVisualisation.POP_UP
# When CompletionVisualisation.POP_UP has been chosen, use this
# scroll_offset in the completion menu.
repl.completion_menu_scroll_offset = 0
# Show line numbers (when the input contains multiple lines.)
repl.show_line_numbers = False
# Show status bar.
repl.show_status_bar = True
# When the sidebar is visible, also show the help text.
repl.show_sidebar_help = True
# Highlight matching parethesis.
repl.highlight_matching_parenthesis = True
# Line wrapping. (Instead of horizontal scrolling.)
repl.wrap_lines = True
# Mouse support.
repl.enable_mouse_support = True
# Complete while typing. (Don't require tab before the
# completion menu is shown.)
repl.complete_while_typing = True
# Vi mode.
repl.vi_mode = False
# Paste mode. (When True, don't insert whitespace after new line.)
repl.paste_mode = False
# Use the classic prompt. (Display '>>>' instead of 'In [1]'.)
repl.prompt_style = 'classic' # 'classic' or 'ipython'
# Don't insert a blank line after the output.
repl.insert_blank_line_after_output = False
# History Search.
# When True, going back in history will filter the history on the records
# starting with the current input. (Like readline.)
# Note: When enable, please disable the `complete_while_typing` option.
# otherwise, when there is a completion available, the arrows will
# browse through the available completions instead of the history.
repl.enable_history_search = False
# Enable auto suggestions. (Pressing right arrow will complete the input,
# based on the history.)
repl.enable_auto_suggest = False
# Enable open-in-editor. Pressing C-X C-E in emacs mode or 'v' in
# Vi navigation mode will open the input in the current editor.
repl.enable_open_in_editor = True
# Enable system prompt. Pressing meta-! will display the system prompt.
# Also enables Control-Z suspend.
repl.enable_system_bindings = True
# Ask for confirmation on exit.
repl.confirm_exit = True
# Enable input validation. (Don't try to execute when the input contains
# syntax errors.)
repl.enable_input_validation = True
# Use this colorscheme for the code.
repl.use_code_colorscheme('pastie')
# Set color depth (keep in mind that not all terminals support true color).
#repl.color_depth = 'DEPTH_1_BIT' # Monochrome.
#repl.color_depth = 'DEPTH_4_BIT' # ANSI colors only.
repl.color_depth = 'DEPTH_8_BIT' # The default, 256 colors.
#repl.color_depth = 'DEPTH_24_BIT' # True color.
# Syntax.
repl.enable_syntax_highlighting = True
# Install custom colorscheme named 'my-colorscheme' and use it.
"""
repl.install_ui_colorscheme('my-colorscheme', _custom_ui_colorscheme)
repl.use_ui_colorscheme('my-colorscheme')
"""
# Add custom key binding for PDB.
"""
@repl.add_key_binding(Keys.ControlB)
def _(event):
' Pressing Control-B will insert "pdb.set_trace()" '
event.cli.current_buffer.insert_text('\nimport pdb; pdb.set_trace()\n')
"""
# Typing ControlE twice should also execute the current command.
# (Alternative for Meta-Enter.)
"""
@repl.add_key_binding(Keys.ControlE, Keys.ControlE)
def _(event):
event.current_buffer.validate_and_handle()
"""
# Typing 'jj' in Vi Insert mode, should send escape. (Go back to navigation
# mode.)
"""
@repl.add_key_binding('j', 'j', filter=ViInsertMode())
def _(event):
" Map 'jj' to Escape. "
event.cli.key_processor.feed(KeyPress(Keys.Escape))
"""
# Custom key binding for some simple autocorrection while typing.
"""
corrections = {
'impotr': 'import',
'pritn': 'print',
}
@repl.add_key_binding(' ')
def _(event):
' When a space is pressed. Check & correct word before cursor. '
b = event.cli.current_buffer
w = b.document.get_word_before_cursor()
if w is not None:
if w in corrections:
b.delete_before_cursor(count=len(w))
b.insert_text(corrections[w])
b.insert_text(' ')
""" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_unclosed_brackets(text):
""" Starting at the end of the string. If we find an opening bracket for which we didn't had a closing one yet, return True. """ |
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document_is_multiline_python(document):
""" Determine whether this is a multiline Python document. """ |
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def if_mousedown(handler):
""" Decorator for mouse handlers. Only handle event when the user pressed mouse down. (When applied to a token list. Scroll events will bubble up and are handled by the Window.) """ |
def handle_if_mouse_down(mouse_event):
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
return handler(mouse_event)
else:
return NotImplemented
return handle_if_mouse_down |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_popup_window(title, body):
""" Return the layout for a pop-up window. It consists of a title bar showing the `title` text, and a body layout. The window is surrounded by borders. """ |
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return Frame(body=body, title=title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_new_document(self, cursor_pos=None):
""" Create a `Document` instance that contains the resulting text. """ |
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with history buffer. """ |
# Only when this buffer has the focus.
if self.app.current_buffer == self.default_buffer:
try:
line_no = self.default_buffer.document.cursor_position_row - \
self.history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(self.history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
self.history_buffer.cursor_position = \
self.history_buffer.document.translate_row_col_to_index(history_lineno, 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _history_buffer_pos_changed(self, _):
""" When the cursor changes in the history buffer. Synchronize. """ |
# Only when this buffer has the focus.
if self.app.current_buffer == self.history_buffer:
line_no = self.history_buffer.document.cursor_position_row
if line_no in self.history_mapping.selected_lines:
default_lineno = sorted(self.history_mapping.selected_lines).index(line_no) + \
self.history_mapping.result_line_offset
self.default_buffer.cursor_position = \
self.default_buffer.document.translate_row_col_to_index(default_lineno, 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python_sidebar(python_input):
""" Create the `Layout` for the sidebar with the configurable options. """ |
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.title', ' %-36s' % category.title),
('class:sidebar', '\n'),
])
def append(index, label, status):
selected = index == python_input.selected_option_index
@if_mousedown
def select_item(mouse_event):
python_input.selected_option_index = index
@if_mousedown
def goto_next(mouse_event):
" Select item and go to next value. "
python_input.selected_option_index = index
option = python_input.selected_option
option.activate_next()
sel = ',selected' if selected else ''
tokens.append(('class:sidebar' + sel, ' >' if selected else ' '))
tokens.append(('class:sidebar.label' + sel, '%-24s' % label, select_item))
tokens.append(('class:sidebar.status' + sel, ' ', select_item))
tokens.append(('class:sidebar.status' + sel, '%s' % status, goto_next))
if selected:
tokens.append(('[SetCursorPosition]', ''))
tokens.append(('class:sidebar.status' + sel, ' ' * (13 - len(status)), goto_next))
tokens.append(('class:sidebar', '<' if selected else ''))
tokens.append(('class:sidebar', '\n'))
i = 0
for category in python_input.options:
append_category(category)
for option in category.options:
append(i, option.title, '%s' % option.get_current_value())
i += 1
tokens.pop() # Remove last newline.
return tokens
class Control(FormattedTextControl):
def move_cursor_down(self):
python_input.selected_option_index += 1
def move_cursor_up(self):
python_input.selected_option_index -= 1
return Window(
Control(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension(min=3),
scroll_offsets=ScrollOffsets(top=1, bottom=1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python_sidebar_navigation(python_input):
""" Create the `Layout` showing the navigation information for the sidebar. """ |
def get_text_fragments():
tokens = []
# Show navigation info.
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.key', '[Arrows]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Navigate'),
('class:sidebar', ' '),
('class:sidebar.key', '[Enter]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Hide menu'),
])
return tokens
return Window(
FormattedTextControl(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension.exact(1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python_sidebar_help(python_input):
""" Create the `Layout` for the help text for the current item in the sidebar. """ |
token = 'class:sidebar.helptext'
def get_current_description():
"""
Return the description of the selected option.
"""
i = 0
for category in python_input.options:
for option in category.options:
if i == python_input.selected_option_index:
return option.description
i += 1
return ''
def get_help_text():
return [(token, get_current_description())]
return ConditionalContainer(
content=Window(
FormattedTextControl(get_help_text),
style=token,
height=Dimension(min=3)),
filter=ShowSidebar(python_input) &
Condition(lambda: python_input.show_sidebar_help) & ~is_done) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature_toolbar(python_input):
""" Return the `Layout` for the signature. """ |
def get_text_fragments():
result = []
append = result.append
Signature = 'class:signature-toolbar'
if python_input.signatures:
sig = python_input.signatures[0] # Always take the first one.
append((Signature, ' '))
try:
append((Signature, sig.full_name))
except IndexError:
# Workaround for #37: https://github.com/jonathanslenders/python-prompt-toolkit/issues/37
# See also: https://github.com/davidhalter/jedi/issues/490
return []
append((Signature + ',operator', '('))
try:
enumerated_params = enumerate(sig.params)
except AttributeError:
# Workaround for #136: https://github.com/jonathanslenders/ptpython/issues/136
# AttributeError: 'Lambda' object has no attribute 'get_subscope_by_name'
return []
for i, p in enumerated_params:
# Workaround for #47: 'p' is None when we hit the '*' in the signature.
# and sig has no 'index' attribute.
# See: https://github.com/jonathanslenders/ptpython/issues/47
# https://github.com/davidhalter/jedi/issues/598
description = (p.description if p else '*') #or '*'
sig_index = getattr(sig, 'index', 0)
if i == sig_index:
# Note: we use `_Param.description` instead of
# `_Param.name`, that way we also get the '*' before args.
append((Signature + ',current-name', str(description)))
else:
append((Signature, str(description)))
append((Signature + ',operator', ', '))
if sig.params:
# Pop last comma
result.pop()
append((Signature + ',operator', ')'))
append((Signature, ' '))
return result
return ConditionalContainer(
content=Window(
FormattedTextControl(get_text_fragments),
height=Dimension.exact(1)),
filter=
# Show only when there is a signature
HasSignature(python_input) &
# And there are no completions to be shown. (would cover signature pop-up.)
~(has_completions & (show_completions_menu(python_input) |
show_multi_column_completions_menu(python_input)))
# Signature needs to be shown.
& ShowSignature(python_input) &
# Not done yet.
~is_done) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status_bar(python_input):
""" Create the `Layout` for the status bar. """ |
TB = 'class:status-toolbar'
@if_mousedown
def toggle_paste_mode(mouse_event):
python_input.paste_mode = not python_input.paste_mode
@if_mousedown
def enter_history(mouse_event):
python_input.enter_history()
def get_text_fragments():
python_buffer = python_input.default_buffer
result = []
append = result.append
append((TB, ' '))
result.extend(get_inputmode_fragments(python_input))
append((TB, ' '))
# Position in history.
append((TB, '%i/%i ' % (python_buffer.working_index + 1,
len(python_buffer._working_lines))))
# Shortcuts.
app = get_app()
if not python_input.vi_mode and app.current_buffer == python_input.search_buffer:
append((TB, '[Ctrl-G] Cancel search [Enter] Go to this position.'))
elif bool(app.current_buffer.selection_state) and not python_input.vi_mode:
# Emacs cut/copy keys.
append((TB, '[Ctrl-W] Cut [Meta-W] Copy [Ctrl-Y] Paste [Ctrl-G] Cancel'))
else:
result.extend([
(TB + ' class:key', '[F3]', enter_history),
(TB, ' History ', enter_history),
(TB + ' class:key', '[F6]', toggle_paste_mode),
(TB, ' ', toggle_paste_mode),
])
if python_input.paste_mode:
append((TB + ' class:paste-mode-on', 'Paste mode (on)', toggle_paste_mode))
else:
append((TB, 'Paste mode', toggle_paste_mode))
return result
return ConditionalContainer(
content=Window(content=FormattedTextControl(get_text_fragments), style=TB),
filter=~is_done & renderer_height_is_known &
Condition(lambda: python_input.show_status_bar and
not python_input.show_exit_confirmation)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exit_confirmation(python_input, style='class:exit-confirmation'):
""" Create `Layout` for the exit message. """ |
def get_text_fragments():
# Show "Do you really want to exit?"
return [
(style, '\n %s ([y]/n)' % python_input.exit_message),
('[SetCursorPosition]', ''),
(style, ' \n'),
]
visible = ~is_done & Condition(lambda: python_input.show_exit_confirmation)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments), style=style), # , has_focus=visible)),
filter=visible) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meta_enter_message(python_input):
""" Create the `Layout` for the 'Meta+Enter` message. """ |
def get_text_fragments():
return [('class:accept-message', ' [Meta+Enter] Execute ')]
def extra_condition():
" Only show when... "
b = python_input.default_buffer
return (
python_input.show_meta_enter_message and
(not b.document.is_cursor_at_the_end or
python_input.accept_input_on_enter is None) and
'\n' in b.text)
visible = ~is_done & has_focus(DEFAULT_BUFFER) & Condition(extra_condition)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments)),
filter=visible) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate_next(self, _previous=False):
""" Activate next value. """ |
current = self.get_current_value()
options = sorted(self.values.keys())
# Get current index.
try:
index = options.index(current)
except ValueError:
index = 0
# Go to previous/next index.
if _previous:
index -= 1
else:
index += 1
# Call handler for this option.
next_option = options[index % len(options)]
self.values[next_option]() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def selected_option(self):
" Return the currently selected option. "
i = 0
for category in self.options:
for o in category.options:
if i == self.selected_option_index:
return o
else:
i += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_compiler_flags(self):
""" Give the current compiler flags by looking for _Feature instances in the globals. """ |
flags = 0
for value in self.get_globals().values():
if isinstance(value, __future__._Feature):
flags |= value.compiler_flag
return flags |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_code_colorscheme(self, name, style_dict):
""" Install a new code color scheme. """ |
assert isinstance(name, six.text_type)
assert isinstance(style_dict, dict)
self.code_styles[name] = style_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_ui_colorscheme(self, name, style_dict):
""" Install a new UI color scheme. """ |
assert isinstance(name, six.text_type)
assert isinstance(style_dict, dict)
self.ui_styles[name] = style_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_application(self):
""" Create an `Application` instance. """ |
return Application(
input=self.input,
output=self.output,
layout=self.ptpython_layout.layout,
key_bindings=merge_key_bindings([
load_python_bindings(self),
load_auto_suggest_bindings(),
load_sidebar_bindings(self),
load_confirm_exit_bindings(self),
ConditionalKeyBindings(
load_open_in_editor_bindings(),
Condition(lambda: self.enable_open_in_editor)),
# Extra key bindings should not be active when the sidebar is visible.
ConditionalKeyBindings(
self.extra_key_bindings,
Condition(lambda: not self.show_sidebar))
]),
color_depth=lambda: self.color_depth,
paste_mode=Condition(lambda: self.paste_mode),
mouse_support=Condition(lambda: self.enable_mouse_support),
style=DynamicStyle(lambda: self._current_style),
style_transformation=self.style_transformation,
include_default_pygments_style=False,
reverse_vi_search_direction=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_buffer(self):
""" Create the `Buffer` for the Python input. """ |
python_buffer = Buffer(
name=DEFAULT_BUFFER,
complete_while_typing=Condition(lambda: self.complete_while_typing),
enable_history_search=Condition(lambda: self.enable_history_search),
tempfile_suffix='.py',
history=self.history,
completer=ThreadedCompleter(self._completer),
validator=ConditionalValidator(
self._validator,
Condition(lambda: self.enable_input_validation)),
auto_suggest=ConditionalAutoSuggest(
ThreadedAutoSuggest(AutoSuggestFromHistory()),
Condition(lambda: self.enable_auto_suggest)),
accept_handler=self._accept_handler,
on_text_changed=self._on_input_timeout)
return python_buffer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _on_input_timeout(self, buff):
""" When there is no input activity, in another thread, get the signature of the current code. """ |
assert isinstance(buff, Buffer)
app = self.app
# Never run multiple get-signature threads.
if self._get_signatures_thread_running:
return
self._get_signatures_thread_running = True
document = buff.document
def run():
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
# Show signatures in help text.
if script:
try:
signatures = script.call_signatures()
except ValueError:
# e.g. in case of an invalid \\x escape.
signatures = []
except Exception:
# Sometimes we still get an exception (TypeError), because
# of probably bugs in jedi. We can silence them.
# See: https://github.com/davidhalter/jedi/issues/492
signatures = []
else:
# Try to access the params attribute just once. For Jedi
# signatures containing the keyword-only argument star,
# this will crash when retrieving it the first time with
# AttributeError. Every following time it works.
# See: https://github.com/jonathanslenders/ptpython/issues/47
# https://github.com/davidhalter/jedi/issues/598
try:
if signatures:
signatures[0].params
except AttributeError:
pass
else:
signatures = []
self._get_signatures_thread_running = False
# Set signatures and redraw if the text didn't change in the
# meantime. Otherwise request new signatures.
if buff.text == document.text:
self.signatures = signatures
# Set docstring in docstring buffer.
if signatures:
string = signatures[0].docstring()
if not isinstance(string, six.text_type):
string = string.decode('utf-8')
self.docstring_buffer.reset(
document=Document(string, cursor_position=0))
else:
self.docstring_buffer.reset()
app.invalidate()
else:
self._on_input_timeout(buff)
get_event_loop().run_in_executor(run) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_history(self):
""" Display the history. """ |
app = get_app()
app.vi_state.input_mode = InputMode.NAVIGATION
def done(f):
result = f.result()
if result is not None:
self.default_buffer.text = result
app.vi_state.input_mode = InputMode.INSERT
history = History(self, self.default_buffer.document)
future = run_coroutine_in_terminal(history.app.run_async)
future.add_done_callback(done) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_code_styles():
""" Return a mapping from style names to their classes. """ |
result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles())
result['win32'] = Style.from_dict(win32_code_style)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_extensions(shell, extensions):
""" Partial copy of `InteractiveShellApp.init_extensions` from IPython. """ |
try:
iter(extensions)
except TypeError:
pass # no extensions found
else:
for ext in extensions:
try:
shell.extension_manager.load_extension(ext)
except:
ipy_utils.warn.warn(
"Error in loading extension: %s" % ext +
"\nCheck your config files in %s" % ipy_utils.path.get_ipython_dir())
shell.showtraceback() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paths_for_download(self):
"""List of URLs available for downloading.""" |
if self._paths_for_download is None:
queries = list()
try:
for sra in self.gsm.relations['SRA']:
query = sra.split("=")[-1]
if 'SRX' not in query:
raise ValueError(
"Sample looks like it is not an SRA: %s" % query)
logger.info("Query: %s" % query)
queries.append(query)
except KeyError:
raise NoSRARelationException(
'No relation called SRA for %s' % self.gsm.get_accession())
# Construction of DataFrame df with paths to download
df = DataFrame(columns=['download_path'])
for query in queries:
# retrieve IDs for given SRX
searchdata = Entrez.esearch(db='sra', term=query, usehistory='y',
retmode='json')
answer = json.loads(searchdata.read())
ids = answer["esearchresult"]["idlist"]
if len(ids) != 1:
raise ValueError(
"There should be one and only one ID per SRX")
# using ID fetch the info
number_of_trials = 10
wait_time = 30
for trial in range(number_of_trials):
try:
results = Entrez.efetch(db="sra", id=ids[0],
rettype="runinfo",
retmode="text").read()
break
except HTTPError as httperr:
if "502" in str(httperr):
logger.warn(("%s, trial %i out of %i, waiting "
"for %i seconds.") % (
str(httperr),
trial,
number_of_trials,
wait_time))
time.sleep(wait_time)
elif httperr.code == 429:
# This means that there is too many requests
try:
header_wait_time = int(
httperr.headers["Retry-After"])
except:
header_wait_time = wait_time
logger.warn(("%s, trial %i out of %i, waiting "
"for %i seconds.") % (
str(httperr),
trial,
number_of_trials,
header_wait_time))
time.sleep(header_wait_time)
else:
raise httperr
try:
df_tmp = DataFrame([i.split(',') for i in results.split('\n') if i != ''][1:],
columns=[i.split(',') for i in results.split('\n') if i != ''][0])
except IndexError:
logger.error(("SRA is empty (ID: %s, query: %s). "
"Check if it is publicly available.") %
(ids[0], query))
continue
# check it first
try:
df_tmp['download_path']
except KeyError as e:
logger.error('KeyError: ' + str(e) + '\n')
logger.error(str(results) + '\n')
df = concat([df, df_tmp], sort=True)
self._paths_for_download = [path for path in df['download_path']]
return self._paths_for_download |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self):
"""Download SRA files. Returns: :obj:`list` of :obj:`str`: List of downloaded files. """ |
self.downloaded_paths = list()
for path in self.paths_for_download:
downloaded_path = list()
utils.mkdir_p(os.path.abspath(self.directory))
sra_run = path.split("/")[-1]
logger.info("Analysing %s" % sra_run)
url = type(self).FTP_ADDRESS_TPL.format(
range_subdir=sra_run[:6],
file_dir=sra_run)
logger.debug("URL: %s", url)
filepath = os.path.abspath(
os.path.join(self.directory, "%s.sra" % sra_run))
utils.download_from_url(
url,
filepath,
aspera=self.aspera,
silent=self.silent,
force=self.force)
if self.filetype in ("fasta", "fastq"):
if utils.which('fastq-dump') is None:
logger.error("fastq-dump command not found")
ftype = ""
if self.filetype == "fasta":
ftype = " --fasta "
cmd = "fastq-dump"
if utils.which('parallel-fastq-dump') is None:
cmd += " %s --outdir %s %s"
else:
logger.debug("Using parallel fastq-dump")
cmd = " parallel-fastq-dump --threads %s"
cmd = cmd % self.threads
cmd += " %s --outdir %s -s %s"
cmd = cmd % (ftype, self.directory, filepath)
for fqoption, fqvalue in iteritems(self.fastq_dump_options):
if fqvalue:
cmd += (" --%s %s" % (fqoption, fqvalue))
elif fqvalue is None:
cmd += (" --%s" % fqoption)
logger.debug(cmd)
process = sp.Popen(cmd, stdout=sp.PIPE,
stderr=sp.PIPE,
shell=True)
logger.info("Converting to %s/%s*.%s.gz\n" % (
self.directory, sra_run, self.filetype))
pout, perr = process.communicate()
downloaded_path = glob.glob(os.path.join(
self.directory,
"%s*.%s.gz" % (sra_run, self.filetype)))
elif self.filetype == 'sra':
downloaded_path = glob.glob(os.path.join(
self.directory,
"%s*.%s" % (sra_run, self.filetype)))
else:
downloaded_path = glob.glob(os.path.join(
self.directory,
"%s*" % sra_run))
logger.error("Filetype %s not supported." % self.filetype)
if not self.keep_sra and self.filetype != 'sra':
# Delete sra file
os.unlink(filepath)
self.downloaded_paths += downloaded_path
return self.downloaded_paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_log_file(path):
"""Add log file. Args: path (:obj:`str`):
Path to the log file. """ |
logfile_handler = RotatingFileHandler(
path, maxBytes=50000, backupCount=2)
formatter = logging.Formatter(
fmt='%(asctime)s %(levelname)s %(module)s - %(message)s',
datefmt="%d-%b-%Y %H:%M:%S")
logfile_handler.setFormatter(formatter)
geoparse_logger.addHandler(logfile_handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sra_download_worker(*args):
"""A worker to download SRA files. To be used with multiprocessing. """ |
gsm = args[0][0]
email = args[0][1]
dirpath = args[0][2]
kwargs = args[0][3]
return (gsm.get_accession(), gsm.download_SRA(email, dirpath, **kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _supplementary_files_download_worker(*args):
"""A worker to download supplementary files. To be used with multiprocessing. """ |
gsm = args[0][0]
download_sra = args[0][1]
email = args[0][2]
dirpath = args[0][3]
sra_kwargs = args[0][4]
return (gsm.get_accession(), gsm.download_supplementary_files(
directory=dirpath,
download_sra=download_sra,
email=email, **sra_kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_metadata_attribute(self, metaname):
"""Get the metadata attribute by the name. Args: metaname (:obj:`str`):
Name of the attribute Returns: :obj:`list` or :obj:`str`: Value(s) of the requested metadata attribute Raises: NoMetadataException: Attribute error TypeError: Metadata should be a list """ |
metadata_value = self.metadata.get(metaname, None)
if metadata_value is None:
raise NoMetadataException(
"No metadata attribute named %s" % metaname)
if not isinstance(metadata_value, list):
raise TypeError("Metadata is not a list and it should be.")
if len(metadata_value) > 1:
return metadata_value
else:
return metadata_value[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_metadata_as_string(self):
"""Get the metadata as SOFT formatted string.""" |
metalist = []
for metaname, meta in iteritems(self.metadata):
message = "Single value in metadata dictionary should be a list!"
assert isinstance(meta, list), message
for data in meta:
if data:
metalist.append("!%s_%s = %s" % (self.geotype.capitalize(),
metaname, data))
return "\n".join(metalist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_soft(self, path_or_handle, as_gzip=False):
"""Save the object in a SOFT format. Args: path_or_handle (:obj:`str` or :obj:`file`):
Path or handle to output file as_gzip (:obj:`bool`):
Save as gzip """ |
if isinstance(path_or_handle, str):
if as_gzip:
with gzip.open(path_or_handle, 'wt') as outfile:
outfile.write(self._get_object_as_soft())
else:
with open(path_or_handle, 'w') as outfile:
outfile.write(self._get_object_as_soft())
else:
path_or_handle.write(self._get_object_as_soft()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(self):
"""Print short description of the object.""" |
summary = list()
summary.append("%s %s" % (self.geotype, self.name) + "\n")
summary.append(" - Metadata:" + "\n")
summary.append(
"\n".join(self._get_metadata_as_string().split("\n")[:5]) + "\n")
summary.append("\n")
summary.append(" - Columns:" + "\n")
summary.append(self.columns.to_string() + "\n")
summary.append("\n")
summary.append(" - Table:" + "\n")
summary.append(
"\t".join(["Index"] + self.table.columns.tolist()) + "\n")
summary.append(self.table.head().to_string(header=None) + "\n")
summary.append(" " * 40 + "..." + " " * 40 + "\n")
summary.append(" " * 40 + "..." + " " * 40 + "\n")
summary.append(" " * 40 + "..." + " " * 40 + "\n")
summary.append(self.table.tail().to_string(header=None) + "\n")
return "\n".join([str(s) for s in summary]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_object_as_soft(self):
"""Get the object as SOFT formated string.""" |
soft = ["^%s = %s" % (self.geotype, self.name),
self._get_metadata_as_string(),
self._get_columns_as_string(),
self._get_table_as_string()]
return "\n".join(soft) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_table_as_string(self):
"""Get table as SOFT formated string.""" |
tablelist = []
tablelist.append("!%s_table_begin" % self.geotype.lower())
tablelist.append("\t".join(self.table.columns))
for idx, row in self.table.iterrows():
tablelist.append("\t".join(map(str, row)))
tablelist.append("!%s_table_end" % self.geotype.lower())
return "\n".join(tablelist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_columns_as_string(self):
"""Returns columns as SOFT formated string.""" |
columnslist = []
for rowidx, row in self.columns.iterrows():
columnslist.append("#%s = %s" % (rowidx, row.description))
return "\n".join(columnslist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotate(self, gpl, annotation_column, gpl_on="ID", gsm_on="ID_REF", in_place=False):
"""Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`):
A Platform or DataFrame to annotate with annotation_column (str`):
Column in a table for annotation gpl_on (:obj:`str`):
Use this column in GSM to merge. Defaults to "ID". gsm_on (:obj:`str`):
Use this column in GPL to merge. Defaults to "ID_REF". in_place (:obj:`bool`):
Substitute table in GSM by new annotated table. Defaults to False. Returns: :obj:`pandas.DataFrame` or :obj:`None`: Annotated table or None Raises: TypeError: GPL should be GPL or pandas.DataFrame """ |
if isinstance(gpl, GPL):
annotation_table = gpl.table
elif isinstance(gpl, DataFrame):
annotation_table = gpl
else:
raise TypeError("gpl should be a GPL object or a pandas.DataFrame")
# annotate by merging
annotated = self.table.merge(
annotation_table[[gpl_on, annotation_column]], left_on=gsm_on,
right_on=gpl_on)
del annotated[gpl_on]
if in_place:
self.table = annotated
return None
else:
return annotated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotate_and_average(self, gpl, expression_column, group_by_column, rename=True, force=False, merge_on_column=None, gsm_on=None, gpl_on=None):
"""Annotate GSM table with provided GPL. Args: gpl (:obj:`GEOTypes.GPL`):
Platform for annotations expression_column (:obj:`str`):
Column name which "expressions" are represented group_by_column (:obj:`str`):
The data will be grouped and averaged over this column and only this column will be kept rename (:obj:`bool`):
Rename output column to the self.name. Defaults to True. force (:obj:`bool`):
If the name of the GPL does not match the platform name in GSM proceed anyway. Defaults to False. merge_on_column (:obj:`str`):
Column to merge the data on. Defaults to None. gsm_on (:obj:`str`):
In the case columns to merge are different in GSM and GPL use this column in GSM. Defaults to None. gpl_on (:obj:`str`):
In the case columns to merge are different in GSM and GPL use this column in GPL. Defaults to None. Returns: :obj:`pandas.DataFrame`: Annotated data """ |
if gpl.name != self.metadata['platform_id'][0] and not force:
raise KeyError("Platforms from GSM (%s) and from GPL (%s)" % (
gpl.name, self.metadata['platform_id']) +
" are incompatible. Use force=True to use this GPL.")
if merge_on_column is None and gpl_on is None and gsm_on is None:
raise Exception("You have to provide one of the two: "
"merge_on_column or gpl_on and gsm_on parameters")
if merge_on_column:
logger.info("merge_on_column is not None. Using this option.")
tmp_data = self.table.merge(gpl.table, on=merge_on_column,
how='outer')
tmp_data = tmp_data.groupby(group_by_column).mean()[
[expression_column]]
else:
if gpl_on is None or gsm_on is None:
raise Exception("Please provide both gpl_on and gsm_on or "
"provide merge_on_column only")
tmp_data = self.table.merge(gpl.table, left_on=gsm_on,
right_on=gpl_on, how='outer')
tmp_data = tmp_data.groupby(group_by_column).mean()[
[expression_column]]
if rename:
tmp_data.columns = [self.name]
return tmp_data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.