id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
1,900
edx/XBlock
xblock/runtime.py
Runtime.render_asides
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ aside_frag_fns = [] for aside in self.get_asides(block): aside_view_fn = aside...
python
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ aside_frag_fns = [] for aside in self.get_asides(block): aside_view_fn = aside...
[ "def", "render_asides", "(", "self", ",", "block", ",", "view_name", ",", "frag", ",", "context", ")", ":", "aside_frag_fns", "=", "[", "]", "for", "aside", "in", "self", ".", "get_asides", "(", "block", ")", ":", "aside_view_fn", "=", "aside", ".", "a...
Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering.
[ "Collect", "all", "of", "the", "asides", "add", "ons", "and", "format", "them", "into", "the", "frag", ".", "The", "frag", "already", "has", "the", "given", "block", "s", "rendering", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L982-L995
1,901
edx/XBlock
xblock/runtime.py
Runtime.layout_asides
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default met...
python
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default met...
[ "def", "layout_asides", "(", "self", ",", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", ":", "result", "=", "Fragment", "(", "frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "frag", ")", "for"...
Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default method appends the aside_frags after frag. If you override this, you must call wrap_aside...
[ "Execute", "and", "layout", "the", "aside_frags", "wrt", "the", "block", "s", "frag", ".", "Runtimes", "should", "feel", "free", "to", "override", "this", "method", "to", "control", "execution", "place", "and", "style", "the", "asides", "appropriately", "for",...
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L997-L1019
1,902
edx/XBlock
xblock/runtime.py
Runtime.handle
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle ...
python
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle ...
[ "def", "handle", "(", "self", ",", "block", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "handler", "=", "getattr", "(", "block", ",", "handler_name", ",", "None", ")", "if", "handler", "and", "getattr", "(", "handler", ",",...
Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, ...
[ "Handles", "any", "calls", "to", "the", "specified", "handler_name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1023-L1048
1,903
edx/XBlock
xblock/runtime.py
Runtime.service
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. X...
python
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. X...
[ "def", "service", "(", "self", ",", "block", ",", "service_name", ")", ":", "declaration", "=", "block", ".", "service_declaration", "(", "service_name", ")", "if", "declaration", "is", "None", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} was not reque...
Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request ser...
[ "Return", "a", "service", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1052-L1082
1,904
edx/XBlock
xblock/runtime.py
Runtime.querypath
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: di...
python
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: di...
[ "def", "querypath", "(", "self", ",", "block", ",", "path", ")", ":", "class", "BadPath", "(", "Exception", ")", ":", "\"\"\"Bad path exception thrown when path cannot be found.\"\"\"", "pass", "results", "=", "self", ".", "query", "(", "block", ")", "ROOT", ","...
An XPath-like interface to `query`.
[ "An", "XPath", "-", "like", "interface", "to", "query", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1095-L1156
1,905
edx/XBlock
xblock/runtime.py
ObjectAggregator._object_with_attr
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if has...
python
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if has...
[ "def", "_object_with_attr", "(", "self", ",", "name", ")", ":", "for", "obj", "in", "self", ".", "_objects", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "return", "obj", "raise", "AttributeError", "(", "\"No object has attribute {!r}\"", ".", ...
Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute
[ "Returns", "the", "first", "object", "that", "has", "the", "attribute", "name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1179-L1191
1,906
edx/XBlock
xblock/runtime.py
Mixologist.mix
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip th...
python
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip th...
[ "def", "mix", "(", "self", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'unmixed_class'", ")", ":", "base_class", "=", "cls", ".", "unmixed_class", "old_mixins", "=", "cls", ".", "__bases__", "[", "1", ":", "]", "# Skip the original unmixed cla...
Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class`
[ "Returns", "a", "subclass", "of", "cls", "mixed", "with", "self", ".", "mixins", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1219-L1253
1,907
edx/XBlock
xblock/runtime.py
RegexLexer.lex
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
python
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
[ "def", "lex", "(", "self", ",", "text", ")", ":", "for", "match", "in", "self", ".", "regex", ".", "finditer", "(", "text", ")", ":", "name", "=", "match", ".", "lastgroup", "yield", "(", "name", ",", "match", ".", "group", "(", "name", ")", ")" ...
Iterator that tokenizes `text` and yields up tokens as they are found
[ "Iterator", "that", "tokenizes", "text", "and", "yields", "up", "tokens", "as", "they", "are", "found" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1264-L1268
1,908
edx/XBlock
xblock/runtime.py
NullI18nService.strftime
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ format = self.STRFTIME_FORMATS.get(format + "_FORMAT", format) if six.PY2 and isinstance(format, six.text_type): format = format.encode("...
python
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ format = self.STRFTIME_FORMATS.get(format + "_FORMAT", format) if six.PY2 and isinstance(format, six.text_type): format = format.encode("...
[ "def", "strftime", "(", "self", ",", "dtime", ",", "format", ")", ":", "# pylint: disable=redefined-builtin", "format", "=", "self", ".", "STRFTIME_FORMATS", ".", "get", "(", "format", "+", "\"_FORMAT\"", ",", "format", ")", "if", "six", ".", "PY2", "and", ...
Locale-aware strftime, with format short-cuts.
[ "Locale", "-", "aware", "strftime", "with", "format", "short", "-", "cuts", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1288-L1298
1,909
edx/XBlock
xblock/runtime.py
NullI18nService.ugettext
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if s...
python
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if s...
[ "def", "ugettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ugettext", "else", ":", "return", "self", ".", "_translations", ".", "gettext" ]
Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "gettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1301-L1312
1,910
edx/XBlock
xblock/runtime.py
NullI18nService.ungettext
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member ...
python
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member ...
[ "def", "ungettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ungettext", "else", ":", "return", "self", ".", "_translations", ".", "ngettext" ]
Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "ngettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1315-L1326
1,911
edx/XBlock
xblock/reference/plugins.py
FSService.load
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(sco...
python
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(sco...
[ "def", "load", "(", "self", ",", "instance", ",", "xblock", ")", ":", "# TODO: Get xblock from context, once the plumbing is piped through", "if", "djpyfs", ":", "return", "djpyfs", ".", "get_filesystem", "(", "scope_key", "(", "instance", ",", "xblock", ")", ")", ...
Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped.
[ "Get", "the", "filesystem", "for", "the", "field", "specified", "in", "instance", "and", "the", "xblock", "in", "xblock", "It", "is", "locally", "scoped", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/reference/plugins.py#L190-L205
1,912
edx/XBlock
xblock/completable.py
CompletableXBlockMixin.emit_completion
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. ...
python
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. ...
[ "def", "emit_completion", "(", "self", ",", "completion_percent", ")", ":", "completion_mode", "=", "XBlockCompletionMode", ".", "get_mode", "(", "self", ")", "if", "not", "self", ".", "has_custom_completion", "or", "completion_mode", "!=", "XBlockCompletionMode", "...
Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion i...
[ "Emits", "completion", "event", "through", "Completion", "API", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/completable.py#L35-L65
1,913
edx/XBlock
xblock/field_data.py
FieldData.has
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: ...
python
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: ...
[ "def", "has", "(", "self", ",", "block", ",", "name", ")", ":", "try", ":", "self", ".", "get", "(", "block", ",", "name", ")", "return", "True", "except", "KeyError", ":", "return", "False" ]
Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str
[ "Return", "whether", "or", "not", "the", "field", "named", "name", "has", "a", "non", "-", "default", "value", "for", "the", "XBlock", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L69-L82
1,914
edx/XBlock
xblock/field_data.py
FieldData.set_many
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ ...
python
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ ...
[ "def", "set_many", "(", "self", ",", "block", ",", "update_dict", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "update_dict", ")", ":", "self", ".", "set", "(", "block", ",", "key", ",", "value", ")" ]
Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict
[ "Update", "many", "fields", "on", "an", "XBlock", "simultaneously", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L84-L94
1,915
edx/XBlock
xblock/exceptions.py
JsonHandlerError.get_response
def get_response(self, **kwargs): """ Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. """ return...
python
def get_response(self, **kwargs): """ Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. """ return...
[ "def", "get_response", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Response", "(", "json", ".", "dumps", "(", "{", "\"error\"", ":", "self", ".", "message", "}", ")", ",", "# pylint: disable=exception-message-attribute", "status_code", "=", "s...
Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response.
[ "Returns", "a", "Response", "object", "containing", "this", "object", "s", "status", "code", "and", "a", "JSON", "object", "containing", "the", "key", "error", "with", "the", "value", "of", "this", "object", "s", "error", "message", "in", "the", "body", "....
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/exceptions.py#L126-L139
1,916
edx/XBlock
xblock/mixins.py
HandlersMixin.json_handler
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function ...
python
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function ...
[ "def", "json_handler", "(", "cls", ",", "func", ")", ":", "@", "cls", ".", "handler", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "request", ",", "suffix", "=", "''", ")", ":", "\"\"\"The wrapper function `json_h...
Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the resp...
[ "Wrap", "a", "handler", "to", "consume", "and", "produce", "JSON", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L40-L75
1,917
edx/XBlock
xblock/mixins.py
HandlersMixin.handle
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
python
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
[ "def", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "return", "self", ".", "runtime", ".", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", ")" ]
Handle `request` with this block's runtime.
[ "Handle", "request", "with", "this", "block", "s", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L87-L89
1,918
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin._combined_services
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to wal...
python
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to wal...
[ "def", "_combined_services", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "# The class declares what services it desires. To deal with subclasses,", "# especially mixins, properly, we have to walk up the inheritance", "# hierarchy, and combine all the declared services into one dict...
A dictionary that collects all _services_requested by all ancestors of this XBlock class.
[ "A", "dictionary", "that", "collects", "all", "_services_requested", "by", "all", "ancestors", "of", "this", "XBlock", "class", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L104-L114
1,919
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.needs
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_nam...
python
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_nam...
[ "def", "needs", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "...
A class decorator to indicate that an XBlock class needs particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "needs", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L127-L133
1,920
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.wants
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_nam...
python
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_nam...
[ "def", "wants", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "...
A class decorator to indicate that an XBlock class wants particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "wants", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L136-L142
1,921
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_parent
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" if not self.has_cached_parent: if self.parent is not None: self._parent_block = self.runtime.get_block(self.parent) else: self._parent_block = None ...
python
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" if not self.has_cached_parent: if self.parent is not None: self._parent_block = self.runtime.get_block(self.parent) else: self._parent_block = None ...
[ "def", "get_parent", "(", "self", ")", ":", "if", "not", "self", ".", "has_cached_parent", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "self", ".", "_parent_block", "=", "self", ".", "runtime", ".", "get_block", "(", "self", ".", "paren...
Return the parent block of this block, or None if there isn't one.
[ "Return", "the", "parent", "block", "of", "this", "block", "or", "None", "if", "there", "isn", "t", "one", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L373-L381
1,922
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_child
def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] child_block = self.runtime.get_block(usage_id, for_parent=self) self._child_cache[usage_id] = child_block return chi...
python
def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] child_block = self.runtime.get_block(usage_id, for_parent=self) self._child_cache[usage_id] = child_block return chi...
[ "def", "get_child", "(", "self", ",", "usage_id", ")", ":", "if", "usage_id", "in", "self", ".", "_child_cache", ":", "return", "self", ".", "_child_cache", "[", "usage_id", "]", "child_block", "=", "self", ".", "runtime", ".", "get_block", "(", "usage_id"...
Return the child identified by ``usage_id``.
[ "Return", "the", "child", "identified", "by", "usage_id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L388-L395
1,923
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_children
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ if not self.has_children: return [] return [ self.get_child(usage_id) for usage_id in self.children if usage_id...
python
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ if not self.has_children: return [] return [ self.get_child(usage_id) for usage_id in self.children if usage_id...
[ "def", "get_children", "(", "self", ",", "usage_id_filter", "=", "None", ")", ":", "if", "not", "self", ".", "has_children", ":", "return", "[", "]", "return", "[", "self", ".", "get_child", "(", "usage_id", ")", "for", "usage_id", "in", "self", ".", "...
Return instantiated XBlocks for each of this blocks ``children``.
[ "Return", "instantiated", "XBlocks", "for", "each", "of", "this", "blocks", "children", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L397-L408
1,924
edx/XBlock
xblock/mixins.py
HierarchyMixin.add_children_to_node
def add_children_to_node(self, node): """ Add children to etree.Element `node`. """ if self.has_children: for child_id in self.children: child = self.runtime.get_block(child_id) self.runtime.add_block_as_child_node(child, node)
python
def add_children_to_node(self, node): """ Add children to etree.Element `node`. """ if self.has_children: for child_id in self.children: child = self.runtime.get_block(child_id) self.runtime.add_block_as_child_node(child, node)
[ "def", "add_children_to_node", "(", "self", ",", "node", ")", ":", "if", "self", ".", "has_children", ":", "for", "child_id", "in", "self", ".", "children", ":", "child", "=", "self", ".", "runtime", ".", "get_block", "(", "child_id", ")", "self", ".", ...
Add children to etree.Element `node`.
[ "Add", "children", "to", "etree", ".", "Element", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L416-L423
1,925
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.parse_xml
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. k...
python
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. k...
[ "def", "parse_xml", "(", "cls", ",", "node", ",", "runtime", ",", "keys", ",", "id_generator", ")", ":", "block", "=", "runtime", ".", "construct_xblock_from_class", "(", "cls", ",", "keys", ")", "# The base implementation: child nodes become child blocks.", "# Or f...
Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block ...
[ "Use", "node", "to", "construct", "a", "new", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L432-L477
1,926
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.add_xml_to_node
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes...
python
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes...
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "# pylint: disable=E1101", "# Set node.tag based on our class name.", "node", ".", "tag", "=", "self", ".", "xml_element_name", "(", ")", "node", ".", "set", "(", "'xblock-family'", ",", "self", ".", ...
For exporting, set data on `node` from ourselves.
[ "For", "exporting", "set", "data", "on", "node", "from", "ourselves", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L479-L498
1,927
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._set_field_if_present
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" if name in block.fields: value = (block.fields[name]).from_string(value) if "none" in attrs and attrs["none"] == "true": setattr(block, name, No...
python
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" if name in block.fields: value = (block.fields[name]).from_string(value) if "none" in attrs and attrs["none"] == "true": setattr(block, name, No...
[ "def", "_set_field_if_present", "(", "cls", ",", "block", ",", "name", ",", "value", ",", "attrs", ")", ":", "if", "name", "in", "block", ".", "fields", ":", "value", "=", "(", "block", ".", "fields", "[", "name", "]", ")", ".", "from_string", "(", ...
Sets the field block.name, if block have such a field.
[ "Sets", "the", "field", "block", ".", "name", "if", "block", "have", "such", "a", "field", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L513-L522
1,928
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._add_field
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_va...
python
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_va...
[ "def", "_add_field", "(", "self", ",", "node", ",", "field_name", ",", "field", ")", ":", "value", "=", "field", ".", "to_string", "(", "field", ".", "read_from", "(", "self", ")", ")", "text_value", "=", "\"\"", "if", "value", "is", "None", "else", ...
Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node.
[ "Add", "xml", "representation", "of", "field", "to", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L524-L549
1,929
edx/XBlock
xblock/mixins.py
ViewsMixin.supports
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ ...
python
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ ...
[ "def", "supports", "(", "cls", ",", "*", "functionalities", ")", ":", "def", "_decorator", "(", "view", ")", ":", "\"\"\"\n Internal decorator that updates the given view's list of supported\n functionalities.\n \"\"\"", "# pylint: disable=protected-a...
A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device".
[ "A", "view", "decorator", "to", "indicate", "that", "an", "xBlock", "view", "has", "support", "for", "the", "given", "functionalities", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L572-L592
1,930
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin.rescore
def rescore(self, only_if_higher): """ Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed th...
python
def rescore(self, only_if_higher): """ Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed th...
[ "def", "rescore", "(", "self", ",", "only_if_higher", ")", ":", "_", "=", "self", ".", "runtime", ".", "service", "(", "self", ",", "'i18n'", ")", ".", "ugettext", "if", "not", "self", ".", "allows_rescore", "(", ")", ":", "raise", "TypeError", "(", ...
Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self...
[ "Calculate", "a", "new", "raw", "score", "and", "save", "it", "to", "the", "block", ".", "If", "only_if_higher", "is", "True", "and", "the", "score", "didn", "t", "improve", "keep", "the", "existing", "score", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L34-L55
1,931
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin._publish_grade
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'gra...
python
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'gra...
[ "def", "_publish_grade", "(", "self", ",", "score", ",", "only_if_higher", "=", "None", ")", ":", "grade_dict", "=", "{", "'value'", ":", "score", ".", "raw_earned", ",", "'max_value'", ":", "score", ".", "raw_possible", ",", "'only_if_higher'", ":", "only_i...
Publish a grade to the runtime.
[ "Publish", "a", "grade", "to", "the", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L108-L117
1,932
edx/XBlock
xblock/fields.py
scope_key
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posi...
python
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posi...
[ "def", "scope_key", "(", "instance", ",", "xblock", ")", ":", "scope_key_dict", "=", "{", "}", "scope_key_dict", "[", "'name'", "]", "=", "instance", ".", "name", "if", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "NONE", "or", "instanc...
Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd lik...
[ "Generate", "a", "unique", "key", "for", "a", "scope", "that", "can", "be", "used", "as", "a", "filename", "in", "a", "URL", "or", "in", "a", "KVS", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L1045-L1138
1,933
edx/XBlock
xblock/fields.py
Field.default
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
python
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
[ "def", "default", "(", "self", ")", ":", "if", "self", ".", "MUTABLE", ":", "return", "copy", ".", "deepcopy", "(", "self", ".", "_default", ")", "else", ":", "return", "self", ".", "_default" ]
Returns the static value that this defaults to.
[ "Returns", "the", "static", "value", "that", "this", "defaults", "to", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L342-L347
1,934
edx/XBlock
xblock/fields.py
Field._set_cached_value
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
python
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
[ "def", "_set_cached_value", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "if", "not", "hasattr", "(", "xblock", ",", "'_field_data_cache'", ")", ":", "xblock", ".", "_field_data_cache", "=", "{", "}", "xblock", ".", ...
Store a value in the xblock's cache, creating the cache if necessary.
[ "Store", "a", "value", "in", "the", "xblock", "s", "cache", "creating", "the", "cache", "if", "necessary", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L404-L409
1,935
edx/XBlock
xblock/fields.py
Field._del_cached_value
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
python
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
[ "def", "_del_cached_value", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "if", "hasattr", "(", "xblock", ",", "'_field_data_cache'", ")", "and", "self", ".", "name", "in", "xblock", ".", "_field_data_cache", ":", "del", "xblock", "...
Remove a value from the xblock's cache, if the cache exists.
[ "Remove", "a", "value", "from", "the", "xblock", "s", "cache", "if", "the", "cache", "exists", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L411-L415
1,936
edx/XBlock
xblock/fields.py
Field._mark_dirty
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xb...
python
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xb...
[ "def", "_mark_dirty", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "# Deep copy the value being marked as dirty, so that there", "# is a baseline to check against when saving later", "if", "self", "not", "in", "xblock", ".", "_dirty_...
Set this field to dirty on the xblock.
[ "Set", "this", "field", "to", "dirty", "on", "the", "xblock", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L417-L424
1,937
edx/XBlock
xblock/fields.py
Field._check_or_enforce_type
def _check_or_enforce_type(self, value): """ Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: w...
python
def _check_or_enforce_type(self, value): """ Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: w...
[ "def", "_check_or_enforce_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_enable_enforce_type", ":", "return", "self", ".", "enforce_type", "(", "value", ")", "try", ":", "new_value", "=", "self", ".", "enforce_type", "(", "value", ")", "e...
Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) ...
[ "Depending", "on", "whether", "enforce_type", "is", "enabled", "call", "self", ".", "enforce_type", "and", "return", "the", "result", "or", "call", "it", "and", "trigger", "a", "silent", "warning", "if", "the", "result", "is", "different", "or", "a", "Traceb...
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L443-L472
1,938
edx/XBlock
xblock/fields.py
Field._calculate_unique_id
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.s...
python
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.s...
[ "def", "_calculate_unique_id", "(", "self", ",", "xblock", ")", ":", "key", "=", "scope_key", "(", "self", ",", "xblock", ")", "return", "hashlib", ".", "sha1", "(", "key", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope.
[ "Provide", "a", "default", "value", "for", "fields", "with", "default", "=", "UNIQUE_ID", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L474-L482
1,939
edx/XBlock
xblock/fields.py
Field._get_default_value_to_cache
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: ...
python
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: ...
[ "def", "_get_default_value_to_cache", "(", "self", ",", "xblock", ")", ":", "try", ":", "# pylint: disable=protected-access", "return", "self", ".", "from_json", "(", "xblock", ".", "_field_data", ".", "default", "(", "xblock", ",", "self", ".", "name", ")", "...
Perform special logic to provide a field's default value for caching.
[ "Perform", "special", "logic", "to", "provide", "a", "field", "s", "default", "value", "for", "caching", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L484-L495
1,940
edx/XBlock
xblock/fields.py
Field._warn_deprecated_outside_JSONField
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ if not isinstance(self, JSONField) and not self.warned: warnings....
python
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ if not isinstance(self, JSONField) and not self.warned: warnings....
[ "def", "_warn_deprecated_outside_JSONField", "(", "self", ")", ":", "# pylint: disable=invalid-name", "if", "not", "isinstance", "(", "self", ",", "JSONField", ")", "and", "not", "self", ".", "warned", ":", "warnings", ".", "warn", "(", "\"Deprecated. JSONifiable fi...
Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class.
[ "Certain", "methods", "will", "be", "moved", "to", "JSONField", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L589-L601
1,941
edx/XBlock
xblock/fields.py
Field.to_string
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ...
python
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ...
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "value", "=", "json", ".", "dumps", "(", "self", ".", "to_json", "(", "value", ")", ",", "indent", "=", "2", ",", "sort_keys", "=", "T...
Return a JSON serialized string representation of the value.
[ "Return", "a", "JSON", "serialized", "string", "representation", "of", "the", "value", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L624-L635
1,942
edx/XBlock
xblock/fields.py
Field.from_string
def from_string(self, serialized): """ Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.) """ self._warn_deprecated_outside_JSONField() value = yaml.safe_load(serialized) return...
python
def from_string(self, serialized): """ Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.) """ self._warn_deprecated_outside_JSONField() value = yaml.safe_load(serialized) return...
[ "def", "from_string", "(", "self", ",", "serialized", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "value", "=", "yaml", ".", "safe_load", "(", "serialized", ")", "return", "self", ".", "enforce_type", "(", "value", ")" ]
Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.)
[ "Returns", "a", "native", "value", "from", "a", "YAML", "serialized", "string", "representation", ".", "Since", "YAML", "is", "a", "superset", "of", "JSON", "this", "is", "the", "inverse", "of", "to_string", ".", ")" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L637-L644
1,943
edx/XBlock
xblock/fields.py
Field.read_json
def read_json(self, xblock): """ Retrieve the serialized value for this field from the specified xblock """ self._warn_deprecated_outside_JSONField() return self.to_json(self.read_from(xblock))
python
def read_json(self, xblock): """ Retrieve the serialized value for this field from the specified xblock """ self._warn_deprecated_outside_JSONField() return self.to_json(self.read_from(xblock))
[ "def", "read_json", "(", "self", ",", "xblock", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "return", "self", ".", "to_json", "(", "self", ".", "read_from", "(", "xblock", ")", ")" ]
Retrieve the serialized value for this field from the specified xblock
[ "Retrieve", "the", "serialized", "value", "for", "this", "field", "from", "the", "specified", "xblock" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L664-L669
1,944
edx/XBlock
xblock/fields.py
Field.is_set_on
def is_set_on(self, xblock): """ Return whether this field has a non-default value on the supplied xblock """ # pylint: disable=protected-access return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name)
python
def is_set_on(self, xblock): """ Return whether this field has a non-default value on the supplied xblock """ # pylint: disable=protected-access return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name)
[ "def", "is_set_on", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "return", "self", ".", "_is_dirty", "(", "xblock", ")", "or", "xblock", ".", "_field_data", ".", "has", "(", "xblock", ",", "self", ".", "name", ")" ]
Return whether this field has a non-default value on the supplied xblock
[ "Return", "whether", "this", "field", "has", "a", "non", "-", "default", "value", "on", "the", "supplied", "xblock" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L683-L688
1,945
edx/XBlock
xblock/fields.py
String.to_string
def to_string(self, value): """String gets serialized and deserialized without quote marks.""" if isinstance(value, six.binary_type): value = value.decode('utf-8') return self.to_json(value)
python
def to_string(self, value): """String gets serialized and deserialized without quote marks.""" if isinstance(value, six.binary_type): value = value.decode('utf-8') return self.to_json(value)
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "return", "self", ".", "to_json", "(", "value", ")" ]
String gets serialized and deserialized without quote marks.
[ "String", "gets", "serialized", "and", "deserialized", "without", "quote", "marks", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L904-L908
1,946
edx/XBlock
xblock/fields.py
DateTime.from_json
def from_json(self, value): """ Parse the date from an ISO-formatted date string, or None. """ if value is None: return None if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): # P...
python
def from_json(self, value): """ Parse the date from an ISO-formatted date string, or None. """ if value is None: return None if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): # P...
[ "def", "from_json", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "if", ...
Parse the date from an ISO-formatted date string, or None.
[ "Parse", "the", "date", "from", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L954-L981
1,947
edx/XBlock
xblock/fields.py
DateTime.to_json
def to_json(self, value): """ Serialize the date as an ISO-formatted date string, or None. """ if isinstance(value, datetime.datetime): return value.strftime(self.DATETIME_FORMAT) if value is None: return None raise TypeError("Value stored must be ...
python
def to_json(self, value): """ Serialize the date as an ISO-formatted date string, or None. """ if isinstance(value, datetime.datetime): return value.strftime(self.DATETIME_FORMAT) if value is None: return None raise TypeError("Value stored must be ...
[ "def", "to_json", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "strftime", "(", "self", ".", "DATETIME_FORMAT", ")", "if", "value", "is", "None", ":", "return...
Serialize the date as an ISO-formatted date string, or None.
[ "Serialize", "the", "date", "as", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L983-L991
1,948
edx/XBlock
xblock/run_script.py
run_script
def run_script(pycode): """Run the Python in `pycode`, and return a dict of the resulting globals.""" # Fix up the whitespace in pycode. if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) # execute it. globs = {} six.exec_(pycode, globs, g...
python
def run_script(pycode): """Run the Python in `pycode`, and return a dict of the resulting globals.""" # Fix up the whitespace in pycode. if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) # execute it. globs = {} six.exec_(pycode, globs, g...
[ "def", "run_script", "(", "pycode", ")", ":", "# Fix up the whitespace in pycode.", "if", "pycode", "[", "0", "]", "==", "\"\\n\"", ":", "pycode", "=", "pycode", "[", "1", ":", "]", "pycode", ".", "rstrip", "(", ")", "pycode", "=", "textwrap", ".", "dede...
Run the Python in `pycode`, and return a dict of the resulting globals.
[ "Run", "the", "Python", "in", "pycode", "and", "return", "a", "dict", "of", "the", "resulting", "globals", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/run_script.py#L12-L24
1,949
edx/XBlock
xblock/core.py
SharedBlockBase.open_local_resource
def open_local_resource(cls, uri): """ Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back ...
python
def open_local_resource(cls, uri): """ Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back ...
[ "def", "open_local_resource", "(", "cls", ",", "uri", ")", ":", "if", "isinstance", "(", "uri", ",", "six", ".", "binary_type", ")", ":", "uri", "=", "uri", ".", "decode", "(", "'utf-8'", ")", "# If no resources_dir is set, then this XBlock cannot serve local reso...
Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and retu...
[ "Open", "a", "local", "resource", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L79-L115
1,950
edx/XBlock
xblock/core.py
XBlock._class_tags
def _class_tags(cls): # pylint: disable=no-self-argument """ Collect the tags from all base classes. """ class_tags = set() for base in cls.mro()[1:]: # pylint: disable=no-member class_tags.update(getattr(base, '_class_tags', set())) return class_tags
python
def _class_tags(cls): # pylint: disable=no-self-argument """ Collect the tags from all base classes. """ class_tags = set() for base in cls.mro()[1:]: # pylint: disable=no-member class_tags.update(getattr(base, '_class_tags', set())) return class_tags
[ "def", "_class_tags", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "class_tags", "=", "set", "(", ")", "for", "base", "in", "cls", ".", "mro", "(", ")", "[", "1", ":", "]", ":", "# pylint: disable=no-member", "class_tags", ".", "update", "(", ...
Collect the tags from all base classes.
[ "Collect", "the", "tags", "from", "all", "base", "classes", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L135-L144
1,951
edx/XBlock
xblock/core.py
XBlock.tag
def tag(tags): """Returns a function that adds the words in `tags` as class tags to this class.""" def dec(cls): """Add the words in `tags` as class tags to this class.""" # Add in this class's tags cls._class_tags.update(tags.replace(",", " ").split()) # pylint: dis...
python
def tag(tags): """Returns a function that adds the words in `tags` as class tags to this class.""" def dec(cls): """Add the words in `tags` as class tags to this class.""" # Add in this class's tags cls._class_tags.update(tags.replace(",", " ").split()) # pylint: dis...
[ "def", "tag", "(", "tags", ")", ":", "def", "dec", "(", "cls", ")", ":", "\"\"\"Add the words in `tags` as class tags to this class.\"\"\"", "# Add in this class's tags", "cls", ".", "_class_tags", ".", "update", "(", "tags", ".", "replace", "(", "\",\"", ",", "\"...
Returns a function that adds the words in `tags` as class tags to this class.
[ "Returns", "a", "function", "that", "adds", "the", "words", "in", "tags", "as", "class", "tags", "to", "this", "class", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L147-L154
1,952
edx/XBlock
xblock/core.py
XBlock.load_tagged_classes
def load_tagged_classes(cls, tag, fail_silently=True): """ Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it...
python
def load_tagged_classes(cls, tag, fail_silently=True): """ Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it...
[ "def", "load_tagged_classes", "(", "cls", ",", "tag", ",", "fail_silently", "=", "True", ")", ":", "# Allow this method to access the `_class_tags`", "# pylint: disable=W0212", "for", "name", ",", "class_", "in", "cls", ".", "load_classes", "(", "fail_silently", ")", ...
Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depend...
[ "Produce", "a", "sequence", "of", "all", "XBlock", "classes", "tagged", "with", "tag", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L157-L174
1,953
edx/XBlock
xblock/core.py
XBlock.render
def render(self, view, context=None): """Render `view` with this block's runtime and the supplied `context`""" return self.runtime.render(self, view, context)
python
def render(self, view, context=None): """Render `view` with this block's runtime and the supplied `context`""" return self.runtime.render(self, view, context)
[ "def", "render", "(", "self", ",", "view", ",", "context", "=", "None", ")", ":", "return", "self", ".", "runtime", ".", "render", "(", "self", ",", "view", ",", "context", ")" ]
Render `view` with this block's runtime and the supplied `context`
[ "Render", "view", "with", "this", "block", "s", "runtime", "and", "the", "supplied", "context" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L200-L202
1,954
edx/XBlock
xblock/core.py
XBlock.add_xml_to_node
def add_xml_to_node(self, node): """ For exporting, set data on etree.Element `node`. """ super(XBlock, self).add_xml_to_node(node) # Add children for each of our children. self.add_children_to_node(node)
python
def add_xml_to_node(self, node): """ For exporting, set data on etree.Element `node`. """ super(XBlock, self).add_xml_to_node(node) # Add children for each of our children. self.add_children_to_node(node)
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "super", "(", "XBlock", ",", "self", ")", ".", "add_xml_to_node", "(", "node", ")", "# Add children for each of our children.", "self", ".", "add_children_to_node", "(", "node", ")" ]
For exporting, set data on etree.Element `node`.
[ "For", "exporting", "set", "data", "on", "etree", ".", "Element", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L222-L228
1,955
edx/XBlock
xblock/core.py
XBlockAside.aside_for
def aside_for(cls, view_name): """ A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... ...
python
def aside_for(cls, view_name): """ A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... ...
[ "def", "aside_for", "(", "cls", ",", "view_name", ")", ":", "# pylint: disable=protected-access", "def", "_decorator", "(", "func", ")", ":", "# pylint: disable=missing-docstring", "if", "not", "hasattr", "(", "func", ",", "'_aside_for'", ")", ":", "func", ".", ...
A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... return Fragment(...)
[ "A", "decorator", "to", "indicate", "a", "function", "is", "the", "aside", "view", "for", "the", "given", "view_name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L239-L257
1,956
edx/XBlock
xblock/core.py
XBlockAside.aside_view_declaration
def aside_view_declaration(self, view_name): """ Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: ...
python
def aside_view_declaration(self, view_name): """ Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: ...
[ "def", "aside_view_declaration", "(", "self", ",", "view_name", ")", ":", "if", "view_name", "in", "self", ".", "_combined_asides", ":", "# pylint: disable=unsupported-membership-test", "return", "getattr", "(", "self", ",", "self", ".", "_combined_asides", "[", "vi...
Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: view_name (string): the name of the view requested. ...
[ "Find", "and", "return", "a", "function", "object", "if", "one", "is", "an", "aside_view", "for", "the", "given", "view_name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L282-L298
1,957
edx/XBlock
xblock/core.py
XBlockAside.needs_serialization
def needs_serialization(self): """ Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all. """ return any(field.is_set_on(self) for field in six.itervalues(se...
python
def needs_serialization(self): """ Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all. """ return any(field.is_set_on(self) for field in six.itervalues(se...
[ "def", "needs_serialization", "(", "self", ")", ":", "return", "any", "(", "field", ".", "is_set_on", "(", "self", ")", "for", "field", "in", "six", ".", "itervalues", "(", "self", ".", "fields", ")", ")" ]
Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all.
[ "Return", "True", "if", "the", "aside", "has", "any", "data", "to", "serialize", "to", "XML", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L300-L307
1,958
edx/XBlock
xblock/validation.py
Validation.add
def add(self, message): """ Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages. """ if not isinstance(message, ValidationMessage): raise TypeError("Argument mus...
python
def add(self, message): """ Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages. """ if not isinstance(message, ValidationMessage): raise TypeError("Argument mus...
[ "def", "add", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "ValidationMessage", ")", ":", "raise", "TypeError", "(", "\"Argument must of type ValidationMessage\"", ")", "self", ".", "messages", ".", "append", "(", "mes...
Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages.
[ "Add", "a", "new", "validation", "message", "to", "this", "instance", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L87-L96
1,959
edx/XBlock
xblock/validation.py
Validation.add_messages
def add_messages(self, validation): """ Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages. """ if not isinstance(va...
python
def add_messages(self, validation): """ Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages. """ if not isinstance(va...
[ "def", "add_messages", "(", "self", ",", "validation", ")", ":", "if", "not", "isinstance", "(", "validation", ",", "Validation", ")", ":", "raise", "TypeError", "(", "\"Argument must be of type Validation\"", ")", "self", ".", "messages", ".", "extend", "(", ...
Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages.
[ "Adds", "all", "the", "messages", "in", "the", "specified", "Validation", "object", "to", "this", "instance", "s", "messages", "array", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L98-L109
1,960
edx/XBlock
xblock/validation.py
Validation.to_json
def to_json(self): """ Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable. """ return { "xblock_id": six.text_type(self.xblock_id), "messages": [message.to_json() for message in self.m...
python
def to_json(self): """ Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable. """ return { "xblock_id": six.text_type(self.xblock_id), "messages": [message.to_json() for message in self.m...
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "\"xblock_id\"", ":", "six", ".", "text_type", "(", "self", ".", "xblock_id", ")", ",", "\"messages\"", ":", "[", "message", ".", "to_json", "(", ")", "for", "message", "in", "self", ".", "message...
Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable.
[ "Convert", "to", "a", "json", "-", "serializable", "representation", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122
1,961
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
recarray_view
def recarray_view(qimage): """Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexin...
python
def recarray_view(qimage): """Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexin...
[ "def", "recarray_view", "(", "qimage", ")", ":", "raw", "=", "_qimage_or_filename_view", "(", "qimage", ")", "if", "raw", ".", "itemsize", "!=", "4", ":", "raise", "ValueError", "(", "\"For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Prem...
Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexing or via attribute lookup (through...
[ "Returns", "recarray_", "view", "of", "a", "given", "32", "-", "bit", "color", "QImage_", "s", "memory", "." ]
023f3c67f90e646ce2fd80418fed85b9c7660bfc
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L137-L173
1,962
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
gray2qimage
def gray2qimage(gray, normalize = False): """Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, ...
python
def gray2qimage(gray, normalize = False): """Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, ...
[ "def", "gray2qimage", "(", "gray", ",", "normalize", "=", "False", ")", ":", "if", "_np", ".", "ndim", "(", "gray", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"gray2QImage can only convert 2D arrays\"", "+", "\" (try using array2qimage)\"", "if", "_np", ...
Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, nmax): scale & clip image values from nmin....
[ "Convert", "the", "2D", "numpy", "array", "gray", "into", "a", "8", "-", "bit", "indexed", "QImage_", "with", "a", "gray", "colormap", ".", "The", "first", "dimension", "represents", "the", "vertical", "image", "axis", "." ]
023f3c67f90e646ce2fd80418fed85b9c7660bfc
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L203-L258
1,963
ampl/amplpy
amplpy/ampl.py
AMPL.getVariable
def getVariable(self, name): """ Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist. """ return lock_and_call( lambda: Variable(self....
python
def getVariable(self, name): """ Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist. """ return lock_and_call( lambda: Variable(self....
[ "def", "getVariable", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Variable", "(", "self", ".", "_impl", ".", "getVariable", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist.
[ "Get", "the", "variable", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L175-L188
1,964
ampl/amplpy
amplpy/ampl.py
AMPL.getConstraint
def getConstraint(self, name): """ Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist. """ return lock_and_call( lambda: Constr...
python
def getConstraint(self, name): """ Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist. """ return lock_and_call( lambda: Constr...
[ "def", "getConstraint", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Constraint", "(", "self", ".", "_impl", ".", "getConstraint", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist.
[ "Get", "the", "constraint", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L190-L203
1,965
ampl/amplpy
amplpy/ampl.py
AMPL.getObjective
def getObjective(self, name): """ Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist. """ return lock_and_call( lambda: Objectiv...
python
def getObjective(self, name): """ Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist. """ return lock_and_call( lambda: Objectiv...
[ "def", "getObjective", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Objective", "(", "self", ".", "_impl", ".", "getObjective", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist.
[ "Get", "the", "objective", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L205-L218
1,966
ampl/amplpy
amplpy/ampl.py
AMPL.getSet
def getSet(self, name): """ Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist. """ return lock_and_call( lambda: Set(self._impl.getSet(name)), ...
python
def getSet(self, name): """ Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist. """ return lock_and_call( lambda: Set(self._impl.getSet(name)), ...
[ "def", "getSet", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Set", "(", "self", ".", "_impl", ".", "getSet", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist.
[ "Get", "the", "set", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L220-L233
1,967
ampl/amplpy
amplpy/ampl.py
AMPL.getParameter
def getParameter(self, name): """ Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist. """ return lock_and_call( lambda: Parameter(...
python
def getParameter(self, name): """ Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist. """ return lock_and_call( lambda: Parameter(...
[ "def", "getParameter", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Parameter", "(", "self", ".", "_impl", ".", "getParameter", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist.
[ "Get", "the", "parameter", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L235-L248
1,968
ampl/amplpy
amplpy/ampl.py
AMPL.eval
def eval(self, amplstatements, **kwargs): """ Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities wil...
python
def eval(self, amplstatements, **kwargs): """ Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities wil...
[ "def", "eval", "(", "self", ",", "amplstatements", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ",", "*", "*", "kwar...
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) Th...
[ "Parses", "AMPL", "code", "and", "evaluates", "it", "as", "a", "possibly", "empty", "sequence", "of", "AMPL", "declarations", "and", "statements", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L250-L282
1,969
ampl/amplpy
amplpy/ampl.py
AMPL.isBusy
def isBusy(self): """ Returns true if the underlying engine is doing an async operation. """ # return self._impl.isBusy() if self._lock.acquire(False): self._lock.release() return False else: return True
python
def isBusy(self): """ Returns true if the underlying engine is doing an async operation. """ # return self._impl.isBusy() if self._lock.acquire(False): self._lock.release() return False else: return True
[ "def", "isBusy", "(", "self", ")", ":", "# return self._impl.isBusy()", "if", "self", ".", "_lock", ".", "acquire", "(", "False", ")", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "False", "else", ":", "return", "True" ]
Returns true if the underlying engine is doing an async operation.
[ "Returns", "true", "if", "the", "underlying", "engine", "is", "doing", "an", "async", "operation", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L326-L335
1,970
ampl/amplpy
amplpy/ampl.py
AMPL.evalAsync
def evalAsync(self, amplstatements, callback, **kwargs): """ Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the state...
python
def evalAsync(self, amplstatements, callback, **kwargs): """ Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the state...
[ "def", "evalAsync", "(", "self", ",", "amplstatements", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ...
Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the statement has been interpreted. Raises: RuntimeError:...
[ "Interpret", "the", "given", "AMPL", "statement", "asynchronously", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L410-L440
1,971
ampl/amplpy
amplpy/ampl.py
AMPL.solveAsync
def solveAsync(self, callback): """ Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done. """ def async_call(): self._lock.acquire() try: self._impl.solve() except Ex...
python
def solveAsync(self, callback): """ Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done. """ def async_call(): self._lock.acquire() try: self._impl.solve() except Ex...
[ "def", "solveAsync", "(", "self", ",", "callback", ")", ":", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "solve", "(", ")", "except", "Exception", ":", "self", ".", "_lo...
Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done.
[ "Solve", "the", "current", "model", "asynchronously", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L442-L459
1,972
ampl/amplpy
amplpy/ampl.py
AMPL.setOption
def setOption(self, name, value): """ Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not vali...
python
def setOption(self, name, value): """ Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not vali...
[ "def", "setOption", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setBoolOption", "(", "name", ",", "value", ")", ",", "self...
Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not valid. TypeError: if the value has an invalid...
[ "Set", "an", "AMPL", "option", "to", "a", "specified", "value", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L500-L535
1,973
ampl/amplpy
amplpy/ampl.py
AMPL.getOption
def getOption(self, name): """ Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not val...
python
def getOption(self, name): """ Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not val...
[ "def", "getOption", "(", "self", ",", "name", ")", ":", "try", ":", "value", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getOption", "(", "name", ")", ".", "value", "(", ")", ",", "self", ".", "_lock", ")", "except", "Runt...
Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not valid.
[ "Get", "the", "current", "value", "of", "the", "specified", "option", ".", "If", "the", "option", "does", "not", "exist", "returns", "None", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L537-L565
1,974
ampl/amplpy
amplpy/ampl.py
AMPL.getValue
def getValue(self, scalarExpression): """ Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression. ...
python
def getValue(self, scalarExpression): """ Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression. ...
[ "def", "getValue", "(", "self", ",", "scalarExpression", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Utils", ".", "castVariant", "(", "self", ".", "_impl", ".", "getValue", "(", "scalarExpression", ")", ")", ",", "self", ".", "_lock", ")" ]
Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression.
[ "Get", "a", "scalar", "value", "from", "the", "underlying", "AMPL", "interpreter", "as", "a", "double", "or", "a", "string", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L612-L627
1,975
ampl/amplpy
amplpy/ampl.py
AMPL.setData
def setData(self, data, setName=None): """ Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices val...
python
def setData(self, data, setName=None): """ Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices val...
[ "def", "setData", "(", "self", ",", "data", ",", "setName", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "DataFrame", ")", ":", "if", "pd", "is", "not", "None", "and", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", "...
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. ...
[ "Assign", "the", "data", "in", "the", "dataframe", "to", "the", "AMPL", "entities", "with", "the", "names", "corresponding", "to", "the", "column", "names", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L629-L655
1,976
ampl/amplpy
amplpy/ampl.py
AMPL.writeTable
def writeTable(self, tableName): """ Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written. """ lock_and_call( ...
python
def writeTable(self, tableName): """ Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written. """ lock_and_call( ...
[ "def", "writeTable", "(", "self", ",", "tableName", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "writeTable", "(", "tableName", ")", ",", "self", ".", "_lock", ")" ]
Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written.
[ "Write", "the", "table", "corresponding", "to", "the", "specified", "name", "equivalent", "to", "the", "AMPL", "statement" ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L674-L689
1,977
ampl/amplpy
amplpy/ampl.py
AMPL.display
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions t...
python
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions t...
[ "def", "display", "(", "self", ",", "*", "amplExpressions", ")", ":", "exprs", "=", "list", "(", "map", "(", "str", ",", "amplExpressions", ")", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "displayLst", "(", "exprs", ",", "len"...
Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated.
[ "Writes", "on", "the", "current", "OutputHandler", "the", "outcome", "of", "the", "AMPL", "statement", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L691-L708
1,978
ampl/amplpy
amplpy/ampl.py
AMPL.setOutputHandler
def setOutputHandler(self, outputhandler): """ Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands. """ class OutputHandlerInternal(amplpython.OutputHandler): def output...
python
def setOutputHandler(self, outputhandler): """ Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands. """ class OutputHandlerInternal(amplpython.OutputHandler): def output...
[ "def", "setOutputHandler", "(", "self", ",", "outputhandler", ")", ":", "class", "OutputHandlerInternal", "(", "amplpython", ".", "OutputHandler", ")", ":", "def", "output", "(", "self", ",", "kind", ",", "msg", ")", ":", "outputhandler", ".", "output", "(",...
Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands.
[ "Sets", "a", "new", "output", "handler", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L710-L729
1,979
ampl/amplpy
amplpy/ampl.py
AMPL.setErrorHandler
def setErrorHandler(self, errorhandler): """ Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings. """ class ErrorHandlerWrapper(ErrorHandler): def __init__(self, errorhandler): self.errorhandler = err...
python
def setErrorHandler(self, errorhandler): """ Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings. """ class ErrorHandlerWrapper(ErrorHandler): def __init__(self, errorhandler): self.errorhandler = err...
[ "def", "setErrorHandler", "(", "self", ",", "errorhandler", ")", ":", "class", "ErrorHandlerWrapper", "(", "ErrorHandler", ")", ":", "def", "__init__", "(", "self", ",", "errorhandler", ")", ":", "self", ".", "errorhandler", "=", "errorhandler", "self", ".", ...
Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings.
[ "Sets", "a", "new", "error", "handler", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L731-L779
1,980
ampl/amplpy
amplpy/ampl.py
AMPL.getVariables
def getVariables(self): """ Get all the variables declared. """ variables = lock_and_call( lambda: self._impl.getVariables(), self._lock ) return EntityMap(variables, Variable)
python
def getVariables(self): """ Get all the variables declared. """ variables = lock_and_call( lambda: self._impl.getVariables(), self._lock ) return EntityMap(variables, Variable)
[ "def", "getVariables", "(", "self", ")", ":", "variables", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getVariables", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "variables", ",", "Variable", ")" ]
Get all the variables declared.
[ "Get", "all", "the", "variables", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L799-L807
1,981
ampl/amplpy
amplpy/ampl.py
AMPL.getConstraints
def getConstraints(self): """ Get all the constraints declared. """ constraints = lock_and_call( lambda: self._impl.getConstraints(), self._lock ) return EntityMap(constraints, Constraint)
python
def getConstraints(self): """ Get all the constraints declared. """ constraints = lock_and_call( lambda: self._impl.getConstraints(), self._lock ) return EntityMap(constraints, Constraint)
[ "def", "getConstraints", "(", "self", ")", ":", "constraints", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getConstraints", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "constraints", ",", "Constraint", ")...
Get all the constraints declared.
[ "Get", "all", "the", "constraints", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L809-L817
1,982
ampl/amplpy
amplpy/ampl.py
AMPL.getObjectives
def getObjectives(self): """ Get all the objectives declared. """ objectives = lock_and_call( lambda: self._impl.getObjectives(), self._lock ) return EntityMap(objectives, Objective)
python
def getObjectives(self): """ Get all the objectives declared. """ objectives = lock_and_call( lambda: self._impl.getObjectives(), self._lock ) return EntityMap(objectives, Objective)
[ "def", "getObjectives", "(", "self", ")", ":", "objectives", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getObjectives", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "objectives", ",", "Objective", ")" ]
Get all the objectives declared.
[ "Get", "all", "the", "objectives", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L819-L827
1,983
ampl/amplpy
amplpy/ampl.py
AMPL.getSets
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
python
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
[ "def", "getSets", "(", "self", ")", ":", "sets", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getSets", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "sets", ",", "Set", ")" ]
Get all the sets declared.
[ "Get", "all", "the", "sets", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L829-L837
1,984
ampl/amplpy
amplpy/ampl.py
AMPL.getParameters
def getParameters(self): """ Get all the parameters declared. """ parameters = lock_and_call( lambda: self._impl.getParameters(), self._lock ) return EntityMap(parameters, Parameter)
python
def getParameters(self): """ Get all the parameters declared. """ parameters = lock_and_call( lambda: self._impl.getParameters(), self._lock ) return EntityMap(parameters, Parameter)
[ "def", "getParameters", "(", "self", ")", ":", "parameters", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getParameters", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "parameters", ",", "Parameter", ")" ]
Get all the parameters declared.
[ "Get", "all", "the", "parameters", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L839-L847
1,985
ampl/amplpy
amplpy/ampl.py
AMPL.getCurrentObjective
def getCurrentObjective(self): """ Get the the current objective. Returns `None` if no objective is set. """ name = self._impl.getCurrentObjectiveName() if name == '': return None else: return self.getObjective(name)
python
def getCurrentObjective(self): """ Get the the current objective. Returns `None` if no objective is set. """ name = self._impl.getCurrentObjectiveName() if name == '': return None else: return self.getObjective(name)
[ "def", "getCurrentObjective", "(", "self", ")", ":", "name", "=", "self", ".", "_impl", ".", "getCurrentObjectiveName", "(", ")", "if", "name", "==", "''", ":", "return", "None", "else", ":", "return", "self", ".", "getObjective", "(", "name", ")" ]
Get the the current objective. Returns `None` if no objective is set.
[ "Get", "the", "the", "current", "objective", ".", "Returns", "None", "if", "no", "objective", "is", "set", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L849-L857
1,986
ampl/amplpy
amplpy/ampl.py
AMPL._obj
def _obj(self): """ Get an objective. """ class Objectives(object): def __getitem__(_self, name): return self.getObjective(name) def __iter__(_self): return self.getObjectives() return Objectives()
python
def _obj(self): """ Get an objective. """ class Objectives(object): def __getitem__(_self, name): return self.getObjective(name) def __iter__(_self): return self.getObjectives() return Objectives()
[ "def", "_obj", "(", "self", ")", ":", "class", "Objectives", "(", "object", ")", ":", "def", "__getitem__", "(", "_self", ",", "name", ")", ":", "return", "self", ".", "getObjective", "(", "name", ")", "def", "__iter__", "(", "_self", ")", ":", "retu...
Get an objective.
[ "Get", "an", "objective", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L891-L902
1,987
ampl/amplpy
amplpy/ampl.py
AMPL.exportData
def exportData(self, datfile): """ Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). """ def ampl_set(name, values): def format_entry(e): ...
python
def exportData(self, datfile): """ Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). """ def ampl_set(name, values): def format_entry(e): ...
[ "def", "exportData", "(", "self", ",", "datfile", ")", ":", "def", "ampl_set", "(", "name", ",", "values", ")", ":", "def", "format_entry", "(", "e", ")", ":", "return", "repr", "(", "e", ")", ".", "replace", "(", "' '", ",", "''", ")", "return", ...
Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute).
[ "Create", "a", ".", "dat", "file", "with", "the", "data", "that", "has", "been", "loaded", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L959-L1003
1,988
ampl/amplpy
amplpy/ampl.py
AMPL.importGurobiSolution
def importGurobiSolution(self, grbmodel): """ Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved. """ self.eval(''.join( 'let {} := {};'.format(var.VarName, var.X) for var i...
python
def importGurobiSolution(self, grbmodel): """ Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved. """ self.eval(''.join( 'let {} := {};'.format(var.VarName, var.X) for var i...
[ "def", "importGurobiSolution", "(", "self", ",", "grbmodel", ")", ":", "self", ".", "eval", "(", "''", ".", "join", "(", "'let {} := {};'", ".", "format", "(", "var", ".", "VarName", ",", "var", ".", "X", ")", "for", "var", "in", "grbmodel", ".", "ge...
Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved.
[ "Import", "the", "solution", "from", "a", "gurobipy", ".", "Model", "object", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1070-L1081
1,989
ampl/amplpy
amplpy/ampl.py
AMPL._startRecording
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
python
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
[ "def", "_startRecording", "(", "self", ",", "filename", ")", ":", "self", ".", "setOption", "(", "'_log_file_name'", ",", "filename", ")", "self", ".", "setOption", "(", "'_log_input_only'", ",", "True", ")", "self", ".", "setOption", "(", "'_log'", ",", "...
Start recording the session to a file for debug purposes.
[ "Start", "recording", "the", "session", "to", "a", "file", "for", "debug", "purposes", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090
1,990
ampl/amplpy
amplpy/ampl.py
AMPL._loadSession
def _loadSession(self, filename): """ Load a recorded session. """ try: self.eval(open(filename).read()) except RuntimeError as e: print(e)
python
def _loadSession(self, filename): """ Load a recorded session. """ try: self.eval(open(filename).read()) except RuntimeError as e: print(e)
[ "def", "_loadSession", "(", "self", ",", "filename", ")", ":", "try", ":", "self", ".", "eval", "(", "open", "(", "filename", ")", ".", "read", "(", ")", ")", "except", "RuntimeError", "as", "e", ":", "print", "(", "e", ")" ]
Load a recorded session.
[ "Load", "a", "recorded", "session", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1098-L1105
1,991
ampl/amplpy
setup.py
ls_dir
def ls_dir(base_dir): """List files recursively.""" return [ os.path.join(dirpath.replace(base_dir, '', 1), f) for (dirpath, dirnames, files) in os.walk(base_dir) for f in files ]
python
def ls_dir(base_dir): """List files recursively.""" return [ os.path.join(dirpath.replace(base_dir, '', 1), f) for (dirpath, dirnames, files) in os.walk(base_dir) for f in files ]
[ "def", "ls_dir", "(", "base_dir", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "dirpath", ".", "replace", "(", "base_dir", ",", "''", ",", "1", ")", ",", "f", ")", "for", "(", "dirpath", ",", "dirnames", ",", "files", ")", "in", ...
List files recursively.
[ "List", "files", "recursively", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/setup.py#L45-L51
1,992
ampl/amplpy
amplpy/entity.py
Entity.get
def get(self, *index): """ Get the instance with the specified index. Returns: The corresponding instance. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] if len(index) ...
python
def get(self, *index): """ Get the instance with the specified index. Returns: The corresponding instance. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] if len(index) ...
[ "def", "get", "(", "self", ",", "*", "index", ")", ":", "assert", "self", ".", "wrapFunction", "is", "not", "None", "if", "len", "(", "index", ")", "==", "1", "and", "isinstance", "(", "index", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ...
Get the instance with the specified index. Returns: The corresponding instance.
[ "Get", "the", "instance", "with", "the", "specified", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L60-L73
1,993
ampl/amplpy
amplpy/entity.py
Entity.find
def find(self, *index): """ Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, ...
python
def find(self, *index): """ Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, ...
[ "def", "find", "(", "self", ",", "*", "index", ")", ":", "assert", "self", ".", "wrapFunction", "is", "not", "None", "if", "len", "(", "index", ")", "==", "1", "and", "isinstance", "(", "index", "[", "0", "]", ",", "(", "tuple", ",", "list", ")",...
Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`.
[ "Searches", "the", "current", "entity", "for", "an", "instance", "with", "the", "specified", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L75-L89
1,994
ampl/amplpy
amplpy/dataframe.py
DataFrame.addRow
def addRow(self, *value): """ Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments ...
python
def addRow(self, *value): """ Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments ...
[ "def", "addRow", "(", "self", ",", "*", "value", ")", ":", "if", "len", "(", "value", ")", "==", "1", "and", "isinstance", "(", "value", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "value", "=", "value", "[", "0", "]", "asse...
Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments with the values for each column.
[ "Add", "a", "row", "to", "the", "DataFrame", ".", "The", "size", "of", "the", "tuple", "must", "be", "equal", "to", "the", "total", "number", "of", "columns", "in", "the", "dataframe", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L155-L168
1,995
ampl/amplpy
amplpy/dataframe.py
DataFrame.addColumn
def addColumn(self, header, values=[]): """ Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the n...
python
def addColumn(self, header, values=[]): """ Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the n...
[ "def", "addColumn", "(", "self", ",", "header", ",", "values", "=", "[", "]", ")", ":", "if", "len", "(", "values", ")", "==", "0", ":", "self", ".", "_impl", ".", "addColumn", "(", "header", ")", "else", ":", "assert", "len", "(", "values", ")",...
Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the new column.
[ "Add", "a", "new", "column", "with", "the", "corresponding", "header", "and", "values", "to", "the", "dataframe", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L170-L192
1,996
ampl/amplpy
amplpy/dataframe.py
DataFrame.setColumn
def setColumn(self, header, values): """ Set the values of a column. Args: header: The header of the column to be set. values: The values to set. """ if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) ...
python
def setColumn(self, header, values): """ Set the values of a column. Args: header: The header of the column to be set. values: The values to set. """ if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) ...
[ "def", "setColumn", "(", "self", ",", "header", ",", "values", ")", ":", "if", "any", "(", "isinstance", "(", "value", ",", "basestring", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "str", ",", "values", "...
Set the values of a column. Args: header: The header of the column to be set. values: The values to set.
[ "Set", "the", "values", "of", "a", "column", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L203-L220
1,997
ampl/amplpy
amplpy/dataframe.py
DataFrame.getRow
def getRow(self, key): """ Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row. """ ...
python
def getRow(self, key): """ Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row. """ ...
[ "def", "getRow", "(", "self", ",", "key", ")", ":", "return", "Row", "(", "self", ".", "_impl", ".", "getRow", "(", "Tuple", "(", "key", ")", ".", "_impl", ")", ")" ]
Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row.
[ "Get", "a", "row", "by", "value", "of", "the", "indexing", "columns", ".", "If", "the", "index", "is", "not", "specified", "gets", "the", "only", "row", "of", "a", "dataframe", "with", "no", "indexing", "columns", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L222-L233
1,998
ampl/amplpy
amplpy/dataframe.py
DataFrame.getRowByIndex
def getRowByIndex(self, index): """ Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row. """ assert isinstance(index, int) return Row(self._impl.getRowByIndex(index))
python
def getRowByIndex(self, index): """ Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row. """ assert isinstance(index, int) return Row(self._impl.getRowByIndex(index))
[ "def", "getRowByIndex", "(", "self", ",", "index", ")", ":", "assert", "isinstance", "(", "index", ",", "int", ")", "return", "Row", "(", "self", ".", "_impl", ".", "getRowByIndex", "(", "index", ")", ")" ]
Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row.
[ "Get", "row", "by", "numeric", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L235-L246
1,999
ampl/amplpy
amplpy/dataframe.py
DataFrame.getHeaders
def getHeaders(self): """ Get the headers of this DataFrame. Returns: The headers of this DataFrame. """ headers = self._impl.getHeaders() return tuple( headers.getIndex(i) for i in range(self._impl.getNumCols()) )
python
def getHeaders(self): """ Get the headers of this DataFrame. Returns: The headers of this DataFrame. """ headers = self._impl.getHeaders() return tuple( headers.getIndex(i) for i in range(self._impl.getNumCols()) )
[ "def", "getHeaders", "(", "self", ")", ":", "headers", "=", "self", ".", "_impl", ".", "getHeaders", "(", ")", "return", "tuple", "(", "headers", ".", "getIndex", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "_impl", ".", "getNumCols",...
Get the headers of this DataFrame. Returns: The headers of this DataFrame.
[ "Get", "the", "headers", "of", "this", "DataFrame", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L248-L258