code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def _pulse():
start_time = time.time()
while True:
data = json.dumps({"header": "pyblish-qml:server.pulse"})
if six.PY3:
data = data.encode("ascii")
try:
self.popen.stdin.write(data + b"\... | def _start_pulse(self) | Send pulse to child process
Child process will run forever if parent process encounter such
failure that not able to kill child process.
This inform child process that server is still running and child
process will auto kill itself after server stop sending pulse
message. | 3.380916 | 3.085513 | 1.095739 |
if aschild:
print("Starting pyblish-qml")
compat.main()
app = Application(APP_PATH, targets)
app.listen()
print("Done, don't forget to call `show()`")
return app.exec_()
else:
print("Starting pyblish-qml server..")
service = ipc.service.Moc... | def main(demo=False, aschild=False, targets=[]) | Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process | 7.128738 | 7.441773 | 0.957935 |
if event.type() == QtCore.QEvent.Close:
modifiers = self.app.queryKeyboardModifiers()
shift_pressed = QtCore.Qt.ShiftModifier & modifiers
states = self.app.controller.states
if shift_pressed:
print("Force quitted..")
self.... | def event(self, event) | Allow GUI to be closed upon holding Shift | 5.454304 | 5.037464 | 1.082748 |
window = self.window
if client_settings:
# Apply client-side settings
settings.from_dict(client_settings)
window.setWidth(client_settings["WindowSize"][0])
window.setHeight(client_settings["WindowSize"][1])
window.setTitle(client_sett... | def show(self, client_settings=None) | Display GUI
Once the QML interface has been loaded, use this
to display it.
Arguments:
port (int): Client asking to show GUI.
client_settings (dict, optional): Visual settings, see settings.py | 4.662523 | 4.716457 | 0.988565 |
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | def inFocus(self) | Set GUI on-top flag | 5.215304 | 4.726765 | 1.103356 |
def _listen():
while True:
line = self.host.channels["parent"].get()
payload = json.loads(line)["payload"]
# We can't call methods directly, as we are running
# in a thread. Instead, we emit signals that do the
... | def listen(self) | Listen on incoming messages from host
TODO(marcus): We can't use this, as we are already listening on stdin
through client.py. Do use this, we will have to find a way to
receive multiple signals from the same stdin, and channel them
to their corresponding source. | 5.126724 | 4.597264 | 1.115169 |
obj = _defer(target, args, kwargs, callback)
obj.finished.connect(lambda: _defer_cleanup(obj))
obj.start()
_defer_threads.append(obj)
return obj | def defer(target, args=None, kwargs=None, callback=None) | Perform operation in thread with callback
Instances are cached until finished, at which point
they are garbage collected. If we didn't do this,
Python would step in and garbage collect the thread
before having had time to finish, resulting in an
exception.
Arguments:
target (callable):... | 4.08492 | 5.971524 | 0.684067 |
try:
_jobs[channel].stop()
except (AttributeError, KeyError):
pass
timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(func)
timer.start(time)
_jobs[channel] = timer | def schedule(func, time, channel="default") | Run `func` at a later `time` in a dedicated `channel`
Given an arbitrary function, call this function after a given
timeout. It will ensure that only one "job" is running within
the given channel at any one time and cancel any currently
running job if a new job is submitted before the timeout. | 2.874473 | 2.918515 | 0.98491 |
result = ""
for paragraph in text.split("\n\n"):
result += " ".join(paragraph.split()) + "\n\n"
result = result.rstrip("\n") # Remove last newlines
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
i... | def format_text(text) | Remove newlines, but preserve paragraphs | 4.519508 | 4.127446 | 1.094989 |
# (NOTE) davidlatwe
# Thanks to this answer
# https://stackoverflow.com/questions/18740884
if len(args) == 0 or isinstance(args[0], types.FunctionType):
args = []
@QtCore.pyqtSlot(*args)
def slotdecorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
... | def SlotSentinel(*args) | Provides exception handling for all slots | 5.683672 | 5.246748 | 1.083275 |
# Unicode
if isinstance(data, six.text_type):
return data.encode("utf-8")
# Members of lists
if isinstance(data, list):
return [_byteify(item) for item in data]
# Members of dicts
if isinstance(data, dict):
return {
_byteify(key): _byteify(value) for k... | def _byteify(data) | Convert unicode to bytes | 2.5087 | 2.466756 | 1.017004 |
plugin = plugin.to_json()
instance = instance.to_json() if instance is not None else None
return self._dispatch("process", args=[plugin, instance, action]) | def process(self, plugin, context, instance=None, action=None) | Transmit a `process` request to host
Arguments:
plugin (PluginProxy): Plug-in to process
context (ContextProxy): Filtered context
instance (InstanceProxy, optional): Instance to process
action (str, optional): Action to process | 4.682341 | 5.564596 | 0.841452 |
# This will give parent process 15 seconds to reset.
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() | def _self_destruct(self) | Auto quit exec if parent process failed | 8.15798 | 6.284283 | 1.298156 |
def _listen():
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 par... | 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. | 5.072214 | 4.554266 | 1.113728 |
data = json.dumps(
{
"header": "pyblish-qml:popen.request",
"payload": {
"name": func,
"args": args or list(),
}
}
)
# This should never happen. Each request is immediately
... | 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 | 5.386047 | 5.321522 | 1.012125 |
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(nam... | 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`. | 5.489808 | 4.93743 | 1.111876 |
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)
re... | 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:
>>> item = Item(name="default... | 5.597877 | 5.438179 | 1.029366 |
self.beginInsertRows(QtCore.QModelIndex(),
self.rowCount(),
self.rowCount())
item["parent"] = self
item = Item(**item)
self.items.append(item)
self.endInsertRows()
item.__datachanged__.connect(self._dat... | def add_item(self, item) | Add new item to model
Each keyword argument is passed to the :func:Item
factory function. | 4.507364 | 4.079167 | 1.104972 |
index = self.items.index(item)
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.items.remove(item)
self.endRemoveRows() | def remove_item(self, item) | Remove item from model | 2.242289 | 1.980187 | 1.132362 |
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) | def _dataChanged(self, item) | Explicitly emit dataChanged upon item changing | 3.246956 | 2.886308 | 1.124951 |
item = {}
item.update(defaults["common"])
item.update(defaults["plugin"])
for member in ["pre11",
"name",
"label",
"optional",
"category",
"actions",
... | def add_plugin(self, plugin) | Append `plugin` to model
Arguments:
plugin (dict): Serialised plug-in from pyblish-rpc
Schema:
plugin.json | 6.386456 | 6.102021 | 1.046613 |
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)
it... | def add_instance(self, instance) | Append `instance` to model
Arguments:
instance (dict): Serialised instance
Schema:
instance.json | 5.706875 | 5.850436 | 0.975462 |
self.instances.remove(item)
self.remove_item(item) | def remove_instance(self, item) | Remove `instance` from model | 4.626696 | 4.359278 | 1.061344 |
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_... | def add_section(self, name) | Append `section` to model
Arguments:
name (str): Name of section | 4.559703 | 4.566751 | 0.998457 |
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"
i... | def add_context(self, context, label=None) | Append `context` to model
Arguments:
context (dict): Serialised to add
Schema:
context.json | 6.728445 | 6.797383 | 0.989858 |
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 = ... | 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 | 3.757829 | 3.700293 | 1.015549 |
for item in self.items:
item.isProcessing = False
item.currentProgress = 0 | def reset_status(self) | Reset progress bars | 8.388819 | 7.616677 | 1.101375 |
self._add_rule(self.excludes, role, value) | 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 | 10.87217 | 13.19055 | 0.824239 |
self._remove_rule(self.excludes, role, value) | def remove_exclusion(self, role, value=None) | Remove exclusion rule
Arguments:
role (int, string): Qt role or name to remove
value (object, optional): Value to remove. If none
is supplied, the entire role will be removed. | 9.688647 | 8.100985 | 1.195984 |
self._add_rule(self.includes, role, value) | 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 | 12.331148 | 15.128143 | 0.815113 |
self._remove_rule(self.includes, role, value) | def remove_inclusion(self, role, value=None) | Remove exclusion rule | 10.443452 | 6.591344 | 1.584419 |
if role not in group:
group[role] = list()
group[role].append(value)
self.invalidate() | def _add_rule(self, group, role, value) | Implementation detail | 4.806565 | 4.359205 | 1.102624 |
if role not in group:
return
if value is None:
group.pop(role, None)
else:
group[role].remove(value)
self.invalidate() | def _remove_rule(self, group, role, value=None) | Implementation detail | 3.130214 | 2.979831 | 1.050467 |
group.clear()
for rule in rules:
self._add_rule(group, *rule)
self.invalidate() | def _set_rules(self, group, rules) | Implementation detail | 5.740563 | 6.095092 | 0.941834 |
model = self.sourceModel()
item = model.items[source_row]
key = getattr(item, "filter", None)
if key is not None:
regex = self.filterRegExp()
if regex.pattern():
match = regex.indexIn(key)
return False if match == -1 else ... | def filterAcceptsRow(self, source_row, source_parent) | Exclude items in `self.excludes` | 2.835112 | 2.682888 | 1.056739 |
instance = None
error = None
if result["instance"] is not None:
instance = format_instance(result["instance"])
if result["error"] is not None:
error = format_error(result["error"])
result = {
"success": result["success"],
"plugin": format_plugin(result["plugin... | def format_result(result) | Serialise Result | 3.255446 | 3.193316 | 1.019456 |
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted | def format_records(records) | Serialise multiple records | 4.44256 | 4.087235 | 1.086935 |
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
"thread",
"created",
"process",
"processName",
"args",
"module",
"filename",
"levelno",
... | def format_record(record) | Serialise LogRecord instance | 4.476944 | 4.376306 | 1.022996 |
formatted = {"message": str(error)}
if hasattr(error, "traceback"):
fname, line_no, func, exc = error.traceback
formatted.update({
"fname": fname,
"line_number": line_no,
"func": func,
"exc": exc
})
return formatted | def format_error(error) | Serialise exception | 4.127395 | 3.925222 | 1.051506 |
instance = {
"name": instance.name,
"id": instance.id,
"data": format_data(instance.data),
"children": list(),
}
if os.getenv("PYBLISH_SAFE"):
schema.validate(instance, "instance")
return instance | def format_instance(instance) | Serialise `instance`
For children to be visualised and modified,
they must provide an appropriate implementation
of __str__.
Data that isn't JSON compatible cannot be
visualised nor modified.
Attributes:
name (str): Name of instance
niceName (str, optional): Nice name of insta... | 5.967261 | 7.429458 | 0.803189 |
formatted = []
for plugin_ in plugins:
formatted_plugin = format_plugin(plugin_)
formatted.append(formatted_plugin)
return formatted | def format_plugins(plugins) | Serialise multiple plug-in
Returns:
List of JSON-compatible plug-ins | 3.557207 | 3.854661 | 0.922832 |
type = "Other"
for order, _type in {pyblish.plugin.CollectorOrder: "Collector",
pyblish.plugin.ValidatorOrder: "Validator",
pyblish.plugin.ExtractorOrder: "Extractor",
pyblish.plugin.IntegratorOrder: "Integrator"}.items():
... | def format_plugin(plugin) | Serialise `plugin`
Attributes:
name: Name of Python class
id: Unique identifier
version: Plug-in version
category: Optional category
requires: Plug-in requirements
order: Plug-in order
optional: Is the plug-in optional?
doc: The plug-in documentation
... | 3.15232 | 2.897426 | 1.087973 |
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)
... | def iterator(plugins, context) | An iterator for plug-in and instance pairs | 6.128952 | 5.943991 | 1.031117 |
test = pyblish.logic.registered_test()
state = {
"nextOrder": None,
"ordersWithError": set()
}
signals = {
pyblish.api.ValidatorOrder: self.validating,
pyblish.api.ExtractorOrder: self.extracting,
pyblish.api.Integrat... | def iterator(self, plugins, context) | Primary iterator
CAUTION: THIS RUNS IN A SEPARATE THREAD
This is the brains of publishing. It handles logic related
to which plug-in to process with which Instance or Context,
in addition to stopping when necessary. | 5.539783 | 5.430859 | 1.020057 |
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(ac... | def getPluginActions(self, index) | Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model | 3.547254 | 3.488947 | 1.016712 |
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":
... | 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 | 3.706247 | 3.311606 | 1.119169 |
item = model.items[index]
data = {
"name": item.name,
"data": item.data,
"doc": getattr(item, "doc", None),
"path": getattr(item, "path", None),
}
return data | def __item_data(self, model, index) | Return item data as dict | 3.24232 | 3.054556 | 1.06147 |
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | def comment_sync(self, comment) | Update comments to host and notify subscribers | 9.536229 | 6.811892 | 1.399938 |
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... | def on_commenting(self, comment) | The user is entering a comment | 10.824616 | 11.067598 | 0.978046 |
if instance is None:
instance_item = self.data["models"]["item"].instances[0]
else:
instance_item = self.data["models"]["item"].instances[instance.id]
plugin_item = self.data["models"]["item"].plugins[plugin.id]
for section in self.data["models"]["item... | def on_about_to_process(self, plugin, instance) | Reflect currently running pair in GUI | 3.456757 | 3.368813 | 1.026105 |
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_plugi... | def publish(self) | Start asynchonous publishing
Publishing takes into account all available and currently
toggled plug-ins and instances. | 6.741343 | 6.235678 | 1.081092 |
# if "ready" not in self.states:
# return self.error.emit("Not ready")
# Initial set-up
self.data["state"]["is_running"] = True
# Setup statistics for better debugging.
# (To be finalised in `on_finished`)
util.timer("publishing")
stats = {... | def run(self, plugins, context, callback=None, callback_args=[]) | Commence asynchronous tasks
This method runs through the provided `plugins` in
an asynchronous manner, interrupted by either
completion or failure of a plug-in.
Inbetween processes, the GUI is fed information
from the task and redraws itself.
Arguments:
plu... | 4.775676 | 4.654646 | 1.026002 |
assert isinstance(settings, dict), "`settings` must be of type dict"
for key, value in settings.items():
setattr(self, key, value) | def from_dict(settings) | Apply settings from dictionary
Arguments:
settings (dict): Settings in the form of a dictionary | 3.75686 | 4.056662 | 0.926097 |
if not isinstance(obj, ClassTypes):
# already an instance
return getattr(obj, '__call__', None) is not None
klass = obj
# uses __bases__ instead of __mro__ so that we work with old style classes
if klass.__dict__.get('__call__') is not None:
return True
for base in kla... | def _instance_callable(obj) | Given an object, return True if the object is callable.
For classes, return True if instances would be callable. | 4.420306 | 4.145127 | 1.066386 |
if type(target) in (unicode, str):
getter = lambda: _importer(target)
else:
getter = lambda: target
if not kwargs:
raise ValueError(
'Must supply at least one keyword argument with patch.multiple'
)
# need to wrap in a list for python 3, where items is a... | def _patch_multiple(target, spec=None, create=False, spec_set=None,
autospec=None, new_callable=None, **kwargs) | Perform multiple patches in a single call. It takes the object to be
patched (either as an object or a string to fetch the object by importing)
and keyword arguments for the patches::
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
...
Use `DEFAULT` as the value i... | 3.294321 | 3.444745 | 0.956332 |
getter, attribute = _get_target(target)
return _patch(
getter, attribute, new, spec, create,
spec_set, autospec, new_callable, kwargs
) | def patch(
target, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs
) | `patch` acts as a function decorator, class decorator or a context
manager. Inside the body of the function or with statement, the `target`
is patched with a `new` object. When the function/with statement exits
the patch is undone.
If `new` is omitted, then the target is replaced with a
`MagicMock`... | 3.85517 | 6.840896 | 0.563548 |
"Turns a callable object (like a mock) into a real function"
def method(self, *args, **kw):
return func(self, *args, **kw)
method.__name__ = name
return method | def _get_method(name, func) | Turns a callable object (like a mock) into a real function | 4.375156 | 2.507251 | 1.745001 |
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 Non... | 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 t... | 5.342958 | 5.499482 | 0.971538 |
global file_spec
if file_spec is None:
# set on first use
if inPy3k:
import _io
file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
else:
file_spec = file
if mock is None:
mock = MagicMock(name='open', spec=open... | def mock_open(mock=None, read_data='') | A helper function to create a mock to replace the use of `open`. It works
for `open` called directly or used as a context manager.
The `mock` argument is the mock object to configure. If `None` (the
default) then a `MagicMock` will be created for you, with the API limited
to methods or attributes avail... | 3.410118 | 3.476716 | 0.980845 |
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock) | 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. | 4.385824 | 4.726692 | 0.927885 |
"Restore the mock object to its initial state."
self.called = False
self.call_args = None
self.call_count = 0
self.mock_calls = _CallList()
self.call_args_list = _CallList()
self.method_calls = _CallList()
for child in self._mock_children.values():
... | def reset_mock(self) | Restore the mock object to its initial state. | 3.771199 | 3.534907 | 1.066845 |
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('.'))... | 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:
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mo... | 5.061237 | 6.123253 | 0.82656 |
self = _mock_self
if self.call_args is None:
expected = self._format_mock_call_signature(args, kwargs)
raise AssertionError('Expected call: %s\nNot called' % (expected,))
if self.call_args != (args, kwargs):
msg = self._format_mock_failure_message(ar... | def assert_called_with(_mock_self, *args, **kwargs) | assert that the mock was called with the specified arguments.
Raises an AssertionError if the args and keyword args passed in are
different to the last call to the mock. | 3.782413 | 3.682244 | 1.027203 |
if not any_order:
if calls not in self.mock_calls:
raise AssertionError(
'Calls not found.\nExpected: %r\n'
'Actual: %r' % (calls, self.mock_calls)
)
return
all_calls = list(self.mock_calls)
... | def assert_has_calls(self, calls, any_order=False) | assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
specified calls.
If `any_order` is True then the calls... | 2.699898 | 2.636551 | 1.024027 |
kall = call(*args, **kwargs)
if kall not in self.call_args_list:
expected_string = self._format_mock_call_signature(args, kwargs)
raise AssertionError(
'%s call not found' % expected_string
) | def assert_any_call(self, *args, **kwargs) | assert the mock has been called with the specified arguments.
The assert passes if the mock has *ever* been called, unlike
`assert_called_with` and `assert_called_once_with` that only pass if
the call is the most recent one. | 6.127391 | 5.164378 | 1.186472 |
_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]
ret... | 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 c... | 4.252579 | 3.810255 | 1.116088 |
result = self.__enter__()
self._active_patches.add(self)
return result | def start(self) | Activate a patch, returning any created mock. | 13.482831 | 7.428076 | 1.815117 |
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | 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. | 6.223577 | 8.168489 | 0.761901 |
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals)) | 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. | 7.419879 | 6.500862 | 1.141369 |
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()... | def _wrapinstance(func, ptr, base=None) | Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not pr... | 2.52046 | 2.459012 | 1.024989 |
for src, dst in _misplaced_members[binding].items():
src_module, src_member = src.split(".")
dst_module, dst_member = dst.split(".")
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
# Skip reassignment of non-existing members.
... | def _reassign_misplaced_members(binding) | Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members | 4.808294 | 4.700799 | 1.022867 |
import PySide2 as module
_setup(module, ["QtUiTools"])
Qt.__binding_version__ = module.__version__
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
f... | def _pyside2() | Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py | 4.611264 | 4.407295 | 1.04628 |
import PySide as module
_setup(module, ["QtUiTools"])
Qt.__binding_version__ = module.__version__
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
fro... | def _pyside() | Initialise PySide | 4.132303 | 4.066586 | 1.01616 |
import PyQt5 as module
_setup(module, ["uic"])
try:
import sip
Qt.QtCompat.wrapInstance = (
lambda ptr, base=None: _wrapinstance(
sip.wrapinstance, ptr, base)
)
Qt.QtCompat.getCppPointer = lambda object: \
sip.unwrapinstance(obje... | def _pyqt5() | Initialise PyQt5 | 4.861306 | 4.86172 | 0.999915 |
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_... | def _pyqt4() | Initialise PyQt4 | 4.418611 | 4.394482 | 1.005491 |
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
def __init__(self, baseinstance):
super(_UiLoader, ... | def _loadUi(uifile, baseinstance=None) | Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute... | 3.567816 | 3.441404 | 1.036733 |
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):
try:
return wrapper(func, ... | def register_dispatch_wrapper(wrapper) | Register a dispatch wrapper for servers
The wrapper must have this exact signature:
(func, *args, **kwargs) | 4.435513 | 4.175719 | 1.062216 |
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 | def install(modal) | Perform first time install | 10.071974 | 9.721732 | 1.036027 |
# 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['autoVali... | 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 | 5.347835 | 4.993282 | 1.071006 |
for install in (_install_maya,
_install_houdini,
_install_nuke,
_install_nukeassist,
_install_hiero,
_install_nukestudio,
_install_blender):
try:
install(use_threaded_wra... | 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. | 3.538384 | 3.546794 | 0.997629 |
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) | 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 PYTHO... | 3.581282 | 3.431641 | 1.043606 |
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()
_com... | def _install_maya(use_threaded_wrapper) | Helper function to Autodesk Maya support | 5.308569 | 5.477155 | 0.96922 |
import hdefereval
def threaded_wrapper(func, *args, **kwargs):
return hdefereval.executeInMainThreadWithResult(
func, *args, **kwargs)
_common_setup("Houdini", threaded_wrapper, use_threaded_wrapper) | def _install_houdini(use_threaded_wrapper) | Helper function to SideFx Houdini support | 5.045031 | 5.031442 | 1.002701 |
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(
... | def _install_nuke(use_threaded_wrapper) | Helper function to The Foundry Nuke support | 4.897795 | 4.829197 | 1.014205 |
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) | def _install_nukeassist(use_threaded_wrapper) | Helper function to The Foundry NukeAssist support | 5.378176 | 5.159469 | 1.04239 |
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) | def _install_hiero(use_threaded_wrapper) | Helper function to The Foundry Hiero support | 5.476368 | 5.291718 | 1.034894 |
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):
bl_idname = "wm.pyblish_q... | 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 whil... | 3.276132 | 3.163966 | 1.035451 |
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":
... | def install(self, host) | Setup common to all Qt-based hosts | 4.947663 | 4.777631 | 1.035589 |
window = self.app.activeWindow()
while True:
parent_window = window.parent()
if parent_window:
window = parent_window
else:
break
return window | def find_window(self) | Get top window in host | 3.588146 | 3.258023 | 1.101326 |
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())) | 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. | 5.911696 | 5.894743 | 1.002876 |
bindings = KeyBindings()
sidebar_visible = Condition(lambda: python_input.show_sidebar)
handle = bindings.add
@handle('c-l')
def _(event):
event.app.renderer.clear()
@handle('c-z')
def _(event):
if python_input.enable_system_bindings:
eve... | def load_python_bindings(python_input) | Custom key bindings. | 3.03201 | 3.01216 | 1.00659 |
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. "
pyth... | def load_sidebar_bindings(python_input) | Load bindings for the navigation in the sidebar. | 1.774729 | 1.781174 | 0.996382 |
bindings = KeyBindings()
handle = bindings.add
confirmation_visible = Condition(lambda: python_input.show_exit_confirmation)
@handle('y', filter=confirmation_visible)
@handle('Y', filter=confirmation_visible)
@handle('enter', filter=confirmation_visible)
@handle('c-d', filter=confirma... | def load_confirm_exit_bindings(python_input) | Handle yes/no key presses when the exit confirmation is shown. | 3.182606 | 2.960234 | 1.07512 |
r
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.... | def auto_newline(buffer) | r"""
Insert \n at the cursor position. Also add necessary padding. | 4.407835 | 4.188818 | 1.052286 |
# 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... | def _path_completer_grammar(self) | Return the grammar for matching paths inside strings inside Python
code. | 4.274474 | 3.874425 | 1.103254 |
# 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 sel... | def get_completions(self, document, complete_event) | Get Python completions. | 3.651045 | 3.613152 | 1.010487 |
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wait_using_filehandler():
# Add a handler that sets the stop flag when `prompt-toolkit` has input
# to process.
stop = ... | def _inputhook_tk(inputhook_context) | Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input. | 5.173679 | 4.860495 | 1.064435 |
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(... | 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. | 3.284563 | 3.149126 | 1.043008 |
assert configure is None or callable(configure)
# Default globals/locals
if globals is None:
globals = {
'__name__': '__main__',
'__package__': None,
'__doc__': None,
'__builtins__': six.moves.builtins,
}
locals = locals or globals
... | def embed(globals=None, locals=None, configure=None,
vi_mode=False, history_filename=None, title=None,
startup_paths=None, patch_stdout=False, return_asyncio_coroutine=False) | Call this to embed Python shell at the current point in your program.
It's similar to `IPython.embed` and `bpython.embed`. ::
from prompt_toolkit.contrib.repl import embed
embed(globals(), locals())
:param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
:param configure: Callable ... | 3.204487 | 3.340601 | 0.959254 |
" 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.ge... | def _load_start_paths(self) | Start the Read-Eval-Print Loop. | 3.938957 | 3.19419 | 1.233163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.