sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _check_middleware_dependencies(concerned_object, required_middleware): """ Check required middleware dependencies exist and in the correct order. Args: concerned_object (object): The object for which the required middleware is being checked. This is used for error messages only. ...
Check required middleware dependencies exist and in the correct order. Args: concerned_object (object): The object for which the required middleware is being checked. This is used for error messages only. required_middleware (list of String): An ordered list representing the ...
entailment
def is_valid_request(self, request, parameters={}, fake_method=None, handle_error=True): ''' Validates an OAuth request using the python-oauth2 library: https://github.com/simplegeo/python-oauth2 ''' try: # Set the parameters to be what w...
Validates an OAuth request using the python-oauth2 library: https://github.com/simplegeo/python-oauth2
entailment
def parse_request(self, request, parameters=None, fake_method=None): ''' Parse Flask request ''' return (request.method, request.url, request.headers, request.form.copy())
Parse Flask request
entailment
def parse_request(self, request, parameters, fake_method=None): ''' Parse Django request ''' return (fake_method or request.method, request.build_absolute_uri(), request.META, (dict(request.POST.iteritems()) if request.m...
Parse Django request
entailment
def parse_request(self, request, parameters=None, fake_method=None): ''' Parse WebOb request ''' return (request.method, request.url, request.headers, request.POST.mixed())
Parse WebOb request
entailment
def from_post_response(post_response, content): ''' Convenience method for creating a new OutcomeResponse from a response object. ''' response = OutcomeResponse() response.post_response = post_response response.response_code = post_response.status response...
Convenience method for creating a new OutcomeResponse from a response object.
entailment
def process_xml(self, xml): ''' Parse OutcomeResponse data form XML. ''' try: root = objectify.fromstring(xml) # Get message idenifier from header info self.message_identifier = root.imsx_POXHeader.\ imsx_POXResponseHeaderInfo.\ ...
Parse OutcomeResponse data form XML.
entailment
def generate_response_xml(self): ''' Generate XML based on the current configuration. ''' root = etree.Element( 'imsx_POXEnvelopeResponse', xmlns='http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0') header = etree.SubElement(root, 'imsx_POXHeader'...
Generate XML based on the current configuration.
entailment
def profiled_thread(func): """decorator to profile a thread or function. Profiling output will be written to 'agent_profile_<process_id>.<thread_id_>.<thread_name>.log'""" def wrapper(*args, **kwargs): profile = Profile() profile.enable() try: func(*args, **kwargs) ...
decorator to profile a thread or function. Profiling output will be written to 'agent_profile_<process_id>.<thread_id_>.<thread_name>.log
entailment
def _minimally_quoted_parameter_value(value): """ Per RFC 7321 (https://tools.ietf.org/html/rfc7231#section-3.1.1.1): Parameters values don't need to be quoted if they are a "token". Token characters are defined by RFC 7320 (https://tools.ietf.org/html/rfc7230#section-3.2.6). Oth...
Per RFC 7321 (https://tools.ietf.org/html/rfc7231#section-3.1.1.1): Parameters values don't need to be quoted if they are a "token". Token characters are defined by RFC 7320 (https://tools.ietf.org/html/rfc7230#section-3.2.6). Otherwise, parameters values can be a "quoted-string". So we ...
entailment
def set_custom_metrics_for_course_key(course_key): """ Set monitoring custom metrics related to a course key. This is not cached, and only support reporting to New Relic Insights. """ if not newrelic: return newrelic.agent.add_custom_parameter('course_id', six.text_type(course_key)) ...
Set monitoring custom metrics related to a course key. This is not cached, and only support reporting to New Relic Insights.
entailment
def set_monitoring_transaction_name(name, group=None, priority=None): """ Sets the transaction name for monitoring. This is not cached, and only support reporting to New Relic. """ if not newrelic: return newrelic.agent.set_transaction_name(name, group, priority)
Sets the transaction name for monitoring. This is not cached, and only support reporting to New Relic.
entailment
def function_trace(function_name): """ Wraps a chunk of code that we want to appear as a separate, explicit, segment in our monitoring tools. """ if newrelic: nr_transaction = newrelic.agent.current_transaction() with newrelic.agent.FunctionTrace(nr_transaction, function_name): ...
Wraps a chunk of code that we want to appear as a separate, explicit, segment in our monitoring tools.
entailment
def channel(self, channel_id=None, auto_encode_decode=True): """Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. See Channel for meaning of auto_encode_decode. If the channel already exists, the auto_* flag will not be update...
Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. See Channel for meaning of auto_encode_decode. If the channel already exists, the auto_* flag will not be updated.
entailment
def drain_events(self, timeout=None): """Wait for an event on a channel.""" chanmap = self.channels chanid, method_sig, args, content = self._wait_multiple( chanmap, None, timeout=timeout, ) channel = chanmap[chanid] if (content and channel.a...
Wait for an event on a channel.
entailment
def close(self, reply_code=0, reply_text='', method_sig=(0, 0)): """Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e...
Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender pro...
entailment
def filter_by(self, types=(), units=()): """Return list of value labels, filtered by either or both type and unit. An empty sequence for either argument will match as long as the other argument matches any values.""" if not (isinstance(types, Sequence) and isinstance(units, Sequence)): ...
Return list of value labels, filtered by either or both type and unit. An empty sequence for either argument will match as long as the other argument matches any values.
entailment
def get_template(self, data=None): # noqa (complexity) """Get new template which represents the values of this point in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject). If data is set (to a dictionary), use this to populate the created template.""" with self.__l...
Get new template which represents the values of this point in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject). If data is set (to a dictionary), use this to populate the created template.
entailment
def __refresh(self): """Update local knowledge of values (to be used to create new skeletal instances). MUST be called within lock.""" raw_values = self.__get_values() if not raw_values: raise RefreshException('Point has no values') # individual templates tem...
Update local knowledge of values (to be used to create new skeletal instances). MUST be called within lock.
entailment
def __get_values(self): """Retrieve value information either via describe or point value listing. MUST be called within lock.""" values = [] if self.__remote: description = self.__client.describe(self.__point) if description is not None: if description['t...
Retrieve value information either via describe or point value listing. MUST be called within lock.
entailment
def get_s3_multipart_chunk_size(filesize): """Returns the chunk size of the S3 multipart object, given a file's size.""" if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE: return AWS_MIN_CHUNK_SIZE else: div = filesize // AWS_MAX_MULTIPART_COUNT if div * AWS_MAX_MULTIPART_C...
Returns the chunk size of the S3 multipart object, given a file's size.
entailment
def set_ext_param(self, ext_key, param_key, val): ''' Set the provided parameter in a set of extension parameters. ''' if not self.extensions[ext_key]: self.extensions[ext_key] = defaultdict(lambda: None) self.extensions[ext_key][param_key] = val
Set the provided parameter in a set of extension parameters.
entailment
def get_ext_param(self, ext_key, param_key): ''' Get specific param in set of provided extension parameters. ''' return self.extensions[ext_key][param_key] if self.extensions[ext_key]\ else None
Get specific param in set of provided extension parameters.
entailment
def process_xml(self, xml): ''' Parse tool configuration data out of the Common Cartridge LTI link XML. ''' root = objectify.fromstring(xml, parser = etree.XMLParser()) # Parse all children of the root node for child in root.getchildren(): if 'title' in child....
Parse tool configuration data out of the Common Cartridge LTI link XML.
entailment
def to_xml(self, opts = defaultdict(lambda: None)): ''' Generate XML from the current settings. ''' if not self.launch_url or not self.secure_launch_url: raise InvalidLTIConfigError('Invalid LTI configuration') root = etree.Element('cartridge_basiclti_link', attrib ...
Generate XML from the current settings.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration if d.orientation == 'vertical': self.widget = ScrollView(self.get_context(), None, d.style) else: self.widget = HorizontalScrollView(self.get_context(), ...
Create the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CalendarView(self.get_context(), None, d.style or "@attr/calendarViewStyle")
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidCalendarView, self).init_widget() #: Setup listener w = self.widget w.setOnDateChangeListener(w.getId()) w.onSelectedDayChange.connect(self.on_selected_day_change)
Initialize the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidFragment, self).init_widget() f = self.fragment f.setFragmentListener(f.getId()) f.onCreateView.connect(self.on_create_view) f.onDestroyView.connect(self.on_destroy_view)
Initialize the underlying widget.
entailment
def init_layout(self): """ Initialize the layout of the toolkit widget. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will be fully initialized and layed out when this is called. """ parent = s...
Initialize the layout of the toolkit widget. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will be fully initialized and layed out when this is called.
entailment
def destroy(self): """ Custom destructor that deletes the fragment and removes itself from the adapter it was added to. """ #: Destroy fragment fragment = self.fragment if fragment: #: Stop listening fragment.setFragmentListener(None) ...
Custom destructor that deletes the fragment and removes itself from the adapter it was added to.
entailment
def on_create_view(self): """ Trigger the click """ d = self.declaration changed = not d.condition if changed: d.condition = True view = self.get_view() if changed: self.ready.set_result(True) return view
Trigger the click
entailment
def get_view(self): """ Get the page to display. If a view has already been created and is cached, use that otherwise initialize the view and proxy. If defer loading is used, wrap the view in a FrameLayout and defer add view until later. """ d = self.declaratio...
Get the page to display. If a view has already been created and is cached, use that otherwise initialize the view and proxy. If defer loading is used, wrap the view in a FrameLayout and defer add view until later.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidPagerFragment, self).init_widget() d = self.declaration if d.title: self.set_title(d.title) if d.icon: self.set_icon(d.icon)
Initialize the underlying widget.
entailment
def engine(func): """Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it d...
Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it does not return a `.Fu...
entailment
def _make_coroutine_wrapper(func, replace_callback): """The inner workings of ``@gen.coroutine`` and ``@gen.engine``. The two decorators differ in their treatment of the ``callback`` argument, so we cannot simply implement ``@engine`` in terms of ``@coroutine``. """ # On Python 3.5, set the cor...
The inner workings of ``@gen.coroutine`` and ``@gen.engine``. The two decorators differ in their treatment of the ``callback`` argument, so we cannot simply implement ``@engine`` in terms of ``@coroutine``.
entailment
def Task(func, *args, **kwargs): """Adapts a callback-based asynchronous function for use in coroutines. Takes a function (and optional additional arguments) and runs it with those arguments plus a ``callback`` keyword argument. The argument passed to the callback is returned as the result of the yiel...
Adapts a callback-based asynchronous function for use in coroutines. Takes a function (and optional additional arguments) and runs it with those arguments plus a ``callback`` keyword argument. The argument passed to the callback is returned as the result of the yield expression. .. versionchanged:: 4...
entailment
def _contains_yieldpoint(children): """Returns True if ``children`` contains any YieldPoints. ``children`` may be a dict or a list, as used by `MultiYieldPoint` and `multi_future`. """ if isinstance(children, dict): return any(isinstance(i, YieldPoint) for i in children.values()) if isi...
Returns True if ``children`` contains any YieldPoints. ``children`` may be a dict or a list, as used by `MultiYieldPoint` and `multi_future`.
entailment
def multi(children, quiet_exceptions=()): """Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` ...
Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` is a list, the result is a list of results in...
entailment
def multi_future(children, quiet_exceptions=()): """Wait for multiple asynchronous futures in parallel. This function is similar to `multi`, but does not support `YieldPoints <YieldPoint>`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the...
Wait for multiple asynchronous futures in parallel. This function is similar to `multi`, but does not support `YieldPoints <YieldPoint>`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the first (which is raised) will be logged. Added th...
entailment
def maybe_future(x): """Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. ...
Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This...
entailment
def with_timeout(timeout, future, quiet_exceptions=()): """Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timed...
Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) ...
entailment
def sleep(duration): """Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling thi...
Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does n...
entailment
def _argument_adapter(callback): """Returns a function that when invoked runs ``callback`` with one arg. If the function returned by this function is called with exactly one argument, that argument is passed to ``callback``. Otherwise the args tuple and kwargs dict are wrapped in an `Arguments` object...
Returns a function that when invoked runs ``callback`` with one arg. If the function returned by this function is called with exactly one argument, that argument is passed to ``callback``. Otherwise the args tuple and kwargs dict are wrapped in an `Arguments` object.
entailment
def convert_yielded(yielded): """Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.r...
Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.register(asyncio.Future) def _...
entailment
def done(self): """Returns True if this iterator has no more results.""" if self._finished or self._unfinished: return False # Clear the 'current' values when iteration is done. self.current_index = self.current_future = None return True
Returns True if this iterator has no more results.
entailment
def next(self): """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = TracebackFuture() if self._finished: self._return_result(self._finished.po...
Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs.
entailment
def _return_result(self, done): """Called set the returned future's state that of the future we yielded, and set the current future for the iterator. """ chain_future(done, self._running_future) self.current_future = done self.current_index = self._unfinished.pop(done)
Called set the returned future's state that of the future we yielded, and set the current future for the iterator.
entailment
def register_callback(self, key): """Adds ``key`` to the list of callbacks.""" if self.pending_callbacks is None: # Lazily initialize the old-style YieldPoint data structures. self.pending_callbacks = set() self.results = {} if key in self.pending_callbacks: ...
Adds ``key`` to the list of callbacks.
entailment
def is_ready(self, key): """Returns true if a result is available for ``key``.""" if self.pending_callbacks is None or key not in self.pending_callbacks: raise UnknownKeyError("key %r is not pending" % (key,)) return key in self.results
Returns true if a result is available for ``key``.
entailment
def set_result(self, key, result): """Sets the result for ``key`` and attempts to resume the generator.""" self.results[key] = result if self.yield_point is not None and self.yield_point.is_ready(): try: self.future.set_result(self.yield_point.get_result()) ...
Sets the result for ``key`` and attempts to resume the generator.
entailment
def pop_result(self, key): """Returns the result for ``key`` and unregisters it.""" self.pending_callbacks.remove(key) return self.results.pop(key)
Returns the result for ``key`` and unregisters it.
entailment
def run(self): """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: future = self.future ...
Starts or resumes the generator, running until it reaches a yield point that is not ready.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = RadioButton(self.get_context(), None, d.style or '@attr/radioButtonStyle')
Create the underlying widget.
entailment
def write_message(self, data, binary=False): """ Write a message to the client """ self.connection.write_message(data, binary)
Write a message to the client
entailment
def render_files(self, root=None): """ Render the file path as accordions """ if root is None: tmp = os.environ.get('TMP') root = sys.path[1 if tmp and tmp in sys.path else 0] items = [] for filename in os.listdir(root): # for subdirname in di...
Render the file path as accordions
entailment
def render_code(self): """ Try to load the previous code (if we had a crash or something) I should allow saving. """ tmp_dir = os.environ.get('TMP','') view_code = os.path.join(tmp_dir,'view.enaml') if os.path.exists(view_code): try: with o...
Try to load the previous code (if we had a crash or something) I should allow saving.
entailment
def render_component(self, declaration): """ Render a row of all the attributes """ items = ["""<tr><td>{name}</td><td>{type}</td></tr>""" .format(name=m.name, type=self.render_component_types(declaration, m)) for m in self.get_component_members...
Render a row of all the attributes
entailment
def start(self): """ Start the dev session. Attempt to use tornado first, then try twisted """ print("Starting debug client cwd: {}".format(os.getcwd())) print("Sys path: {}".format(sys.path)) #: Initialize the hotswapper self.hotswap = Hotswapper(debug...
Start the dev session. Attempt to use tornado first, then try twisted
entailment
def _default_url(self): """ Websocket URL to connect to and listen for reload requests """ host = 'localhost' if self.mode == 'remote' else self.host return 'ws://{}:{}/dev'.format(host, self.port)
Websocket URL to connect to and listen for reload requests
entailment
def write_message(self, data, binary=False): """ Write a message to the active client """ self.client.write_message(data, binary=binary)
Write a message to the active client
entailment
def handle_message(self, data): """ When we get a message """ msg = json.loads(data) print("Dev server message: {}".format(msg)) handler_name = 'do_{}'.format(msg['type']) if hasattr(self, handler_name): handler = getattr(self, handler_name) result = handl...
When we get a message
entailment
def do_reload(self, msg): """ Called when the dev server wants to reload the view. """ #: TODO: This should use the autorelaoder app = self.app #: Show loading screen try: self.app.widget.showLoading("Reloading... Please wait.", now=True) #self.app.widget...
Called when the dev server wants to reload the view.
entailment
def do_hotswap(self, msg): """ Attempt to hotswap the code """ #: Show hotswap tooltip try: self.app.widget.showTooltip("Hot swapping...", now=True) except: pass self.save_changed_files(msg) hotswap = self.hotswap app = self.app tr...
Attempt to hotswap the code
entailment
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'event': name = 'do_'+change['name'] if hasattr(self.proxy, name): handler = getattr(self.proxy, name) handler() e...
An observer which sends the state change to the proxy.
entailment
def create_widget(self): """ Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. """ d = self.declaration style = d.style or '@style/Widget.DeviceDefault.PopupMenu' s...
Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent.
entailment
def init_widget(self): """ Set the listeners """ w = self.window d = self.declaration self.set_background_color(d.background_color) self.set_touchable(d.touchable) self.set_outside_touchable(d.outside_touchable) # Listen for events w.setOnDismissL...
Set the listeners
entailment
def init_layout(self): """ If a view is given show it """ super(AndroidPopupWindow, self).init_layout() #: Set the content for view in self.child_widgets(): self.window.setContentView(view) break #: Show it if needed d = self.de...
If a view is given show it
entailment
def child_added(self, child): """ Overwrite the content view """ view = child.widget if view is not None: self.window.setContentView(view)
Overwrite the content view
entailment
def destroy(self): """ A reimplemented destructor that cancels the dialog before destroying. """ super(AndroidPopupWindow, self).destroy() window = self.window if window: #: Clear the dismiss listener #: (or we get an error during the ca...
A reimplemented destructor that cancels the dialog before destroying.
entailment
def update(self): """ Update the PopupWindow if it is currently showing. This avoids calling update during initialization. """ if not self.showing: return d = self.declaration self.set_show(d.show)
Update the PopupWindow if it is currently showing. This avoids calling update during initialization.
entailment
def refresh_items(self): """ Refresh the items of the pattern. This method destroys the old items and creates and initializes the new items. It is overridden to NOT insert the children to the parent. The Fragment adapter handles this. """ items = [] if s...
Refresh the items of the pattern. This method destroys the old items and creates and initializes the new items. It is overridden to NOT insert the children to the parent. The Fragment adapter handles this.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidSwipeRefreshLayout, self).init_widget() d = self.declaration w = self.widget if not d.enabled: self.set_enabled(d.enabled) if d.indicator_background_color: self....
Initialize the underlying widget.
entailment
def load_module(self, mod): """ Load the extension using the load_dynamic method. """ try: return sys.modules[mod] except KeyError: pass lib = ExtensionImporter.extension_modules[mod] m = imp.load_dynamic(mod, lib) sys.modules[mod] = m ret...
Load the extension using the load_dynamic method.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = TabLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidTabLayout, self).init_widget() w = self.widget w.addOnTabSelectedListener(w.getId()) w.onTabSelected.connect(self.on_tab_selected) w.onTabUnselected.connect(self.on_tab_unselected)
Initialize the underlying widget.
entailment
def destroy(self): """ Destroy all tabs when destroyed """ super(AndroidTabLayout, self).destroy() if self.tabs: del self.tabs
Destroy all tabs when destroyed
entailment
def update_atom_members(old, new): """ Update an atom member """ old_keys = old.members().keys() new_keys = new.members().keys() for key in old_keys: old_obj = getattr(old, key) try: new_obj = getattr(new, key) if old_obj == new_obj: continue ...
Update an atom member
entailment
def update_class_by_type(old, new): """ Update declarative classes or fallback on default """ autoreload.update_class(old, new) if isinstance2(old, new, AtomMeta): update_atom_members(old, new)
Update declarative classes or fallback on default
entailment
def check(self, check_all=True, do_reload=True): """Check whether some modules need to be reloaded.""" with enaml.imports(): super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)
Check whether some modules need to be reloaded.
entailment
def update(self, old, new=None): """ Update given view declaration with new declaration Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative or None The new or reloaded view instance to that will be ...
Update given view declaration with new declaration Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative or None The new or reloaded view instance to that will be used to update the existing view....
entailment
def find_best_matching_node(self, new, old_nodes): """ Find the node that best matches the new node given the old nodes. If no good match exists return `None`. """ name = new.__class__.__name__ #: TODO: We should pick the BEST one from this list #: based on some "mat...
Find the node that best matches the new node given the old nodes. If no good match exists return `None`.
entailment
def update_attrs(self, old, new): """ Update any `attr` members. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for updating ...
Update any `attr` members. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for updating
entailment
def update_bindings(self, old, new): """ Update any enaml operator bindings. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for...
Update any enaml operator bindings. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for updating
entailment
def init_widget(self): """ Initialize the state of the toolkit widget. This method is called during the top-down pass, just after the 'create_widget()' method is called. This method should init the state of the widget. The child widgets will not yet be created. """ supe...
Initialize the state of the toolkit widget. This method is called during the top-down pass, just after the 'create_widget()' method is called. This method should init the state of the widget. The child widgets will not yet be created.
entailment
def destroy(self): """ A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None. """ widget = self.widget if widget is not None: del self.widget super(UiKitToolkitObject, self).destroy()
A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None.
entailment
def create_widget(self): """ Create the underlying label widget. """ d = self.declaration self.widget = View(self.get_context(), None, d.style)
Create the underlying label widget.
entailment
def init_widget(self): """ Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the ...
Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the properties that need to be overridd...
entailment
def get_declared_items(self): """ Get the members that were set in the enamldef block for this Declaration. Layout keys are grouped together until the end so as to avoid triggering multiple updates. Returns ------- result: List of (k,v) pairs that were defined fo...
Get the members that were set in the enamldef block for this Declaration. Layout keys are grouped together until the end so as to avoid triggering multiple updates. Returns ------- result: List of (k,v) pairs that were defined for this widget in enaml List of...
entailment
def on_key(self, view, key, event): """ Trigger the key event Parameters ---------- view: int The ID of the view that sent this event key: int The code of the key that was pressed data: bytes The msgpack encoded key event """ ...
Trigger the key event Parameters ---------- view: int The ID of the view that sent this event key: int The code of the key that was pressed data: bytes The msgpack encoded key event
entailment
def on_touch(self, view, event): """ Trigger the touch event Parameters ---------- view: int The ID of the view that sent this event data: bytes The msgpack encoded key event """ d = self.declaration r = {'event': event, 'result':...
Trigger the touch event Parameters ---------- view: int The ID of the view that sent this event data: bytes The msgpack encoded key event
entailment
def set_visible(self, visible): """ Set the visibility of the widget. """ v = View.VISIBILITY_VISIBLE if visible else View.VISIBILITY_GONE self.widget.setVisibility(v)
Set the visibility of the widget.
entailment
def set_layout(self, layout): """ Sets the LayoutParams of this widget. Since the available properties that may be set for the layout params depends on the parent, actual creation of the params is delegated to the parent Parameters ---------- ...
Sets the LayoutParams of this widget. Since the available properties that may be set for the layout params depends on the parent, actual creation of the params is delegated to the parent Parameters ---------- layout: Dict A dict of layo...
entailment
def create_layout_params(self, child, layout): """ Create the LayoutParams for a child with it's requested layout parameters. Subclasses should override this as needed to handle layout specific needs. Parameters ---------- child: AndroidView A view to...
Create the LayoutParams for a child with it's requested layout parameters. Subclasses should override this as needed to handle layout specific needs. Parameters ---------- child: AndroidView A view to create layout params for. layout: Dict ...
entailment
def apply_layout(self, child, layout): """ Apply a layout to a child. This sets the layout_params of the child which is later used during the `init_layout` pass. Subclasses should override this as needed to handle layout specific needs of the ViewGroup. Parameters ...
Apply a layout to a child. This sets the layout_params of the child which is later used during the `init_layout` pass. Subclasses should override this as needed to handle layout specific needs of the ViewGroup. Parameters ---------- child: AndroidView ...
entailment
def default(cls): """ Get the first available event loop implementation based on which packages are installed. """ with enamlnative.imports(): for impl in [ TornadoEventLoop, TwistedEventLoop, BuiltinEventLoop, ...
Get the first available event loop implementation based on which packages are installed.
entailment
def log_error(self, callback, error=None): """ Log the error that occurred when running the given callback. """ print("Uncaught error during callback: {}".format(callback)) print("Error: {}".format(error))
Log the error that occurred when running the given callback.
entailment
def deferred_call(self, callback, *args, **kwargs): """ We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor ...
We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor "wakes up"
entailment
def timed_call(self, ms, callback, *args, **kwargs): """ We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor ...
We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor "wakes up"
entailment
def init_widget(self): """ Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the properties ...
Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the properties that need to be overridden from def...
entailment