repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
edx/XBlock
xblock/runtime.py
Runtime.create_aside
def create_aside(self, block_type, keys): """ The aside version of construct_xblock: take a type and key. Return an instance """ aside_cls = XBlockAside.load_class(block_type) return aside_cls(runtime=self, scope_ids=keys)
python
def create_aside(self, block_type, keys): aside_cls = XBlockAside.load_class(block_type) return aside_cls(runtime=self, scope_ids=keys)
[ "def", "create_aside", "(", "self", ",", "block_type", ",", "keys", ")", ":", "aside_cls", "=", "XBlockAside", ".", "load_class", "(", "block_type", ")", "return", "aside_cls", "(", "runtime", "=", "self", ",", "scope_ids", "=", "keys", ")" ]
The aside version of construct_xblock: take a type and key. Return an instance
[ "The", "aside", "version", "of", "construct_xblock", ":", "take", "a", "type", "and", "key", ".", "Return", "an", "instance" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L923-L928
edx/XBlock
xblock/runtime.py
Runtime.get_asides
def get_asides(self, block): """ Return instances for all of the asides that will decorate this `block`. Arguments: block (:class:`.XBlock`): The block to render retrieve asides for. Returns: List of XBlockAside instances """ aside_instances = [ self.get_aside_of_type(block, aside_type) for aside_type in self.applicable_aside_types(block) ] return [ aside_instance for aside_instance in aside_instances if aside_instance.should_apply_to_block(block) ]
python
def get_asides(self, block): aside_instances = [ self.get_aside_of_type(block, aside_type) for aside_type in self.applicable_aside_types(block) ] return [ aside_instance for aside_instance in aside_instances if aside_instance.should_apply_to_block(block) ]
[ "def", "get_asides", "(", "self", ",", "block", ")", ":", "aside_instances", "=", "[", "self", ".", "get_aside_of_type", "(", "block", ",", "aside_type", ")", "for", "aside_type", "in", "self", ".", "applicable_aside_types", "(", "block", ")", "]", "return", "[", "aside_instance", "for", "aside_instance", "in", "aside_instances", "if", "aside_instance", ".", "should_apply_to_block", "(", "block", ")", "]" ]
Return instances for all of the asides that will decorate this `block`. Arguments: block (:class:`.XBlock`): The block to render retrieve asides for. Returns: List of XBlockAside instances
[ "Return", "instances", "for", "all", "of", "the", "asides", "that", "will", "decorate", "this", "block", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L930-L947
edx/XBlock
xblock/runtime.py
Runtime.get_aside_of_type
def get_aside_of_type(self, block, aside_type): """ Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside """ # TODO: This function will need to be extended if we want to allow: # a) XBlockAsides to statically indicated which types of blocks they can comment on # b) XBlockRuntimes to limit the selection of asides to a subset of the installed asides # c) Optimize by only loading asides that actually decorate a particular view if self.id_generator is None: raise Exception("Runtimes must be supplied with an IdGenerator to load XBlockAsides.") usage_id = block.scope_ids.usage_id aside_cls = self.load_aside_type(aside_type) definition_id = self.id_reader.get_definition_id(usage_id) aside_def_id, aside_usage_id = self.id_generator.create_aside(definition_id, usage_id, aside_type) scope_ids = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) return aside_cls(runtime=self, scope_ids=scope_ids)
python
def get_aside_of_type(self, block, aside_type): if self.id_generator is None: raise Exception("Runtimes must be supplied with an IdGenerator to load XBlockAsides.") usage_id = block.scope_ids.usage_id aside_cls = self.load_aside_type(aside_type) definition_id = self.id_reader.get_definition_id(usage_id) aside_def_id, aside_usage_id = self.id_generator.create_aside(definition_id, usage_id, aside_type) scope_ids = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) return aside_cls(runtime=self, scope_ids=scope_ids)
[ "def", "get_aside_of_type", "(", "self", ",", "block", ",", "aside_type", ")", ":", "# TODO: This function will need to be extended if we want to allow:", "# a) XBlockAsides to statically indicated which types of blocks they can comment on", "# b) XBlockRuntimes to limit the selection of asides to a subset of the installed asides", "# c) Optimize by only loading asides that actually decorate a particular view", "if", "self", ".", "id_generator", "is", "None", ":", "raise", "Exception", "(", "\"Runtimes must be supplied with an IdGenerator to load XBlockAsides.\"", ")", "usage_id", "=", "block", ".", "scope_ids", ".", "usage_id", "aside_cls", "=", "self", ".", "load_aside_type", "(", "aside_type", ")", "definition_id", "=", "self", ".", "id_reader", ".", "get_definition_id", "(", "usage_id", ")", "aside_def_id", ",", "aside_usage_id", "=", "self", ".", "id_generator", ".", "create_aside", "(", "definition_id", ",", "usage_id", ",", "aside_type", ")", "scope_ids", "=", "ScopeIds", "(", "self", ".", "user_id", ",", "aside_type", ",", "aside_def_id", ",", "aside_usage_id", ")", "return", "aside_cls", "(", "runtime", "=", "self", ",", "scope_ids", "=", "scope_ids", ")" ]
Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside
[ "Return", "the", "aside", "of", "the", "given", "aside_type", "which", "might", "be", "decorating", "this", "block", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L958-L980
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.aside_view_declaration(view_name) if aside_view_fn is not None: aside_frag_fns.append((aside, aside_view_fn)) if aside_frag_fns: # layout (overideable by other runtimes) return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
python
def render_asides(self, block, view_name, frag, context): aside_frag_fns = [] for aside in self.get_asides(block): aside_view_fn = aside.aside_view_declaration(view_name) if aside_view_fn is not None: aside_frag_fns.append((aside, aside_view_fn)) if aside_frag_fns: return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
[ "def", "render_asides", "(", "self", ",", "block", ",", "view_name", ",", "frag", ",", "context", ")", ":", "aside_frag_fns", "=", "[", "]", "for", "aside", "in", "self", ".", "get_asides", "(", "block", ")", ":", "aside_view_fn", "=", "aside", ".", "aside_view_declaration", "(", "view_name", ")", "if", "aside_view_fn", "is", "not", "None", ":", "aside_frag_fns", ".", "append", "(", "(", "aside", ",", "aside_view_fn", ")", ")", "if", "aside_frag_fns", ":", "# layout (overideable by other runtimes)", "return", "self", ".", "layout_asides", "(", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", "return", "frag" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L982-L995
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 method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call """ result = Fragment(frag.content) result.add_fragment_resources(frag) for aside, aside_fn in aside_frag_fns: aside_frag = self.wrap_aside(block, aside, view_name, aside_fn(block, context), context) aside.save() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
python
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): result = Fragment(frag.content) result.add_fragment_resources(frag) for aside, aside_fn in aside_frag_fns: aside_frag = self.wrap_aside(block, aside, view_name, aside_fn(block, context), context) aside.save() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
[ "def", "layout_asides", "(", "self", ",", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", ":", "result", "=", "Fragment", "(", "frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "frag", ")", "for", "aside", ",", "aside_fn", "in", "aside_frag_fns", ":", "aside_frag", "=", "self", ".", "wrap_aside", "(", "block", ",", "aside", ",", "view_name", ",", "aside_fn", "(", "block", ",", "context", ")", ",", "context", ")", "aside", ".", "save", "(", ")", "result", ".", "add_content", "(", "aside_frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "aside_frag", ")", "return", "result" ]
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 around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call
[ "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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L997-L1019
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 :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
python
def handle(self, block, handler_name, request, suffix=''): handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) block.save() return results
[ "def", "handle", "(", "self", ",", "block", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "handler", "=", "getattr", "(", "block", ",", "handler_name", ",", "None", ")", "if", "handler", "and", "getattr", "(", "handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "handler", "(", "request", ",", "suffix", ")", "else", ":", "fallback_handler", "=", "getattr", "(", "block", ",", "\"fallback_handler\"", ",", "None", ")", "if", "fallback_handler", "and", "getattr", "(", "fallback_handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "fallback_handler", "(", "handler_name", ",", "request", ",", "suffix", ")", "else", ":", "raise", "NoSuchHandlerError", "(", "\"Couldn't find handler %r for %r\"", "%", "(", "handler_name", ",", "block", ")", ")", "# Write out dirty fields", "block", ".", "save", "(", ")", "return", "results" ]
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, after the handler url prefix, if available
[ "Handles", "any", "calls", "to", "the", "specified", "handler_name", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1023-L1048
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. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None. """ declaration = block.service_declaration(service_name) if declaration is None: raise NoSuchServiceError("Service {!r} was not requested.".format(service_name)) service = self._services.get(service_name) if service is None and declaration == "need": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
python
def service(self, block, service_name): declaration = block.service_declaration(service_name) if declaration is None: raise NoSuchServiceError("Service {!r} was not requested.".format(service_name)) service = self._services.get(service_name) if service is None and declaration == "need": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
[ "def", "service", "(", "self", ",", "block", ",", "service_name", ")", ":", "declaration", "=", "block", ".", "service_declaration", "(", "service_name", ")", "if", "declaration", "is", "None", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} was not requested.\"", ".", "format", "(", "service_name", ")", ")", "service", "=", "self", ".", "_services", ".", "get", "(", "service_name", ")", "if", "service", "is", "None", "and", "declaration", "==", "\"need\"", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} is not available.\"", ".", "format", "(", "service_name", ")", ")", "return", "service" ]
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 services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None.
[ "Return", "a", "service", "or", "None", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1052-L1082
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: disable=C0103 state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: # Shouldn't be any tokens after a last token. raise BadPath() if tokname == "dotdot": # .. (parent) if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": # . (current node) if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": # // (descendants) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": # / (here) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": # @xxx (attribute access) if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": # xxx (tag selection) if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
python
def querypath(self, block, path): class BadPath(Exception): pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: raise BadPath() if tokname == "dotdot": if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
[ "def", "querypath", "(", "self", ",", "block", ",", "path", ")", ":", "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: disable=C0103", "state", "=", "ROOT", "lexer", "=", "RegexLexer", "(", "(", "\"dotdot\"", ",", "r\"\\.\\.\"", ")", ",", "(", "\"dot\"", ",", "r\"\\.\"", ")", ",", "(", "\"slashslash\"", ",", "r\"//\"", ")", ",", "(", "\"slash\"", ",", "r\"/\"", ")", ",", "(", "\"atword\"", ",", "r\"@\\w+\"", ")", ",", "(", "\"word\"", ",", "r\"\\w+\"", ")", ",", "(", "\"err\"", ",", "r\".\"", ")", ",", ")", "for", "tokname", ",", "toktext", "in", "lexer", ".", "lex", "(", "path", ")", ":", "if", "state", "==", "FINAL", ":", "# Shouldn't be any tokens after a last token.", "raise", "BadPath", "(", ")", "if", "tokname", "==", "\"dotdot\"", ":", "# .. (parent)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "parent", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"dot\"", ":", "# . (current node)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"slashslash\"", ":", "# // (descendants)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "results", "=", "results", ".", "descendants", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"slash\"", ":", "# / (here)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"atword\"", ":", "# @xxx (attribute access)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "attr", "(", "toktext", "[", "1", ":", "]", ")", "state", "=", "FINAL", "elif", "tokname", "==", "\"word\"", ":", "# xxx (tag selection)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "children", "(", ")", ".", "tagged", "(", "toktext", ")", "state", "=", "WORD", "else", ":", "raise", "BadPath", "(", "\"Invalid thing: %r\"", "%", "toktext", ")", "return", "results" ]
An XPath-like interface to `query`.
[ "An", "XPath", "-", "like", "interface", "to", "query", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1095-L1156
edx/XBlock
xblock/runtime.py
Runtime._family_id_to_superclass
def _family_id_to_superclass(self, family_id): """ Temporary hardcoded mapping from serialized family id to either `class :XBlock:` or `:XBlockAside` """ for family in [XBlock, XBlockAside]: if family_id == family.entry_point: return family raise ValueError('No such family: {}'.format(family_id))
python
def _family_id_to_superclass(self, family_id): for family in [XBlock, XBlockAside]: if family_id == family.entry_point: return family raise ValueError('No such family: {}'.format(family_id))
[ "def", "_family_id_to_superclass", "(", "self", ",", "family_id", ")", ":", "for", "family", "in", "[", "XBlock", ",", "XBlockAside", "]", ":", "if", "family_id", "==", "family", ".", "entry_point", ":", "return", "family", "raise", "ValueError", "(", "'No such family: {}'", ".", "format", "(", "family_id", ")", ")" ]
Temporary hardcoded mapping from serialized family id to either `class :XBlock:` or `:XBlockAside`
[ "Temporary", "hardcoded", "mapping", "from", "serialized", "family", "id", "to", "either", "class", ":", "XBlock", ":", "or", ":", "XBlockAside" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1158-L1165
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 hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
python
def _object_with_attr(self, name): for obj in self._objects: if hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
[ "def", "_object_with_attr", "(", "self", ",", "name", ")", ":", "for", "obj", "in", "self", ".", "_objects", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "return", "obj", "raise", "AttributeError", "(", "\"No object has attribute {!r}\"", ".", "format", "(", "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
[ "Returns", "the", "first", "object", "that", "has", "the", "attribute", "name" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1179-L1191
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 the original unmixed class mixins = old_mixins + tuple( mixin for mixin in self._mixins if mixin not in old_mixins ) else: base_class = cls mixins = self._mixins mixin_key = (base_class, mixins) if mixin_key not in _CLASS_CACHE: # Only lock if we're about to make a new class with _CLASS_CACHE_LOCK: # Use setdefault so that if someone else has already # created a class before we got the lock, we don't # overwrite it return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), # type() requires native str (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
python
def mix(self, cls): if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] mixins = old_mixins + tuple( mixin for mixin in self._mixins if mixin not in old_mixins ) else: base_class = cls mixins = self._mixins mixin_key = (base_class, mixins) if mixin_key not in _CLASS_CACHE: with _CLASS_CACHE_LOCK: return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
[ "def", "mix", "(", "self", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'unmixed_class'", ")", ":", "base_class", "=", "cls", ".", "unmixed_class", "old_mixins", "=", "cls", ".", "__bases__", "[", "1", ":", "]", "# Skip the original unmixed class", "mixins", "=", "old_mixins", "+", "tuple", "(", "mixin", "for", "mixin", "in", "self", ".", "_mixins", "if", "mixin", "not", "in", "old_mixins", ")", "else", ":", "base_class", "=", "cls", "mixins", "=", "self", ".", "_mixins", "mixin_key", "=", "(", "base_class", ",", "mixins", ")", "if", "mixin_key", "not", "in", "_CLASS_CACHE", ":", "# Only lock if we're about to make a new class", "with", "_CLASS_CACHE_LOCK", ":", "# Use setdefault so that if someone else has already", "# created a class before we got the lock, we don't", "# overwrite it", "return", "_CLASS_CACHE", ".", "setdefault", "(", "mixin_key", ",", "type", "(", "base_class", ".", "__name__", "+", "str", "(", "'WithMixins'", ")", ",", "# type() requires native str", "(", "base_class", ",", ")", "+", "mixins", ",", "{", "'unmixed_class'", ":", "base_class", "}", ")", ")", "else", ":", "return", "_CLASS_CACHE", "[", "mixin_key", "]" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1219-L1253
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): 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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1264-L1268
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("utf8") timestring = dtime.strftime(format) if six.PY2: timestring = timestring.decode("utf8") return timestring
python
def strftime(self, dtime, format): format = self.STRFTIME_FORMATS.get(format + "_FORMAT", format) if six.PY2 and isinstance(format, six.text_type): format = format.encode("utf8") timestring = dtime.strftime(format) if six.PY2: timestring = timestring.decode("utf8") return timestring
[ "def", "strftime", "(", "self", ",", "dtime", ",", "format", ")", ":", "# pylint: disable=redefined-builtin", "format", "=", "self", ".", "STRFTIME_FORMATS", ".", "get", "(", "format", "+", "\"_FORMAT\"", ",", "format", ")", "if", "six", ".", "PY2", "and", "isinstance", "(", "format", ",", "six", ".", "text_type", ")", ":", "format", "=", "format", ".", "encode", "(", "\"utf8\"", ")", "timestring", "=", "dtime", ".", "strftime", "(", "format", ")", "if", "six", ".", "PY2", ":", "timestring", "=", "timestring", ".", "decode", "(", "\"utf8\"", ")", "return", "timestring" ]
Locale-aware strftime, with format short-cuts.
[ "Locale", "-", "aware", "strftime", "with", "format", "short", "-", "cuts", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1288-L1298
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 six.PY2: return self._translations.ugettext else: return self._translations.gettext
python
def ugettext(self): if six.PY2: return self._translations.ugettext else: return self._translations.gettext
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1301-L1312
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 if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
python
def ungettext(self): if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1315-L1326
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(scope_key(instance, xblock)) else: # The reference implementation relies on djpyfs # https://github.com/edx/django-pyfs # For Django runtimes, you may use this reference # implementation. Otherwise, you will need to # patch pyfilesystem yourself to implement get_url. raise NotImplementedError("djpyfs not available")
python
def load(self, instance, xblock): if djpyfs: return djpyfs.get_filesystem(scope_key(instance, xblock)) else: raise NotImplementedError("djpyfs not available")
[ "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", ")", ")", "else", ":", "# The reference implementation relies on djpyfs", "# https://github.com/edx/django-pyfs", "# For Django runtimes, you may use this reference", "# implementation. Otherwise, you will need to", "# patch pyfilesystem yourself to implement get_url.", "raise", "NotImplementedError", "(", "\"djpyfs not available\"", ")" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/reference/plugins.py#L190-L205
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. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None """ completion_mode = XBlockCompletionMode.get_mode(self) if not self.has_custom_completion or completion_mode != XBlockCompletionMode.COMPLETABLE: raise AttributeError( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
python
def emit_completion(self, completion_percent): completion_mode = XBlockCompletionMode.get_mode(self) if not self.has_custom_completion or completion_mode != XBlockCompletionMode.COMPLETABLE: raise AttributeError( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
[ "def", "emit_completion", "(", "self", ",", "completion_percent", ")", ":", "completion_mode", "=", "XBlockCompletionMode", ".", "get_mode", "(", "self", ")", "if", "not", "self", ".", "has_custom_completion", "or", "completion_mode", "!=", "XBlockCompletionMode", ".", "COMPLETABLE", ":", "raise", "AttributeError", "(", "\"Using `emit_completion` requires `has_custom_completion == True` (was {}) \"", "\"and `completion_mode == 'completable'` (was {})\"", ".", "format", "(", "self", ".", "has_custom_completion", ",", "completion_mode", ",", ")", ")", "if", "completion_percent", "is", "None", "or", "not", "0.0", "<=", "completion_percent", "<=", "1.0", ":", "raise", "ValueError", "(", "\"Completion percent must be in [0.0; 1.0] interval, {} given\"", ".", "format", "(", "completion_percent", ")", ")", "self", ".", "runtime", ".", "publish", "(", "self", ",", "'completion'", ",", "{", "'completion'", ":", "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. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None
[ "Emits", "completion", "event", "through", "Completion", "API", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/completable.py#L35-L65
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: self.get(block, name) return True except KeyError: return False
python
def has(self, block, name): try: self.get(block, name) return True except KeyError: return False
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L69-L82
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 """ for key, value in six.iteritems(update_dict): self.set(block, key, value)
python
def set_many(self, block, update_dict): for key, value in six.iteritems(update_dict): self.set(block, key, value)
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L84-L94
edx/XBlock
xblock/field_data.py
SplitFieldData._field_data
def _field_data(self, block, name): """Return the field data for the field `name` on the :class:`~xblock.core.XBlock` `block`""" scope = block.fields[name].scope if scope not in self._scope_mappings: raise InvalidScopeError(scope) return self._scope_mappings[scope]
python
def _field_data(self, block, name): scope = block.fields[name].scope if scope not in self._scope_mappings: raise InvalidScopeError(scope) return self._scope_mappings[scope]
[ "def", "_field_data", "(", "self", ",", "block", ",", "name", ")", ":", "scope", "=", "block", ".", "fields", "[", "name", "]", ".", "scope", "if", "scope", "not", "in", "self", ".", "_scope_mappings", ":", "raise", "InvalidScopeError", "(", "scope", ")", "return", "self", ".", "_scope_mappings", "[", "scope", "]" ]
Return the field data for the field `name` on the :class:`~xblock.core.XBlock` `block`
[ "Return", "the", "field", "data", "for", "the", "field", "name", "on", "the", ":", "class", ":", "~xblock", ".", "core", ".", "XBlock", "block" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L150-L157
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 Response( json.dumps({"error": self.message}), # pylint: disable=exception-message-attribute status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
python
def get_response(self, **kwargs): return Response( json.dumps({"error": self.message}), status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
[ "def", "get_response", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Response", "(", "json", ".", "dumps", "(", "{", "\"error\"", ":", "self", ".", "message", "}", ")", ",", "# pylint: disable=exception-message-attribute", "status_code", "=", "self", ".", "status_code", ",", "content_type", "=", "\"application/json\"", ",", "charset", "=", "\"utf-8\"", ",", "*", "*", "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.
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/exceptions.py#L126-L139
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 will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON. """ @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): """The wrapper function `json_handler` returns.""" if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
python
def json_handler(cls, func): @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
[ "def", "json_handler", "(", "cls", ",", "func", ")", ":", "@", "cls", ".", "handler", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "request", ",", "suffix", "=", "''", ")", ":", "\"\"\"The wrapper function `json_handler` returns.\"\"\"", "if", "request", ".", "method", "!=", "\"POST\"", ":", "return", "JsonHandlerError", "(", "405", ",", "\"Method must be POST\"", ")", ".", "get_response", "(", "allow", "=", "[", "\"POST\"", "]", ")", "try", ":", "request_json", "=", "json", ".", "loads", "(", "request", ".", "body", ")", "except", "ValueError", ":", "return", "JsonHandlerError", "(", "400", ",", "\"Invalid JSON\"", ")", ".", "get_response", "(", ")", "try", ":", "response", "=", "func", "(", "self", ",", "request_json", ",", "suffix", ")", "except", "JsonHandlerError", "as", "err", ":", "return", "err", ".", "get_response", "(", ")", "if", "isinstance", "(", "response", ",", "Response", ")", ":", "return", "response", "else", ":", "return", "Response", "(", "json", ".", "dumps", "(", "response", ")", ",", "content_type", "=", "'application/json'", ",", "charset", "=", "'utf8'", ")", "return", "wrapper" ]
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 response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON.
[ "Wrap", "a", "handler", "to", "consume", "and", "produce", "JSON", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L40-L75
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=''): 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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L87-L89
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 walk up the inheritance # hierarchy, and combine all the declared services into one dictionary. combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
python
def _combined_services(cls): combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
[ "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 dictionary.", "combined", "=", "{", "}", "for", "parent", "in", "reversed", "(", "cls", ".", "mro", "(", ")", ")", ":", "combined", ".", "update", "(", "getattr", "(", "parent", ",", "\"_services_requested\"", ",", "{", "}", ")", ")", "return", "combined" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L104-L114
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_name] = "need" # pylint: disable=protected-access return cls_ return _decorator
python
def needs(cls, *service_names): def _decorator(cls_): for service_name in service_names: cls_._services_requested[service_name] = "need" return cls_ return _decorator
[ "def", "needs", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"need\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class needs particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "needs", "particular", "services", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L127-L133
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_name] = "want" # pylint: disable=protected-access return cls_ return _decorator
python
def wants(cls, *service_names): def _decorator(cls_): for service_name in service_names: cls_._services_requested[service_name] = "want" return cls_ return _decorator
[ "def", "wants", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"want\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class wants particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "wants", "particular", "services", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L136-L142
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 self._parent_block_id = self.parent return self._parent_block
python
def get_parent(self): 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 self._parent_block_id = self.parent return self._parent_block
[ "def", "get_parent", "(", "self", ")", ":", "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", "self", ".", "_parent_block_id", "=", "self", ".", "parent", "return", "self", ".", "_parent_block" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L373-L381
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 child_block
python
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, for_parent=self) self._child_cache[usage_id] = child_block return child_block
[ "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", ",", "for_parent", "=", "self", ")", "self", ".", "_child_cache", "[", "usage_id", "]", "=", "child_block", "return", "child_block" ]
Return the child identified by ``usage_id``.
[ "Return", "the", "child", "identified", "by", "usage_id", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L388-L395
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_filter is None or usage_id_filter(usage_id) ]
python
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.children if usage_id_filter is None or usage_id_filter(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", ".", "children", "if", "usage_id_filter", "is", "None", "or", "usage_id_filter", "(", "usage_id", ")", "]" ]
Return instantiated XBlocks for each of this blocks ``children``.
[ "Return", "instantiated", "XBlocks", "for", "each", "of", "this", "blocks", "children", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L397-L408
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): 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", ".", "runtime", ".", "add_block_as_child_node", "(", "child", ",", "node", ")" ]
Add children to etree.Element `node`.
[ "Add", "children", "to", "etree", ".", "Element", "node", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L416-L423
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. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block. """ block = runtime.construct_xblock_from_class(cls, keys) # The base implementation: child nodes become child blocks. # Or fields, if they belong to the right namespace. for child in node: if child.tag is etree.Comment: continue qname = etree.QName(child) tag = qname.localname namespace = qname.namespace if namespace == XML_NAMESPACES["option"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) # Attributes become fields. for name, value in node.items(): # lxml has no iteritems cls._set_field_if_present(block, name, value, {}) # Text content becomes "content", if such a field exists. if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
python
def parse_xml(cls, node, runtime, keys, id_generator): block = runtime.construct_xblock_from_class(cls, keys) for child in node: if child.tag is etree.Comment: continue qname = etree.QName(child) tag = qname.localname namespace = qname.namespace if namespace == XML_NAMESPACES["option"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) for name, value in node.items(): cls._set_field_if_present(block, name, value, {}) if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
[ "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 fields, if they belong to the right namespace.", "for", "child", "in", "node", ":", "if", "child", ".", "tag", "is", "etree", ".", "Comment", ":", "continue", "qname", "=", "etree", ".", "QName", "(", "child", ")", "tag", "=", "qname", ".", "localname", "namespace", "=", "qname", ".", "namespace", "if", "namespace", "==", "XML_NAMESPACES", "[", "\"option\"", "]", ":", "cls", ".", "_set_field_if_present", "(", "block", ",", "tag", ",", "child", ".", "text", ",", "child", ".", "attrib", ")", "else", ":", "block", ".", "runtime", ".", "add_node_as_child", "(", "block", ",", "child", ",", "id_generator", ")", "# Attributes become fields.", "for", "name", ",", "value", "in", "node", ".", "items", "(", ")", ":", "# lxml has no iteritems", "cls", ".", "_set_field_if_present", "(", "block", ",", "name", ",", "value", ",", "{", "}", ")", "# Text content becomes \"content\", if such a field exists.", "if", "\"content\"", "in", "block", ".", "fields", "and", "block", ".", "fields", "[", "\"content\"", "]", ".", "scope", "==", "Scope", ".", "content", ":", "text", "=", "node", ".", "text", "if", "text", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "text", ":", "block", ".", "content", "=", "text", "return", "block" ]
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 will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block.
[ "Use", "node", "to", "construct", "a", "new", "block", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L432-L477
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 based on our fields. for field_name, field in self.fields.items(): if field_name in ('children', 'parent', 'content'): continue if field.is_set_on(self) or field.force_export: self._add_field(node, field_name, field) # A content field becomes text content. text = self.xml_text_content() if text is not None: node.text = text
python
def add_xml_to_node(self, node): node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) for field_name, field in self.fields.items(): if field_name in ('children', 'parent', 'content'): continue if field.is_set_on(self) or field.force_export: self._add_field(node, field_name, field) text = self.xml_text_content() if text is not None: node.text = text
[ "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", ".", "entry_point", ")", "# Set node attributes based on our fields.", "for", "field_name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "field_name", "in", "(", "'children'", ",", "'parent'", ",", "'content'", ")", ":", "continue", "if", "field", ".", "is_set_on", "(", "self", ")", "or", "field", ".", "force_export", ":", "self", ".", "_add_field", "(", "node", ",", "field_name", ",", "field", ")", "# A content field becomes text content.", "text", "=", "self", ".", "xml_text_content", "(", ")", "if", "text", "is", "not", "None", ":", "node", ".", "text", "=", "text" ]
For exporting, set data on `node` from ourselves.
[ "For", "exporting", "set", "data", "on", "node", "from", "ourselves", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L479-L498
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, None) else: setattr(block, name, value) else: logging.warning("XBlock %s does not contain field %s", type(block), name)
python
def _set_field_if_present(cls, block, name, value, attrs): if name in block.fields: value = (block.fields[name]).from_string(value) if "none" in attrs and attrs["none"] == "true": setattr(block, name, None) else: setattr(block, name, value) else: logging.warning("XBlock %s does not contain field %s", type(block), name)
[ "def", "_set_field_if_present", "(", "cls", ",", "block", ",", "name", ",", "value", ",", "attrs", ")", ":", "if", "name", "in", "block", ".", "fields", ":", "value", "=", "(", "block", ".", "fields", "[", "name", "]", ")", ".", "from_string", "(", "value", ")", "if", "\"none\"", "in", "attrs", "and", "attrs", "[", "\"none\"", "]", "==", "\"true\"", ":", "setattr", "(", "block", ",", "name", ",", "None", ")", "else", ":", "setattr", "(", "block", ",", "name", ",", "value", ")", "else", ":", "logging", ".", "warning", "(", "\"XBlock %s does not contain field %s\"", ",", "type", "(", "block", ")", ",", "name", ")" ]
Sets the field block.name, if block have such a field.
[ "Sets", "the", "field", "block", ".", "name", "if", "block", "have", "such", "a", "field", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L513-L522
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_value = "" if value is None else value # Is the field type supposed to serialize the fact that the value is None to XML? save_none_as_xml_attr = field.none_to_xml and value is None field_attrs = {"none": "true"} if save_none_as_xml_attr else {} if save_none_as_xml_attr or field.xml_node: # Field will be output to XML as an separate element. tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: # Only set the value if forced via xml_node; # in all other cases, the value is None. # Avoids an unnecessary XML end tag. elem.text = text_value else: # Field will be output to XML as an attribute on the node. node.set(field_name, text_value)
python
def _add_field(self, node, field_name, field): value = field.to_string(field.read_from(self)) text_value = "" if value is None else value save_none_as_xml_attr = field.none_to_xml and value is None field_attrs = {"none": "true"} if save_none_as_xml_attr else {} if save_none_as_xml_attr or field.xml_node: tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: elem.text = text_value else: node.set(field_name, text_value)
[ "def", "_add_field", "(", "self", ",", "node", ",", "field_name", ",", "field", ")", ":", "value", "=", "field", ".", "to_string", "(", "field", ".", "read_from", "(", "self", ")", ")", "text_value", "=", "\"\"", "if", "value", "is", "None", "else", "value", "# Is the field type supposed to serialize the fact that the value is None to XML?", "save_none_as_xml_attr", "=", "field", ".", "none_to_xml", "and", "value", "is", "None", "field_attrs", "=", "{", "\"none\"", ":", "\"true\"", "}", "if", "save_none_as_xml_attr", "else", "{", "}", "if", "save_none_as_xml_attr", "or", "field", ".", "xml_node", ":", "# Field will be output to XML as an separate element.", "tag", "=", "etree", ".", "QName", "(", "XML_NAMESPACES", "[", "\"option\"", "]", ",", "field_name", ")", "elem", "=", "etree", ".", "SubElement", "(", "node", ",", "tag", ",", "field_attrs", ")", "if", "field", ".", "xml_node", ":", "# Only set the value if forced via xml_node;", "# in all other cases, the value is None.", "# Avoids an unnecessary XML end tag.", "elem", ".", "text", "=", "text_value", "else", ":", "# Field will be output to XML as an attribute on the node.", "node", ".", "set", "(", "field_name", ",", "text_value", ")" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L524-L549
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". """ def _decorator(view): """ Internal decorator that updates the given view's list of supported functionalities. """ # pylint: disable=protected-access if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
python
def supports(cls, *functionalities): def _decorator(view): if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
[ "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-access", "if", "not", "hasattr", "(", "view", ",", "\"_supports\"", ")", ":", "view", ".", "_supports", "=", "set", "(", ")", "for", "functionality", "in", "functionalities", ":", "view", ".", "_supports", ".", "add", "(", "functionality", ")", "return", "view", "return", "_decorator" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L572-L592
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 the problem. May also raise other errors in self.calculate_score(). Currently unconstrained. """ _ = self.runtime.service(self, 'i18n').ugettext if not self.allows_rescore(): raise TypeError(_('Problem does not support rescoring: {}').format(self.location)) if not self.has_submitted_answer(): raise ValueError(_('Cannot rescore unanswered problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
python
def rescore(self, only_if_higher): _ = self.runtime.service(self, 'i18n').ugettext if not self.allows_rescore(): raise TypeError(_('Problem does not support rescoring: {}').format(self.location)) if not self.has_submitted_answer(): raise ValueError(_('Cannot rescore unanswered problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
[ "def", "rescore", "(", "self", ",", "only_if_higher", ")", ":", "_", "=", "self", ".", "runtime", ".", "service", "(", "self", ",", "'i18n'", ")", ".", "ugettext", "if", "not", "self", ".", "allows_rescore", "(", ")", ":", "raise", "TypeError", "(", "_", "(", "'Problem does not support rescoring: {}'", ")", ".", "format", "(", "self", ".", "location", ")", ")", "if", "not", "self", ".", "has_submitted_answer", "(", ")", ":", "raise", "ValueError", "(", "_", "(", "'Cannot rescore unanswered problem: {}'", ")", ".", "format", "(", "self", ".", "location", ")", ")", "new_score", "=", "self", ".", "calculate_score", "(", ")", "self", ".", "_publish_grade", "(", "new_score", ",", "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 the problem. May also raise other errors in self.calculate_score(). Currently unconstrained.
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L34-L55
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, 'grade', grade_dict)
python
def _publish_grade(self, score, only_if_higher=None): grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'grade', grade_dict)
[ "def", "_publish_grade", "(", "self", ",", "score", ",", "only_if_higher", "=", "None", ")", ":", "grade_dict", "=", "{", "'value'", ":", "score", ".", "raw_earned", ",", "'max_value'", ":", "score", ".", "raw_possible", ",", "'only_if_higher'", ":", "only_if_higher", ",", "}", "self", ".", "runtime", ".", "publish", "(", "self", ",", "'grade'", ",", "grade_dict", ")" ]
Publish a grade to the runtime.
[ "Publish", "a", "grade", "to", "the", "runtime", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L108-L117
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: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a """ scope_key_dict = {} scope_key_dict['name'] = instance.name if instance.scope.user == UserScope.NONE or instance.scope.user == UserScope.ALL: pass elif instance.scope.user == UserScope.ONE: scope_key_dict['user'] = six.text_type(xblock.scope_ids.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) # Above runs in 4.7us, and generates a list of common substitutions: # {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\': '.-', '_': '__'} key_list = [] def encode(char): """ Replace all non-alphanumeric characters with -n- where n is their Unicode codepoint. TODO: Test for UTF8 which is not ASCII """ if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] # Prevent injection of "..", hidden files, or similar. # First part adds a prefix. Second part guarantees # continued uniqueness. if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
python
def scope_key(instance, xblock): scope_key_dict = {} scope_key_dict['name'] = instance.name if instance.scope.user == UserScope.NONE or instance.scope.user == UserScope.ALL: pass elif instance.scope.user == UserScope.ONE: scope_key_dict['user'] = six.text_type(xblock.scope_ids.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) key_list = [] def encode(char): if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
[ "def", "scope_key", "(", "instance", ",", "xblock", ")", ":", "scope_key_dict", "=", "{", "}", "scope_key_dict", "[", "'name'", "]", "=", "instance", ".", "name", "if", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "NONE", "or", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "ALL", ":", "pass", "elif", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "ONE", ":", "scope_key_dict", "[", "'user'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "user_id", ")", "else", ":", "raise", "NotImplementedError", "(", ")", "if", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "TYPE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "block_type", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "USAGE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "usage_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "DEFINITION", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "def_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "ALL", ":", "pass", "else", ":", "raise", "NotImplementedError", "(", ")", "replacements", "=", "itertools", ".", "product", "(", "\"._-\"", ",", "\"._-\"", ")", "substitution_list", "=", "dict", "(", "six", ".", "moves", ".", "zip", "(", "\"./\\\\,_ +:-\"", ",", "(", "\"\"", ".", "join", "(", "x", ")", "for", "x", "in", "replacements", ")", ")", ")", "# Above runs in 4.7us, and generates a list of common substitutions:", "# {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\\\': '.-', '_': '__'}", "key_list", "=", "[", "]", "def", "encode", "(", "char", ")", ":", "\"\"\"\n Replace all non-alphanumeric characters with -n- where n\n is their Unicode codepoint.\n TODO: Test for UTF8 which is not ASCII\n \"\"\"", "if", "char", ".", "isalnum", "(", ")", ":", "return", "char", "elif", "char", "in", "substitution_list", ":", "return", "substitution_list", "[", "char", "]", "else", ":", "return", "\"_{}_\"", ".", "format", "(", "ord", "(", "char", ")", ")", "for", "item", "in", "[", "'block'", ",", "'name'", ",", "'user'", "]", ":", "if", "item", "in", "scope_key_dict", ":", "field", "=", "scope_key_dict", "[", "item", "]", "# Prevent injection of \"..\", hidden files, or similar.", "# First part adds a prefix. Second part guarantees", "# continued uniqueness.", "if", "field", ".", "startswith", "(", "\".\"", ")", "or", "field", ".", "startswith", "(", "\"_\"", ")", ":", "field", "=", "\"_\"", "+", "field", "field", "=", "\"\"", ".", "join", "(", "encode", "(", "char", ")", "for", "char", "in", "field", ")", "else", ":", "field", "=", "\"NONE.NONE\"", "key_list", ".", "append", "(", "field", ")", "key", "=", "\"/\"", ".", "join", "(", "key_list", ")", "return", "key" ]
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 like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a
[ "Generate", "a", "unique", "key", "for", "a", "scope", "that", "can", "be", "used", "as", "a", "filename", "in", "a", "URL", "or", "in", "a", "KVS", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L1045-L1138
edx/XBlock
xblock/fields.py
BlockScope.scopes
def scopes(cls): """ Return a list of valid/understood class scopes. """ # Why do we need this? This should either # * Be bubbled to the places where it is used (AcidXBlock). # * Be automatic. Look for all members of a type. return [cls.USAGE, cls.DEFINITION, cls.TYPE, cls.ALL]
python
def scopes(cls): return [cls.USAGE, cls.DEFINITION, cls.TYPE, cls.ALL]
[ "def", "scopes", "(", "cls", ")", ":", "# Why do we need this? This should either", "# * Be bubbled to the places where it is used (AcidXBlock).", "# * Be automatic. Look for all members of a type.", "return", "[", "cls", ".", "USAGE", ",", "cls", ".", "DEFINITION", ",", "cls", ".", "TYPE", ",", "cls", ".", "ALL", "]" ]
Return a list of valid/understood class scopes.
[ "Return", "a", "list", "of", "valid", "/", "understood", "class", "scopes", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L110-L117
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): 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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L342-L347
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): 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", ".", "_field_data_cache", "[", "self", ".", "name", "]", "=", "value" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L404-L409
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): 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", ".", "_field_data_cache", "[", "self", ".", "name", "]" ]
Remove a value from the xblock's cache, if the cache exists.
[ "Remove", "a", "value", "from", "the", "xblock", "s", "cache", "if", "the", "cache", "exists", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L411-L415
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: xblock._dirty_fields[self] = copy.deepcopy(value)
python
def _mark_dirty(self, xblock, value): if self not in xblock._dirty_fields: xblock._dirty_fields[self] = copy.deepcopy(value)
[ "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_fields", ":", "xblock", ".", "_dirty_fields", "[", "self", "]", "=", "copy", ".", "deepcopy", "(", "value", ")" ]
Set this field to dirty on the xblock.
[ "Set", "this", "field", "to", "dirty", "on", "the", "xblock", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L417-L424
edx/XBlock
xblock/fields.py
Field._is_dirty
def _is_dirty(self, xblock): """ Return whether this field should be saved when xblock.save() is called """ # pylint: disable=protected-access if self not in xblock._dirty_fields: return False baseline = xblock._dirty_fields[self] return baseline is EXPLICITLY_SET or xblock._field_data_cache[self.name] != baseline
python
def _is_dirty(self, xblock): if self not in xblock._dirty_fields: return False baseline = xblock._dirty_fields[self] return baseline is EXPLICITLY_SET or xblock._field_data_cache[self.name] != baseline
[ "def", "_is_dirty", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "if", "self", "not", "in", "xblock", ".", "_dirty_fields", ":", "return", "False", "baseline", "=", "xblock", ".", "_dirty_fields", "[", "self", "]", "return", "baseline", "is", "EXPLICITLY_SET", "or", "xblock", ".", "_field_data_cache", "[", "self", ".", "name", "]", "!=", "baseline" ]
Return whether this field should be saved when xblock.save() is called
[ "Return", "whether", "this", "field", "should", "be", "saved", "when", "xblock", ".", "save", "()", "is", "called" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L426-L435
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: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning) """ if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: # pylint: disable=bare-except message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
python
def _check_or_enforce_type(self, value): if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
[ "def", "_check_or_enforce_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_enable_enforce_type", ":", "return", "self", ".", "enforce_type", "(", "value", ")", "try", ":", "new_value", "=", "self", ".", "enforce_type", "(", "value", ")", "except", ":", "# pylint: disable=bare-except", "message", "=", "\"The value {!r} could not be enforced ({})\"", ".", "format", "(", "value", ",", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", ")", "warnings", ".", "warn", "(", "message", ",", "FailingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "else", ":", "try", ":", "equal", "=", "value", "==", "new_value", "except", "TypeError", ":", "equal", "=", "False", "if", "not", "equal", ":", "message", "=", "\"The value {!r} would be enforced to {!r}\"", ".", "format", "(", "value", ",", "new_value", ")", "warnings", ".", "warn", "(", "message", ",", "ModifyingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "return", "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: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning)
[ "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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L443-L472
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.sha1(key.encode('utf-8')).hexdigest()
python
def _calculate_unique_id(self, xblock): key = scope_key(self, xblock) return hashlib.sha1(key.encode('utf-8')).hexdigest()
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L474-L482
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: if self._default is UNIQUE_ID: return self._check_or_enforce_type(self._calculate_unique_id(xblock)) else: return self.default
python
def _get_default_value_to_cache(self, xblock): try: return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: if self._default is UNIQUE_ID: return self._check_or_enforce_type(self._calculate_unique_id(xblock)) else: return self.default
[ "def", "_get_default_value_to_cache", "(", "self", ",", "xblock", ")", ":", "try", ":", "# pylint: disable=protected-access", "return", "self", ".", "from_json", "(", "xblock", ".", "_field_data", ".", "default", "(", "xblock", ",", "self", ".", "name", ")", ")", "except", "KeyError", ":", "if", "self", ".", "_default", "is", "UNIQUE_ID", ":", "return", "self", ".", "_check_or_enforce_type", "(", "self", ".", "_calculate_unique_id", "(", "xblock", ")", ")", "else", ":", "return", "self", ".", "default" ]
Perform special logic to provide a field's default value for caching.
[ "Perform", "special", "logic", "to", "provide", "a", "field", "s", "default", "value", "for", "caching", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L484-L495
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.warn( "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name), DeprecationWarning, stacklevel=3 ) self.warned = True
python
def _warn_deprecated_outside_JSONField(self): if not isinstance(self, JSONField) and not self.warned: warnings.warn( "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name), DeprecationWarning, stacklevel=3 ) self.warned = True
[ "def", "_warn_deprecated_outside_JSONField", "(", "self", ")", ":", "# pylint: disable=invalid-name", "if", "not", "isinstance", "(", "self", ",", "JSONField", ")", "and", "not", "self", ".", "warned", ":", "warnings", ".", "warn", "(", "\"Deprecated. JSONifiable fields should derive from JSONField ({name})\"", ".", "format", "(", "name", "=", "self", ".", "name", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "self", ".", "warned", "=", "True" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L589-L601
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=(',', ': '), ) return value
python
def to_string(self, value): self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "value", "=", "json", ".", "dumps", "(", "self", ".", "to_json", "(", "value", ")", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ",", ")", "return", "value" ]
Return a JSON serialized string representation of the value.
[ "Return", "a", "JSON", "serialized", "string", "representation", "of", "the", "value", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L624-L635
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 self.enforce_type(value)
python
def from_string(self, serialized): self._warn_deprecated_outside_JSONField() value = yaml.safe_load(serialized) return self.enforce_type(value)
[ "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", ".", ")" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L637-L644
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): 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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L664-L669
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 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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L683-L688
edx/XBlock
xblock/fields.py
Dict.to_string
def to_string(self, value): """ In python3, json.dumps() cannot sort keys of different types, so preconvert None to 'null'. """ self.enforce_type(value) if isinstance(value, dict) and None in value: value = value.copy() value['null'] = value[None] del value[None] return super(Dict, self).to_string(value)
python
def to_string(self, value): self.enforce_type(value) if isinstance(value, dict) and None in value: value = value.copy() value['null'] = value[None] del value[None] return super(Dict, self).to_string(value)
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "self", ".", "enforce_type", "(", "value", ")", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "None", "in", "value", ":", "value", "=", "value", ".", "copy", "(", ")", "value", "[", "'null'", "]", "=", "value", "[", "None", "]", "del", "value", "[", "None", "]", "return", "super", "(", "Dict", ",", "self", ")", ".", "to_string", "(", "value", ")" ]
In python3, json.dumps() cannot sort keys of different types, so preconvert None to 'null'.
[ "In", "python3", "json", ".", "dumps", "()", "cannot", "sort", "keys", "of", "different", "types", "so", "preconvert", "None", "to", "null", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L799-L809
edx/XBlock
xblock/fields.py
String._sanitize
def _sanitize(self, value): """ Remove the control characters that are not allowed in XML: https://www.w3.org/TR/xml/#charsets Leave all other characters. """ if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): new_value = ''.join(ch for ch in value if self._valid_char(ch)) else: return value # The new string will be equivalent to the original string if no control characters are present. # If equivalent, return the original string - some tests check for object equality instead of string equality. return value if value == new_value else new_value
python
def _sanitize(self, value): if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): new_value = ''.join(ch for ch in value if self._valid_char(ch)) else: return value return value if value == new_value else new_value
[ "def", "_sanitize", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "new_value", "=", "''", ".", "join", "(", "ch", "for", "ch", "in", "value", "if", "self", ".", "_valid_char", "(", "ch", ")", ")", "else", ":", "return", "value", "# The new string will be equivalent to the original string if no control characters are present.", "# If equivalent, return the original string - some tests check for object equality instead of string equality.", "return", "value", "if", "value", "==", "new_value", "else", "new_value" ]
Remove the control characters that are not allowed in XML: https://www.w3.org/TR/xml/#charsets Leave all other characters.
[ "Remove", "the", "control", "characters", "that", "are", "not", "allowed", "in", "XML", ":", "https", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "xml", "/", "#charsets", "Leave", "all", "other", "characters", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L874-L888
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): 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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L904-L908
edx/XBlock
xblock/fields.py
XMLString.to_json
def to_json(self, value): """ Serialize the data, ensuring that it is valid XML (or None). Raises an lxml.etree.XMLSyntaxError if it is a basestring but not valid XML. """ if self._enable_enforce_type: value = self.enforce_type(value) return super(XMLString, self).to_json(value)
python
def to_json(self, value): if self._enable_enforce_type: value = self.enforce_type(value) return super(XMLString, self).to_json(value)
[ "def", "to_json", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_enable_enforce_type", ":", "value", "=", "self", ".", "enforce_type", "(", "value", ")", "return", "super", "(", "XMLString", ",", "self", ")", ".", "to_json", "(", "value", ")" ]
Serialize the data, ensuring that it is valid XML (or None). Raises an lxml.etree.XMLSyntaxError if it is a basestring but not valid XML.
[ "Serialize", "the", "data", "ensuring", "that", "it", "is", "valid", "XML", "(", "or", "None", ")", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L927-L936
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): # Parser interprets empty string as now by default if value == "": return None try: value = dateutil.parser.parse(value) except (TypeError, ValueError): raise ValueError("Could not parse {} as a date".format(value)) if not isinstance(value, datetime.datetime): raise TypeError( "Value should be loaded from a string, a datetime object or None, not {}".format(type(value)) ) if value.tzinfo is not None: # pylint: disable=maybe-no-member return value.astimezone(pytz.utc) # pylint: disable=maybe-no-member else: return value.replace(tzinfo=pytz.utc)
python
def from_json(self, value): if value is None: return None if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): if value == "": return None try: value = dateutil.parser.parse(value) except (TypeError, ValueError): raise ValueError("Could not parse {} as a date".format(value)) if not isinstance(value, datetime.datetime): raise TypeError( "Value should be loaded from a string, a datetime object or None, not {}".format(type(value)) ) if value.tzinfo is not None: return value.astimezone(pytz.utc) else: return value.replace(tzinfo=pytz.utc)
[ "def", "from_json", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "# Parser interprets empty string as now by default", "if", "value", "==", "\"\"", ":", "return", "None", "try", ":", "value", "=", "dateutil", ".", "parser", ".", "parse", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Could not parse {} as a date\"", ".", "format", "(", "value", ")", ")", "if", "not", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"Value should be loaded from a string, a datetime object or None, not {}\"", ".", "format", "(", "type", "(", "value", ")", ")", ")", "if", "value", ".", "tzinfo", "is", "not", "None", ":", "# pylint: disable=maybe-no-member", "return", "value", ".", "astimezone", "(", "pytz", ".", "utc", ")", "# pylint: disable=maybe-no-member", "else", ":", "return", "value", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")" ]
Parse the date from an ISO-formatted date string, or None.
[ "Parse", "the", "date", "from", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L954-L981
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 a datetime object, not {}".format(type(value)))
python
def to_json(self, value): if isinstance(value, datetime.datetime): return value.strftime(self.DATETIME_FORMAT) if value is None: return None raise TypeError("Value stored must be a datetime object, not {}".format(type(value)))
[ "def", "to_json", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "strftime", "(", "self", ".", "DATETIME_FORMAT", ")", "if", "value", "is", "None", ":", "return", "None", "raise", "TypeError", "(", "\"Value stored must be a datetime object, not {}\"", ".", "format", "(", "type", "(", "value", ")", ")", ")" ]
Serialize the date as an ISO-formatted date string, or None.
[ "Serialize", "the", "date", "as", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L983-L991
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, globs) # pylint: disable=W0122 return globs
python
def run_script(pycode): if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) globs = {} six.exec_(pycode, globs, globs) return globs
[ "def", "run_script", "(", "pycode", ")", ":", "# 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", ",", "globs", ")", "# pylint: disable=W0122", "return", "globs" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/run_script.py#L12-L24
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 to this method. The XBlock must parse this URI and return an open file-like object for the resource. For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to "public". The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource. """ if isinstance(uri, six.binary_type): uri = uri.decode('utf-8') # If no resources_dir is set, then this XBlock cannot serve local resources. if cls.resources_dir is None: raise DisallowedFileError("This XBlock is not configured to serve local resources") # Make sure the path starts with whatever public_dir is set to. if not uri.startswith(cls.public_dir + '/'): raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri)) # Disalow paths that have a '/.' component, as `/./` is a no-op and `/../` # can be used to recurse back past the entry point of this XBlock. if "/." in uri: raise DisallowedFileError("Only safe file names are allowed: %r" % uri) return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri))
python
def open_local_resource(cls, uri): if isinstance(uri, six.binary_type): uri = uri.decode('utf-8') if cls.resources_dir is None: raise DisallowedFileError("This XBlock is not configured to serve local resources") if not uri.startswith(cls.public_dir + '/'): raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri)) if "/." in uri: raise DisallowedFileError("Only safe file names are allowed: %r" % uri) return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri))
[ "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 resources.", "if", "cls", ".", "resources_dir", "is", "None", ":", "raise", "DisallowedFileError", "(", "\"This XBlock is not configured to serve local resources\"", ")", "# Make sure the path starts with whatever public_dir is set to.", "if", "not", "uri", ".", "startswith", "(", "cls", ".", "public_dir", "+", "'/'", ")", ":", "raise", "DisallowedFileError", "(", "\"Only files from %r/ are allowed: %r\"", "%", "(", "cls", ".", "public_dir", ",", "uri", ")", ")", "# Disalow paths that have a '/.' component, as `/./` is a no-op and `/../`", "# can be used to recurse back past the entry point of this XBlock.", "if", "\"/.\"", "in", "uri", ":", "raise", "DisallowedFileError", "(", "\"Only safe file names are allowed: %r\"", "%", "uri", ")", "return", "pkg_resources", ".", "resource_stream", "(", "cls", ".", "__module__", ",", "os", ".", "path", ".", "join", "(", "cls", ".", "resources_dir", ",", "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 to this method. The XBlock must parse this URI and return an open file-like object for the resource. For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to "public". The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource.
[ "Open", "a", "local", "resource", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L79-L115
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): class_tags = set() for base in cls.mro()[1:]: 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", "(", "getattr", "(", "base", ",", "'_class_tags'", ",", "set", "(", ")", ")", ")", "return", "class_tags" ]
Collect the tags from all base classes.
[ "Collect", "the", "tags", "from", "all", "base", "classes", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L135-L144
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: disable=protected-access return cls return dec
python
def tag(tags): def dec(cls): cls._class_tags.update(tags.replace(",", " ").split()) return cls return dec
[ "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", "(", "\",\"", ",", "\" \"", ")", ".", "split", "(", ")", ")", "# pylint: disable=protected-access", "return", "cls", "return", "dec" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L147-L154
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 installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag. """ # Allow this method to access the `_class_tags` # pylint: disable=W0212 for name, class_ in cls.load_classes(fail_silently): if tag in class_._class_tags: yield name, class_
python
def load_tagged_classes(cls, tag, fail_silently=True): for name, class_ in cls.load_classes(fail_silently): if tag in class_._class_tags: yield name, class_
[ "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", ")", ":", "if", "tag", "in", "class_", ".", "_class_tags", ":", "yield", "name", ",", "class_" ]
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. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.
[ "Produce", "a", "sequence", "of", "all", "XBlock", "classes", "tagged", "with", "tag", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L157-L174
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): 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" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L200-L202
edx/XBlock
xblock/core.py
XBlock.ugettext
def ugettext(self, text): """ Translates message/text and returns it in a unicode string. Using runtime to get i18n service. """ runtime_service = self.runtime.service(self, "i18n") runtime_ugettext = runtime_service.ugettext return runtime_ugettext(text)
python
def ugettext(self, text): runtime_service = self.runtime.service(self, "i18n") runtime_ugettext = runtime_service.ugettext return runtime_ugettext(text)
[ "def", "ugettext", "(", "self", ",", "text", ")", ":", "runtime_service", "=", "self", ".", "runtime", ".", "service", "(", "self", ",", "\"i18n\"", ")", "runtime_ugettext", "=", "runtime_service", ".", "ugettext", "return", "runtime_ugettext", "(", "text", ")" ]
Translates message/text and returns it in a unicode string. Using runtime to get i18n service.
[ "Translates", "message", "/", "text", "and", "returns", "it", "in", "a", "unicode", "string", ".", "Using", "runtime", "to", "get", "i18n", "service", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L213-L220
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): super(XBlock, self).add_xml_to_node(node) 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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L222-L228
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): ... return Fragment(...) """ # pylint: disable=protected-access def _decorator(func): # pylint: disable=missing-docstring if not hasattr(func, '_aside_for'): func._aside_for = [] func._aside_for.append(view_name) # pylint: disable=protected-access return func return _decorator
python
def aside_for(cls, view_name): def _decorator(func): if not hasattr(func, '_aside_for'): func._aside_for = [] func._aside_for.append(view_name) return func return _decorator
[ "def", "aside_for", "(", "cls", ",", "view_name", ")", ":", "# pylint: disable=protected-access", "def", "_decorator", "(", "func", ")", ":", "# pylint: disable=missing-docstring", "if", "not", "hasattr", "(", "func", ",", "'_aside_for'", ")", ":", "func", ".", "_aside_for", "=", "[", "]", "func", ".", "_aside_for", ".", "append", "(", "view_name", ")", "# pylint: disable=protected-access", "return", "func", "return", "_decorator" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L239-L257
edx/XBlock
xblock/core.py
XBlockAside._combined_asides
def _combined_asides(cls): # pylint: disable=no-self-argument """ A dictionary mapping XBlock view names to the aside method that decorates them (or None, if there is no decorator for the specified view). """ # The method declares what views it decorates. We rely on `dir` # to handle subclasses and overrides. combined_asides = defaultdict(None) for _view_name, view_func in inspect.getmembers(cls, lambda attr: hasattr(attr, '_aside_for')): aside_for = getattr(view_func, '_aside_for', []) for view in aside_for: combined_asides[view] = view_func.__name__ return combined_asides
python
def _combined_asides(cls): combined_asides = defaultdict(None) for _view_name, view_func in inspect.getmembers(cls, lambda attr: hasattr(attr, '_aside_for')): aside_for = getattr(view_func, '_aside_for', []) for view in aside_for: combined_asides[view] = view_func.__name__ return combined_asides
[ "def", "_combined_asides", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "# The method declares what views it decorates. We rely on `dir`", "# to handle subclasses and overrides.", "combined_asides", "=", "defaultdict", "(", "None", ")", "for", "_view_name", ",", "view_func", "in", "inspect", ".", "getmembers", "(", "cls", ",", "lambda", "attr", ":", "hasattr", "(", "attr", ",", "'_aside_for'", ")", ")", ":", "aside_for", "=", "getattr", "(", "view_func", ",", "'_aside_for'", ",", "[", "]", ")", "for", "view", "in", "aside_for", ":", "combined_asides", "[", "view", "]", "=", "view_func", ".", "__name__", "return", "combined_asides" ]
A dictionary mapping XBlock view names to the aside method that decorates them (or None, if there is no decorator for the specified view).
[ "A", "dictionary", "mapping", "XBlock", "view", "names", "to", "the", "aside", "method", "that", "decorates", "them", "(", "or", "None", "if", "there", "is", "no", "decorator", "for", "the", "specified", "view", ")", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L268-L280
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: view_name (string): the name of the view requested. Returns: either the function or None """ if view_name in self._combined_asides: # pylint: disable=unsupported-membership-test return getattr(self, self._combined_asides[view_name]) # pylint: disable=unsubscriptable-object else: return None
python
def aside_view_declaration(self, view_name): if view_name in self._combined_asides: return getattr(self, self._combined_asides[view_name]) else: return None
[ "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", "[", "view_name", "]", ")", "# pylint: disable=unsubscriptable-object", "else", ":", "return", "None" ]
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. Returns: either the function or None
[ "Find", "and", "return", "a", "function", "object", "if", "one", "is", "an", "aside_view", "for", "the", "given", "view_name" ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L282-L298
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(self.fields))
python
def needs_serialization(self): return any(field.is_set_on(self) for field in six.itervalues(self.fields))
[ "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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L300-L307
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 must of type ValidationMessage") self.messages.append(message)
python
def add(self, message): if not isinstance(message, ValidationMessage): raise TypeError("Argument must of type ValidationMessage") self.messages.append(message)
[ "def", "add", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "ValidationMessage", ")", ":", "raise", "TypeError", "(", "\"Argument must of type ValidationMessage\"", ")", "self", ".", "messages", ".", "append", "(", "message", ")" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L87-L96
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(validation, Validation): raise TypeError("Argument must be of type Validation") self.messages.extend(validation.messages)
python
def add_messages(self, validation): if not isinstance(validation, Validation): raise TypeError("Argument must be of type Validation") self.messages.extend(validation.messages)
[ "def", "add_messages", "(", "self", ",", "validation", ")", ":", "if", "not", "isinstance", "(", "validation", ",", "Validation", ")", ":", "raise", "TypeError", "(", "\"Argument must be of type Validation\"", ")", "self", ".", "messages", ".", "extend", "(", "validation", ".", "messages", ")" ]
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", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L98-L109
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.messages], "empty": self.empty }
python
def to_json(self): return { "xblock_id": six.text_type(self.xblock_id), "messages": [message.to_json() for message in self.messages], "empty": self.empty }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "\"xblock_id\"", ":", "six", ".", "text_type", "(", "self", ".", "xblock_id", ")", ",", "\"messages\"", ":", "[", "message", ".", "to_json", "(", ")", "for", "message", "in", "self", ".", "messages", "]", ",", "\"empty\"", ":", "self", ".", "empty", "}" ]
Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable.
[ "Convert", "to", "a", "json", "-", "serializable", "representation", "." ]
train
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122
hmeine/qimage2ndarray
qimage2ndarray/qt_driver.py
QtDriver.requireCompatibleAPI
def requireCompatibleAPI(): """If PyQt4's API should be configured to be compatible with PySide's (i.e. QString and QVariant should not be explicitly exported, cf. documentation of sip.setapi()), call this function to check that the PyQt4 was properly imported. (It will always be configured this way by this module, but it could have been imported before we got a hand on doing so.) """ if 'PyQt4.QtCore' in sys.modules: import sip for api in ('QVariant', 'QString'): if sip.getapi(api) != 2: raise RuntimeError('%s API already set to V%d, but should be 2' % (api, sip.getapi(api)))
python
def requireCompatibleAPI(): if 'PyQt4.QtCore' in sys.modules: import sip for api in ('QVariant', 'QString'): if sip.getapi(api) != 2: raise RuntimeError('%s API already set to V%d, but should be 2' % (api, sip.getapi(api)))
[ "def", "requireCompatibleAPI", "(", ")", ":", "if", "'PyQt4.QtCore'", "in", "sys", ".", "modules", ":", "import", "sip", "for", "api", "in", "(", "'QVariant'", ",", "'QString'", ")", ":", "if", "sip", ".", "getapi", "(", "api", ")", "!=", "2", ":", "raise", "RuntimeError", "(", "'%s API already set to V%d, but should be 2'", "%", "(", "api", ",", "sip", ".", "getapi", "(", "api", ")", ")", ")" ]
If PyQt4's API should be configured to be compatible with PySide's (i.e. QString and QVariant should not be explicitly exported, cf. documentation of sip.setapi()), call this function to check that the PyQt4 was properly imported. (It will always be configured this way by this module, but it could have been imported before we got a hand on doing so.)
[ "If", "PyQt4", "s", "API", "should", "be", "configured", "to", "be", "compatible", "with", "PySide", "s", "(", "i", ".", "e", ".", "QString", "and", "QVariant", "should", "not", "be", "explicitly", "exported", "cf", ".", "documentation", "of", "sip", ".", "setapi", "()", ")", "call", "this", "function", "to", "check", "that", "the", "PyQt4", "was", "properly", "imported", ".", "(", "It", "will", "always", "be", "configured", "this", "way", "by", "this", "module", "but", "it", "could", "have", "been", "imported", "before", "we", "got", "a", "hand", "on", "doing", "so", ".", ")" ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/qt_driver.py#L103-L115
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
byte_view
def byte_view(qimage, byteorder = 'little'): """Returns raw 3D view of the given QImage_'s memory. This will always be a 3-dimensional numpy.ndarray with dtype numpy.uint8. Note that for 32-bit images, the last dimension will be in the [B,G,R,A] order (if little endian) due to QImage_'s memory layout (the alpha channel will be present for Format_RGB32 images, too). For 8-bit (indexed) images, the array will still be 3-dimensional, i.e. shape will be (height, width, 1). The order of channels in the last axis depends on the `byteorder`, which defaults to 'little', i.e. BGRA order. You may set the argument `byteorder` to 'big' to get ARGB, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ :param byteorder: specify order of channels in last axis :rtype: numpy.ndarray_ with shape (height, width, 1 or 4) and dtype uint8""" raw = _qimage_or_filename_view(qimage) result = raw.view(_np.uint8).reshape(raw.shape + (-1, )) if byteorder and byteorder != _sys.byteorder: result = result[...,::-1] return result
python
def byte_view(qimage, byteorder = 'little'): raw = _qimage_or_filename_view(qimage) result = raw.view(_np.uint8).reshape(raw.shape + (-1, )) if byteorder and byteorder != _sys.byteorder: result = result[...,::-1] return result
[ "def", "byte_view", "(", "qimage", ",", "byteorder", "=", "'little'", ")", ":", "raw", "=", "_qimage_or_filename_view", "(", "qimage", ")", "result", "=", "raw", ".", "view", "(", "_np", ".", "uint8", ")", ".", "reshape", "(", "raw", ".", "shape", "+", "(", "-", "1", ",", ")", ")", "if", "byteorder", "and", "byteorder", "!=", "_sys", ".", "byteorder", ":", "result", "=", "result", "[", "...", ",", ":", ":", "-", "1", "]", "return", "result" ]
Returns raw 3D view of the given QImage_'s memory. This will always be a 3-dimensional numpy.ndarray with dtype numpy.uint8. Note that for 32-bit images, the last dimension will be in the [B,G,R,A] order (if little endian) due to QImage_'s memory layout (the alpha channel will be present for Format_RGB32 images, too). For 8-bit (indexed) images, the array will still be 3-dimensional, i.e. shape will be (height, width, 1). The order of channels in the last axis depends on the `byteorder`, which defaults to 'little', i.e. BGRA order. You may set the argument `byteorder` to 'big' to get ARGB, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ :param byteorder: specify order of channels in last axis :rtype: numpy.ndarray_ with shape (height, width, 1 or 4) and dtype uint8
[ "Returns", "raw", "3D", "view", "of", "the", "given", "QImage_", "s", "memory", ".", "This", "will", "always", "be", "a", "3", "-", "dimensional", "numpy", ".", "ndarray", "with", "dtype", "numpy", ".", "uint8", ".", "Note", "that", "for", "32", "-", "bit", "images", "the", "last", "dimension", "will", "be", "in", "the", "[", "B", "G", "R", "A", "]", "order", "(", "if", "little", "endian", ")", "due", "to", "QImage_", "s", "memory", "layout", "(", "the", "alpha", "channel", "will", "be", "present", "for", "Format_RGB32", "images", "too", ")", "." ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L51-L79
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
rgb_view
def rgb_view(qimage, byteorder = 'big'): """Returns RGB view of a given 32-bit color QImage_'s memory. Similarly to byte_view(), the result is a 3D numpy.uint8 array, but reduced to the rgb dimensions (without alpha), and reordered (using negative strides in the last dimension) to have the usual [R,G,B] order. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. (Note that in the latter case, the values are of course premultiplied with alpha.) The order of channels in the last axis depends on the `byteorder`, which defaults to 'big', i.e. RGB order. You may set the argument `byteorder` to 'little' to get BGR, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :param byteorder: specify order of channels in last axis :rtype: numpy.ndarray_ with shape (height, width, 3) and dtype uint8""" if byteorder is None: byteorder = _sys.byteorder bytes = byte_view(qimage, byteorder) if bytes.shape[2] != 4: raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") if byteorder == 'little': return bytes[...,:3] # strip A off BGRA else: return bytes[...,1:]
python
def rgb_view(qimage, byteorder = 'big'): if byteorder is None: byteorder = _sys.byteorder bytes = byte_view(qimage, byteorder) if bytes.shape[2] != 4: raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") if byteorder == 'little': return bytes[...,:3] else: return bytes[...,1:]
[ "def", "rgb_view", "(", "qimage", ",", "byteorder", "=", "'big'", ")", ":", "if", "byteorder", "is", "None", ":", "byteorder", "=", "_sys", ".", "byteorder", "bytes", "=", "byte_view", "(", "qimage", ",", "byteorder", ")", "if", "bytes", ".", "shape", "[", "2", "]", "!=", "4", ":", "raise", "ValueError", "(", "\"For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)\"", ")", "if", "byteorder", "==", "'little'", ":", "return", "bytes", "[", "...", ",", ":", "3", "]", "# strip A off BGRA", "else", ":", "return", "bytes", "[", "...", ",", "1", ":", "]" ]
Returns RGB view of a given 32-bit color QImage_'s memory. Similarly to byte_view(), the result is a 3D numpy.uint8 array, but reduced to the rgb dimensions (without alpha), and reordered (using negative strides in the last dimension) to have the usual [R,G,B] order. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. (Note that in the latter case, the values are of course premultiplied with alpha.) The order of channels in the last axis depends on the `byteorder`, which defaults to 'big', i.e. RGB order. You may set the argument `byteorder` to 'little' to get BGR, or use None which means sys.byteorder here, i.e. return native order for the machine the code is running on. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :param byteorder: specify order of channels in last axis :rtype: numpy.ndarray_ with shape (height, width, 3) and dtype uint8
[ "Returns", "RGB", "view", "of", "a", "given", "32", "-", "bit", "color", "QImage_", "s", "memory", ".", "Similarly", "to", "byte_view", "()", "the", "result", "is", "a", "3D", "numpy", ".", "uint8", "array", "but", "reduced", "to", "the", "rgb", "dimensions", "(", "without", "alpha", ")", "and", "reordered", "(", "using", "negative", "strides", "in", "the", "last", "dimension", ")", "to", "have", "the", "usual", "[", "R", "G", "B", "]", "order", ".", "The", "image", "must", "have", "32", "bit", "pixel", "size", "i", ".", "e", ".", "be", "RGB32", "ARGB32", "or", "ARGB32_Premultiplied", ".", "(", "Note", "that", "in", "the", "latter", "case", "the", "values", "are", "of", "course", "premultiplied", "with", "alpha", ".", ")" ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L82-L113
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
alpha_view
def alpha_view(qimage): """Returns alpha view of a given 32-bit color QImage_'s memory. The result is a 2D numpy.uint8 array, equivalent to byte_view(qimage)[...,3]. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is not enforced that the given qimage has a format that actually *uses* the alpha channel -- for Format_RGB32, the alpha channel usually contains 255 everywhere. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype uint8""" bytes = byte_view(qimage, byteorder = None) if bytes.shape[2] != 4: raise ValueError("For alpha_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") return bytes[...,_bgra[3]]
python
def alpha_view(qimage): bytes = byte_view(qimage, byteorder = None) if bytes.shape[2] != 4: raise ValueError("For alpha_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") return bytes[...,_bgra[3]]
[ "def", "alpha_view", "(", "qimage", ")", ":", "bytes", "=", "byte_view", "(", "qimage", ",", "byteorder", "=", "None", ")", "if", "bytes", ".", "shape", "[", "2", "]", "!=", "4", ":", "raise", "ValueError", "(", "\"For alpha_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)\"", ")", "return", "bytes", "[", "...", ",", "_bgra", "[", "3", "]", "]" ]
Returns alpha view of a given 32-bit color QImage_'s memory. The result is a 2D numpy.uint8 array, equivalent to byte_view(qimage)[...,3]. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is not enforced that the given qimage has a format that actually *uses* the alpha channel -- for Format_RGB32, the alpha channel usually contains 255 everywhere. For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype uint8
[ "Returns", "alpha", "view", "of", "a", "given", "32", "-", "bit", "color", "QImage_", "s", "memory", ".", "The", "result", "is", "a", "2D", "numpy", ".", "uint8", "array", "equivalent", "to", "byte_view", "(", "qimage", ")", "[", "...", "3", "]", ".", "The", "image", "must", "have", "32", "bit", "pixel", "size", "i", ".", "e", ".", "be", "RGB32", "ARGB32", "or", "ARGB32_Premultiplied", ".", "Note", "that", "it", "is", "not", "enforced", "that", "the", "given", "qimage", "has", "a", "format", "that", "actually", "*", "uses", "*", "the", "alpha", "channel", "--", "for", "Format_RGB32", "the", "alpha", "channel", "usually", "contains", "255", "everywhere", "." ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L116-L134
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 indexing or via attribute lookup (through numpy.recarray_): For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. >>> from PyQt4.QtGui import QImage, qRgb >>> qimg = QImage(320, 240, QImage.Format_ARGB32) >>> qimg.fill(qRgb(12,34,56)) >>> >>> import qimage2ndarray >>> v = qimage2ndarray.recarray_view(qimg) >>> >>> red = v["r"] >>> red[10,10] 12 >>> pixel = v[10,10] >>> pixel["r"] 12 >>> (v.g == v["g"]).all() True >>> (v.alpha == 255).all() True :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`""" 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_Premultiplied)") return raw.view(bgra_dtype, _np.recarray)
python
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_Premultiplied)") return raw.view(bgra_dtype, _np.recarray)
[ "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_Premultiplied)\"", ")", "return", "raw", ".", "view", "(", "bgra_dtype", ",", "_np", ".", "recarray", ")" ]
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 numpy.recarray_): For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. >>> from PyQt4.QtGui import QImage, qRgb >>> qimg = QImage(320, 240, QImage.Format_ARGB32) >>> qimg.fill(qRgb(12,34,56)) >>> >>> import qimage2ndarray >>> v = qimage2ndarray.recarray_view(qimg) >>> >>> red = v["r"] >>> red[10,10] 12 >>> pixel = v[10,10] >>> pixel["r"] 12 >>> (v.g == v["g"]).all() True >>> (v.alpha == 255).all() True :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`
[ "Returns", "recarray_", "view", "of", "a", "given", "32", "-", "bit", "color", "QImage_", "s", "memory", "." ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L137-L173
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, nmax): scale & clip image values from nmin..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (gray.min(), gray.max())) If the source array `gray` contains masked values, the result will have only 255 shades of gray, and one color map entry will be used to make the corresponding pixels transparent. A full alpha channel cannot be supported with indexed images; instead, use `array2qimage` to convert into a 32-bit QImage. :param gray: image data which should be converted (copied) into a QImage_ :type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format""" if _np.ndim(gray) != 2: raise ValueError("gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np.ndim(gray) == 3 else "") h, w = gray.shape result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8) if not _np.ma.is_masked(gray): for i in range(256): result.setColor(i, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize) else: # map gray value 1 to gray value 0, in order to make room for # transparent colormap entry: result.setColor(0, _qt.qRgb(0,0,0)) for i in range(2, 256): result.setColor(i-1, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1 result.setColor(255, 0) _qimageview(result)[gray.mask] = 255 return result
python
def gray2qimage(gray, normalize = False): if _np.ndim(gray) != 2: raise ValueError("gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np.ndim(gray) == 3 else "") h, w = gray.shape result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8) if not _np.ma.is_masked(gray): for i in range(256): result.setColor(i, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize) else: result.setColor(0, _qt.qRgb(0,0,0)) for i in range(2, 256): result.setColor(i-1, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1 result.setColor(255, 0) _qimageview(result)[gray.mask] = 255 return result
[ "def", "gray2qimage", "(", "gray", ",", "normalize", "=", "False", ")", ":", "if", "_np", ".", "ndim", "(", "gray", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"gray2QImage can only convert 2D arrays\"", "+", "\" (try using array2qimage)\"", "if", "_np", ".", "ndim", "(", "gray", ")", "==", "3", "else", "\"\"", ")", "h", ",", "w", "=", "gray", ".", "shape", "result", "=", "_qt", ".", "QImage", "(", "w", ",", "h", ",", "_qt", ".", "QImage", ".", "Format_Indexed8", ")", "if", "not", "_np", ".", "ma", ".", "is_masked", "(", "gray", ")", ":", "for", "i", "in", "range", "(", "256", ")", ":", "result", ".", "setColor", "(", "i", ",", "_qt", ".", "qRgb", "(", "i", ",", "i", ",", "i", ")", ")", "_qimageview", "(", "result", ")", "[", ":", "]", "=", "_normalize255", "(", "gray", ",", "normalize", ")", "else", ":", "# map gray value 1 to gray value 0, in order to make room for", "# transparent colormap entry:", "result", ".", "setColor", "(", "0", ",", "_qt", ".", "qRgb", "(", "0", ",", "0", ",", "0", ")", ")", "for", "i", "in", "range", "(", "2", ",", "256", ")", ":", "result", ".", "setColor", "(", "i", "-", "1", ",", "_qt", ".", "qRgb", "(", "i", ",", "i", ",", "i", ")", ")", "_qimageview", "(", "result", ")", "[", ":", "]", "=", "_normalize255", "(", "gray", ",", "normalize", ",", "clip", "=", "(", "1", ",", "255", ")", ")", "-", "1", "result", ".", "setColor", "(", "255", ",", "0", ")", "_qimageview", "(", "result", ")", "[", "gray", ".", "mask", "]", "=", "255", "return", "result" ]
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..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (gray.min(), gray.max())) If the source array `gray` contains masked values, the result will have only 255 shades of gray, and one color map entry will be used to make the corresponding pixels transparent. A full alpha channel cannot be supported with indexed images; instead, use `array2qimage` to convert into a 32-bit QImage. :param gray: image data which should be converted (copied) into a QImage_ :type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format
[ "Convert", "the", "2D", "numpy", "array", "gray", "into", "a", "8", "-", "bit", "indexed", "QImage_", "with", "a", "gray", "colormap", ".", "The", "first", "dimension", "represents", "the", "vertical", "image", "axis", "." ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L203-L258
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
array2qimage
def array2qimage(array, normalize = False): """Convert a 2D or 3D numpy array into a 32-bit QImage_. The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels: ========= =================== #channels interpretation ========= =================== 1 scalar/gray 2 scalar/gray + alpha 3 RGB 4 RGB + alpha ========= =================== Scalar data will be converted into corresponding gray RGB triples; if you want to convert to an (indexed) 8-bit image instead, use `gray2qimage` (which cannot support an alpha channel though). 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..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (array.min(), array.max())) If `array` contains masked values, the corresponding pixels will be transparent in the result. Thus, the result will be of QImage.Format_ARGB32 if the input already contains an alpha channel (i.e. has shape (H,W,4)) or if there are masked pixels, and QImage.Format_RGB32 otherwise. :param array: image data which should be converted (copied) into a QImage_ :type array: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format""" if _np.ndim(array) == 2: array = array[...,None] elif _np.ndim(array) != 3: raise ValueError("array2qimage can only convert 2D or 3D arrays (got %d dimensions)" % _np.ndim(array)) if array.shape[2] not in (1, 2, 3, 4): raise ValueError("array2qimage expects the last dimension to contain exactly one (scalar/gray), two (gray+alpha), three (R,G,B), or four (R,G,B,A) channels") h, w, channels = array.shape hasAlpha = _np.ma.is_masked(array) or channels in (2, 4) fmt = _qt.QImage.Format_ARGB32 if hasAlpha else _qt.QImage.Format_RGB32 result = _qt.QImage(w, h, fmt) array = _normalize255(array, normalize) if channels >= 3: rgb_view(result)[:] = array[...,:3] else: rgb_view(result)[:] = array[...,:1] # scalar data alpha = alpha_view(result) if channels in (2, 4): alpha[:] = array[...,-1] else: alpha[:] = 255 if _np.ma.is_masked(array): alpha[:] *= _np.logical_not(_np.any(array.mask, axis = -1)) return result
python
def array2qimage(array, normalize = False): if _np.ndim(array) == 2: array = array[...,None] elif _np.ndim(array) != 3: raise ValueError("array2qimage can only convert 2D or 3D arrays (got %d dimensions)" % _np.ndim(array)) if array.shape[2] not in (1, 2, 3, 4): raise ValueError("array2qimage expects the last dimension to contain exactly one (scalar/gray), two (gray+alpha), three (R,G,B), or four (R,G,B,A) channels") h, w, channels = array.shape hasAlpha = _np.ma.is_masked(array) or channels in (2, 4) fmt = _qt.QImage.Format_ARGB32 if hasAlpha else _qt.QImage.Format_RGB32 result = _qt.QImage(w, h, fmt) array = _normalize255(array, normalize) if channels >= 3: rgb_view(result)[:] = array[...,:3] else: rgb_view(result)[:] = array[...,:1] alpha = alpha_view(result) if channels in (2, 4): alpha[:] = array[...,-1] else: alpha[:] = 255 if _np.ma.is_masked(array): alpha[:] *= _np.logical_not(_np.any(array.mask, axis = -1)) return result
[ "def", "array2qimage", "(", "array", ",", "normalize", "=", "False", ")", ":", "if", "_np", ".", "ndim", "(", "array", ")", "==", "2", ":", "array", "=", "array", "[", "...", ",", "None", "]", "elif", "_np", ".", "ndim", "(", "array", ")", "!=", "3", ":", "raise", "ValueError", "(", "\"array2qimage can only convert 2D or 3D arrays (got %d dimensions)\"", "%", "_np", ".", "ndim", "(", "array", ")", ")", "if", "array", ".", "shape", "[", "2", "]", "not", "in", "(", "1", ",", "2", ",", "3", ",", "4", ")", ":", "raise", "ValueError", "(", "\"array2qimage expects the last dimension to contain exactly one (scalar/gray), two (gray+alpha), three (R,G,B), or four (R,G,B,A) channels\"", ")", "h", ",", "w", ",", "channels", "=", "array", ".", "shape", "hasAlpha", "=", "_np", ".", "ma", ".", "is_masked", "(", "array", ")", "or", "channels", "in", "(", "2", ",", "4", ")", "fmt", "=", "_qt", ".", "QImage", ".", "Format_ARGB32", "if", "hasAlpha", "else", "_qt", ".", "QImage", ".", "Format_RGB32", "result", "=", "_qt", ".", "QImage", "(", "w", ",", "h", ",", "fmt", ")", "array", "=", "_normalize255", "(", "array", ",", "normalize", ")", "if", "channels", ">=", "3", ":", "rgb_view", "(", "result", ")", "[", ":", "]", "=", "array", "[", "...", ",", ":", "3", "]", "else", ":", "rgb_view", "(", "result", ")", "[", ":", "]", "=", "array", "[", "...", ",", ":", "1", "]", "# scalar data", "alpha", "=", "alpha_view", "(", "result", ")", "if", "channels", "in", "(", "2", ",", "4", ")", ":", "alpha", "[", ":", "]", "=", "array", "[", "...", ",", "-", "1", "]", "else", ":", "alpha", "[", ":", "]", "=", "255", "if", "_np", ".", "ma", ".", "is_masked", "(", "array", ")", ":", "alpha", "[", ":", "]", "*=", "_np", ".", "logical_not", "(", "_np", ".", "any", "(", "array", ".", "mask", ",", "axis", "=", "-", "1", ")", ")", "return", "result" ]
Convert a 2D or 3D numpy array into a 32-bit QImage_. The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels: ========= =================== #channels interpretation ========= =================== 1 scalar/gray 2 scalar/gray + alpha 3 RGB 4 RGB + alpha ========= =================== Scalar data will be converted into corresponding gray RGB triples; if you want to convert to an (indexed) 8-bit image instead, use `gray2qimage` (which cannot support an alpha channel though). 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..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (array.min(), array.max())) If `array` contains masked values, the corresponding pixels will be transparent in the result. Thus, the result will be of QImage.Format_ARGB32 if the input already contains an alpha channel (i.e. has shape (H,W,4)) or if there are masked pixels, and QImage.Format_RGB32 otherwise. :param array: image data which should be converted (copied) into a QImage_ :type array: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format
[ "Convert", "a", "2D", "or", "3D", "numpy", "array", "into", "a", "32", "-", "bit", "QImage_", ".", "The", "first", "dimension", "represents", "the", "vertical", "image", "axis", ";", "the", "optional", "third", "dimension", "is", "supposed", "to", "contain", "1", "-", "4", "channels", ":" ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L261-L335
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
imread
def imread(filename, masked = False): """Convenience function that uses the QImage_ constructor to read an image from the given file and return an `rgb_view` of the result. This is intentionally similar to scipy.ndimage.imread (which uses PIL), scipy.misc.imread, or matplotlib.pyplot.imread (using PIL for non-PNGs). For grayscale images, return 2D array (even if it comes from a 32-bit representation; this is a consequence of the QImage API). For images with an alpha channel, the resulting number of channels will be 2 (grayscale+alpha) or 4 (RGB+alpha). Alternatively, one may pass `masked = True` in order to get `masked arrays`_ back. Note that only fully transparent pixels are masked (and that masked arrays only support binary masks). The value of `masked` is ignored when the loaded image has no alpha channel (i.e., one would not get a masked array in that case). This function has been added in version 1.3. """ qImage = _qt.QImage(filename) if qImage.isNull(): raise IOError('loading %r failed' % filename) isGray = qImage.isGrayscale() if isGray and qImage.depth() == 8: return byte_view(qImage)[...,0] hasAlpha = qImage.hasAlphaChannel() if hasAlpha: targetFormat = _qt.QImage.Format_ARGB32 else: targetFormat = _qt.QImage.Format_RGB32 if qImage.format() != targetFormat: qImage = qImage.convertToFormat(targetFormat) result = rgb_view(qImage) if isGray: result = result[...,0] if hasAlpha: if masked: mask = (alpha_view(qImage) == 0) if _np.ndim(result) == 3: mask = _np.repeat(mask[...,None], 3, axis = 2) result = _np.ma.masked_array(result, mask) else: result = _np.dstack((result, alpha_view(qImage))) return result
python
def imread(filename, masked = False): qImage = _qt.QImage(filename) if qImage.isNull(): raise IOError('loading %r failed' % filename) isGray = qImage.isGrayscale() if isGray and qImage.depth() == 8: return byte_view(qImage)[...,0] hasAlpha = qImage.hasAlphaChannel() if hasAlpha: targetFormat = _qt.QImage.Format_ARGB32 else: targetFormat = _qt.QImage.Format_RGB32 if qImage.format() != targetFormat: qImage = qImage.convertToFormat(targetFormat) result = rgb_view(qImage) if isGray: result = result[...,0] if hasAlpha: if masked: mask = (alpha_view(qImage) == 0) if _np.ndim(result) == 3: mask = _np.repeat(mask[...,None], 3, axis = 2) result = _np.ma.masked_array(result, mask) else: result = _np.dstack((result, alpha_view(qImage))) return result
[ "def", "imread", "(", "filename", ",", "masked", "=", "False", ")", ":", "qImage", "=", "_qt", ".", "QImage", "(", "filename", ")", "if", "qImage", ".", "isNull", "(", ")", ":", "raise", "IOError", "(", "'loading %r failed'", "%", "filename", ")", "isGray", "=", "qImage", ".", "isGrayscale", "(", ")", "if", "isGray", "and", "qImage", ".", "depth", "(", ")", "==", "8", ":", "return", "byte_view", "(", "qImage", ")", "[", "...", ",", "0", "]", "hasAlpha", "=", "qImage", ".", "hasAlphaChannel", "(", ")", "if", "hasAlpha", ":", "targetFormat", "=", "_qt", ".", "QImage", ".", "Format_ARGB32", "else", ":", "targetFormat", "=", "_qt", ".", "QImage", ".", "Format_RGB32", "if", "qImage", ".", "format", "(", ")", "!=", "targetFormat", ":", "qImage", "=", "qImage", ".", "convertToFormat", "(", "targetFormat", ")", "result", "=", "rgb_view", "(", "qImage", ")", "if", "isGray", ":", "result", "=", "result", "[", "...", ",", "0", "]", "if", "hasAlpha", ":", "if", "masked", ":", "mask", "=", "(", "alpha_view", "(", "qImage", ")", "==", "0", ")", "if", "_np", ".", "ndim", "(", "result", ")", "==", "3", ":", "mask", "=", "_np", ".", "repeat", "(", "mask", "[", "...", ",", "None", "]", ",", "3", ",", "axis", "=", "2", ")", "result", "=", "_np", ".", "ma", ".", "masked_array", "(", "result", ",", "mask", ")", "else", ":", "result", "=", "_np", ".", "dstack", "(", "(", "result", ",", "alpha_view", "(", "qImage", ")", ")", ")", "return", "result" ]
Convenience function that uses the QImage_ constructor to read an image from the given file and return an `rgb_view` of the result. This is intentionally similar to scipy.ndimage.imread (which uses PIL), scipy.misc.imread, or matplotlib.pyplot.imread (using PIL for non-PNGs). For grayscale images, return 2D array (even if it comes from a 32-bit representation; this is a consequence of the QImage API). For images with an alpha channel, the resulting number of channels will be 2 (grayscale+alpha) or 4 (RGB+alpha). Alternatively, one may pass `masked = True` in order to get `masked arrays`_ back. Note that only fully transparent pixels are masked (and that masked arrays only support binary masks). The value of `masked` is ignored when the loaded image has no alpha channel (i.e., one would not get a masked array in that case). This function has been added in version 1.3.
[ "Convenience", "function", "that", "uses", "the", "QImage_", "constructor", "to", "read", "an", "image", "from", "the", "given", "file", "and", "return", "an", "rgb_view", "of", "the", "result", ".", "This", "is", "intentionally", "similar", "to", "scipy", ".", "ndimage", ".", "imread", "(", "which", "uses", "PIL", ")", "scipy", ".", "misc", ".", "imread", "or", "matplotlib", ".", "pyplot", ".", "imread", "(", "using", "PIL", "for", "non", "-", "PNGs", ")", "." ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L338-L388
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
imsave
def imsave(filename, image, normalize = False, format = None, quality = -1): """Convenience function that uses QImage.save to save an image to the given file. This is intentionally similar to scipy.misc.imsave. However, it supports different optional arguments: :param normalize: see :func:`array2qimage` (which is used internally) :param format: image filetype (e.g. 'PNG'), (default: check filename's suffix) :param quality: see QImage.save (0 = small .. 100 = uncompressed, -1 = default compression) :returns: boolean success, see QImage.save This function has been added in version 1.4. """ qImage = array2qimage(image, normalize = normalize) return qImage.save(filename, format, quality)
python
def imsave(filename, image, normalize = False, format = None, quality = -1): qImage = array2qimage(image, normalize = normalize) return qImage.save(filename, format, quality)
[ "def", "imsave", "(", "filename", ",", "image", ",", "normalize", "=", "False", ",", "format", "=", "None", ",", "quality", "=", "-", "1", ")", ":", "qImage", "=", "array2qimage", "(", "image", ",", "normalize", "=", "normalize", ")", "return", "qImage", ".", "save", "(", "filename", ",", "format", ",", "quality", ")" ]
Convenience function that uses QImage.save to save an image to the given file. This is intentionally similar to scipy.misc.imsave. However, it supports different optional arguments: :param normalize: see :func:`array2qimage` (which is used internally) :param format: image filetype (e.g. 'PNG'), (default: check filename's suffix) :param quality: see QImage.save (0 = small .. 100 = uncompressed, -1 = default compression) :returns: boolean success, see QImage.save This function has been added in version 1.4.
[ "Convenience", "function", "that", "uses", "QImage", ".", "save", "to", "save", "an", "image", "to", "the", "given", "file", ".", "This", "is", "intentionally", "similar", "to", "scipy", ".", "misc", ".", "imsave", ".", "However", "it", "supports", "different", "optional", "arguments", ":" ]
train
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L391-L404
ampl/amplpy
amplpy/ampl.py
AMPL.getData
def getData(self, *statements): """ Get the data corresponding to the display statements. The statements can be AMPL expressions, or entities. It captures the equivalent of the command: .. code-block:: ampl display ds1, ..., dsn; where ds1, ..., dsn are the ``displayStatements`` with which the function is called. As only one DataFrame is returned, the operation will fail if the results of the display statements cannot be indexed over the same set. As a result, any attempt to get data from more than one set, or to get data for multiple parameters with a different number of indexing sets will fail. Args: statements: The display statements to be fetched. Raises: RuntimeError: if the AMPL visualization command does not succeed for one of the reasons listed above. Returns: DataFrame capturing the output of the display command in tabular form. """ # FIXME: only works for the first statement. return lock_and_call( lambda: DataFrame._fromDataFrameRef( self._impl.getData(list(statements), len(statements)) ), self._lock )
python
def getData(self, *statements): return lock_and_call( lambda: DataFrame._fromDataFrameRef( self._impl.getData(list(statements), len(statements)) ), self._lock )
[ "def", "getData", "(", "self", ",", "*", "statements", ")", ":", "# FIXME: only works for the first statement.", "return", "lock_and_call", "(", "lambda", ":", "DataFrame", ".", "_fromDataFrameRef", "(", "self", ".", "_impl", ".", "getData", "(", "list", "(", "statements", ")", ",", "len", "(", "statements", ")", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the data corresponding to the display statements. The statements can be AMPL expressions, or entities. It captures the equivalent of the command: .. code-block:: ampl display ds1, ..., dsn; where ds1, ..., dsn are the ``displayStatements`` with which the function is called. As only one DataFrame is returned, the operation will fail if the results of the display statements cannot be indexed over the same set. As a result, any attempt to get data from more than one set, or to get data for multiple parameters with a different number of indexing sets will fail. Args: statements: The display statements to be fetched. Raises: RuntimeError: if the AMPL visualization command does not succeed for one of the reasons listed above. Returns: DataFrame capturing the output of the display command in tabular form.
[ "Get", "the", "data", "corresponding", "to", "the", "display", "statements", ".", "The", "statements", "can", "be", "AMPL", "expressions", "or", "entities", ".", "It", "captures", "the", "equivalent", "of", "the", "command", ":" ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L118-L154
ampl/amplpy
amplpy/ampl.py
AMPL.getEntity
def getEntity(self, name): """ Get entity corresponding to the specified name (looks for it in all types of entities). Args: name: Name of the entity. Raises: TypeError: if the specified entity does not exist. Returns: The AMPL entity with the specified name. """ return lock_and_call( lambda: Entity(self._impl.getEntity(name)), self._lock )
python
def getEntity(self, name): return lock_and_call( lambda: Entity(self._impl.getEntity(name)), self._lock )
[ "def", "getEntity", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Entity", "(", "self", ".", "_impl", ".", "getEntity", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get entity corresponding to the specified name (looks for it in all types of entities). Args: name: Name of the entity. Raises: TypeError: if the specified entity does not exist. Returns: The AMPL entity with the specified name.
[ "Get", "entity", "corresponding", "to", "the", "specified", "name", "(", "looks", "for", "it", "in", "all", "types", "of", "entities", ")", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L156-L173
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._impl.getVariable(name)), self._lock )
python
def getVariable(self, name): return lock_and_call( lambda: Variable(self._impl.getVariable(name)), self._lock )
[ "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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L175-L188
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: Constraint(self._impl.getConstraint(name)), self._lock )
python
def getConstraint(self, name): return lock_and_call( lambda: Constraint(self._impl.getConstraint(name)), self._lock )
[ "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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L190-L203
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: Objective(self._impl.getObjective(name)), self._lock )
python
def getObjective(self, name): return lock_and_call( lambda: Objective(self._impl.getObjective(name)), self._lock )
[ "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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L205-L218
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)), self._lock )
python
def getSet(self, name): return lock_and_call( lambda: Set(self._impl.getSet(name)), self._lock )
[ "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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L220-L233
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(self._impl.getParameter(name)), self._lock )
python
def getParameter(self, name): return lock_and_call( lambda: Parameter(self._impl.getParameter(name)), self._lock )
[ "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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L235-L248
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 will be re-populated lazily (at first access) The output of interpreting the statements is passed to the current OutputHandler (see getOutputHandler and setOutputHandler). By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) lock_and_call( lambda: self._impl.eval(amplstatements), self._lock ) self._errorhandler_wrapper.check()
python
def eval(self, amplstatements, **kwargs): if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) lock_and_call( lambda: self._impl.eval(amplstatements), self._lock ) self._errorhandler_wrapper.check()
[ "def", "eval", "(", "self", ",", "amplstatements", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ",", "*", "*", "kwargs", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "eval", "(", "amplstatements", ")", ",", "self", ".", "_lock", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")" ]
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) The output of interpreting the statements is passed to the current OutputHandler (see getOutputHandler and setOutputHandler). By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
[ "Parses", "AMPL", "code", "and", "evaluates", "it", "as", "a", "possibly", "empty", "sequence", "of", "AMPL", "declarations", "and", "statements", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L250-L282
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): 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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L326-L335
ampl/amplpy
amplpy/ampl.py
AMPL.readAsync
def readAsync(self, fileName, callback, **kwargs): """ Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Path to the file (Relative to the current working directory or absolute). callback: Callback to be executed when the file has been interpreted. """ if self._langext is not None: with open(fileName, 'r') as fin: newmodel = self._langext.translate(fin.read(), **kwargs) with open(fileName+'.translated', 'w') as fout: fout.write(newmodel) fileName += '.translated' def async_call(): self._lock.acquire() try: self._impl.read(fileName) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def readAsync(self, fileName, callback, **kwargs): if self._langext is not None: with open(fileName, 'r') as fin: newmodel = self._langext.translate(fin.read(), **kwargs) with open(fileName+'.translated', 'w') as fout: fout.write(newmodel) fileName += '.translated' def async_call(): self._lock.acquire() try: self._impl.read(fileName) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "readAsync", "(", "self", ",", "fileName", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "with", "open", "(", "fileName", ",", "'r'", ")", "as", "fin", ":", "newmodel", "=", "self", ".", "_langext", ".", "translate", "(", "fin", ".", "read", "(", ")", ",", "*", "*", "kwargs", ")", "with", "open", "(", "fileName", "+", "'.translated'", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "newmodel", ")", "fileName", "+=", "'.translated'", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "read", "(", "fileName", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Path to the file (Relative to the current working directory or absolute). callback: Callback to be executed when the file has been interpreted.
[ "Interprets", "the", "specified", "file", "asynchronously", "interpreting", "it", "as", "a", "model", "or", "a", "script", "file", ".", "As", "a", "side", "effect", "it", "invalidates", "all", "entities", "(", "as", "the", "passed", "file", "can", "contain", "any", "arbitrary", "command", ")", ";", "the", "lists", "of", "entities", "will", "be", "re", "-", "populated", "lazily", "(", "at", "first", "access", ")", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L349-L381
ampl/amplpy
amplpy/ampl.py
AMPL.readDataAsync
def readDataAsync(self, fileName, callback): """ Interprets the specified data file asynchronously. When interpreting is over, the specified callback is called. The file is interpreted as data. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) Args: fileName: Full path to the file. callback: Callback to be executed when the file has been interpreted. """ def async_call(): self._lock.acquire() try: self._impl.readData(fileName) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def readDataAsync(self, fileName, callback): def async_call(): self._lock.acquire() try: self._impl.readData(fileName) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "readDataAsync", "(", "self", ",", "fileName", ",", "callback", ")", ":", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "readData", "(", "fileName", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
Interprets the specified data file asynchronously. When interpreting is over, the specified callback is called. The file is interpreted as data. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) Args: fileName: Full path to the file. callback: Callback to be executed when the file has been interpreted.
[ "Interprets", "the", "specified", "data", "file", "asynchronously", ".", "When", "interpreting", "is", "over", "the", "specified", "callback", "is", "called", ".", "The", "file", "is", "interpreted", "as", "data", ".", "As", "a", "side", "effect", "it", "invalidates", "all", "entities", "(", "as", "the", "passed", "file", "can", "contain", "any", "arbitrary", "command", ")", ";", "the", "lists", "of", "entities", "will", "be", "re", "-", "populated", "lazily", "(", "at", "first", "access", ")" ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L383-L408
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 statement has been interpreted. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) def async_call(): self._lock.acquire() try: self._impl.eval(amplstatements) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def evalAsync(self, amplstatements, callback, **kwargs): if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) def async_call(): self._lock.acquire() try: self._impl.eval(amplstatements) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "evalAsync", "(", "self", ",", "amplstatements", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ",", "*", "*", "kwargs", ")", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "eval", "(", "amplstatements", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
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: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
[ "Interpret", "the", "given", "AMPL", "statement", "asynchronously", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L410-L440
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 Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def solveAsync(self, callback): def async_call(): self._lock.acquire() try: self._impl.solve() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "solveAsync", "(", "self", ",", "callback", ")", ":", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "solve", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done.
[ "Solve", "the", "current", "model", "asynchronously", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L442-L459
ampl/amplpy
amplpy/ampl.py
AMPL.cd
def cd(self, path=None): """ Get or set the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory). Args: path: New working directory or None (to display the working directory). Returns: Current working directory. """ if path is None: return lock_and_call( lambda: self._impl.cd(), self._lock ) else: return lock_and_call( lambda: self._impl.cd(path), self._lock )
python
def cd(self, path=None): if path is None: return lock_and_call( lambda: self._impl.cd(), self._lock ) else: return lock_and_call( lambda: self._impl.cd(path), self._lock )
[ "def", "cd", "(", "self", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "return", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "cd", "(", ")", ",", "self", ".", "_lock", ")", "else", ":", "return", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "cd", "(", "path", ")", ",", "self", ".", "_lock", ")" ]
Get or set the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory). Args: path: New working directory or None (to display the working directory). Returns: Current working directory.
[ "Get", "or", "set", "the", "current", "working", "directory", "from", "the", "underlying", "interpreter", "(", "see", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Working_directory", ")", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L477-L498
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 valid. TypeError: if the value has an invalid type. """ if isinstance(value, bool): lock_and_call( lambda: self._impl.setBoolOption(name, value), self._lock ) elif isinstance(value, int): lock_and_call( lambda: self._impl.setIntOption(name, value), self._lock ) elif isinstance(value, float): lock_and_call( lambda: self._impl.setDblOption(name, value), self._lock ) elif isinstance(value, basestring): lock_and_call( lambda: self._impl.setOption(name, value), self._lock ) else: raise TypeError
python
def setOption(self, name, value): if isinstance(value, bool): lock_and_call( lambda: self._impl.setBoolOption(name, value), self._lock ) elif isinstance(value, int): lock_and_call( lambda: self._impl.setIntOption(name, value), self._lock ) elif isinstance(value, float): lock_and_call( lambda: self._impl.setDblOption(name, value), self._lock ) elif isinstance(value, basestring): lock_and_call( lambda: self._impl.setOption(name, value), self._lock ) else: raise TypeError
[ "def", "setOption", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setBoolOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setIntOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setDblOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "else", ":", "raise", "TypeError" ]
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 type.
[ "Set", "an", "AMPL", "option", "to", "a", "specified", "value", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L500-L535
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 valid. """ try: value = lock_and_call( lambda: self._impl.getOption(name).value(), self._lock ) except RuntimeError: return None else: try: return int(value) except ValueError: try: return float(value) except ValueError: return value
python
def getOption(self, name): try: value = lock_and_call( lambda: self._impl.getOption(name).value(), self._lock ) except RuntimeError: return None else: try: return int(value) except ValueError: try: return float(value) except ValueError: return value
[ "def", "getOption", "(", "self", ",", "name", ")", ":", "try", ":", "value", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getOption", "(", "name", ")", ".", "value", "(", ")", ",", "self", ".", "_lock", ")", "except", "RuntimeError", ":", "return", "None", "else", ":", "try", ":", "return", "int", "(", "value", ")", "except", "ValueError", ":", "try", ":", "return", "float", "(", "value", ")", "except", "ValueError", ":", "return", "value" ]
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", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L537-L565
ampl/amplpy
amplpy/ampl.py
AMPL.read
def read(self, fileName, **kwargs): """ Interprets the specified file (script or model or mixed) As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Full path to the file. Raises: RuntimeError: in case the file does not exist. """ if self._langext is not None: with open(fileName, 'r') as fin: newmodel = self._langext.translate(fin.read(), **kwargs) with open(fileName+'.translated', 'w') as fout: fout.write(newmodel) fileName += '.translated' lock_and_call( lambda: self._impl.read(fileName), self._lock ) self._errorhandler_wrapper.check()
python
def read(self, fileName, **kwargs): if self._langext is not None: with open(fileName, 'r') as fin: newmodel = self._langext.translate(fin.read(), **kwargs) with open(fileName+'.translated', 'w') as fout: fout.write(newmodel) fileName += '.translated' lock_and_call( lambda: self._impl.read(fileName), self._lock ) self._errorhandler_wrapper.check()
[ "def", "read", "(", "self", ",", "fileName", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "with", "open", "(", "fileName", ",", "'r'", ")", "as", "fin", ":", "newmodel", "=", "self", ".", "_langext", ".", "translate", "(", "fin", ".", "read", "(", ")", ",", "*", "*", "kwargs", ")", "with", "open", "(", "fileName", "+", "'.translated'", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "newmodel", ")", "fileName", "+=", "'.translated'", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "read", "(", "fileName", ")", ",", "self", ".", "_lock", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")" ]
Interprets the specified file (script or model or mixed) As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Full path to the file. Raises: RuntimeError: in case the file does not exist.
[ "Interprets", "the", "specified", "file", "(", "script", "or", "model", "or", "mixed", ")", "As", "a", "side", "effect", "it", "invalidates", "all", "entities", "(", "as", "the", "passed", "file", "can", "contain", "any", "arbitrary", "command", ")", ";", "the", "lists", "of", "entities", "will", "be", "re", "-", "populated", "lazily", "(", "at", "first", "access", ")", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L567-L590
ampl/amplpy
amplpy/ampl.py
AMPL.readData
def readData(self, fileName): """ Interprets the specified file as an AMPL data file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). After reading the file, the interpreter is put back to "model" mode. Args: fileName: Full path to the file. Raises: RuntimeError: in case the file does not exist. """ lock_and_call( lambda: self._impl.readData(fileName), self._lock ) self._errorhandler_wrapper.check()
python
def readData(self, fileName): lock_and_call( lambda: self._impl.readData(fileName), self._lock ) self._errorhandler_wrapper.check()
[ "def", "readData", "(", "self", ",", "fileName", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "readData", "(", "fileName", ")", ",", "self", ".", "_lock", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")" ]
Interprets the specified file as an AMPL data file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). After reading the file, the interpreter is put back to "model" mode. Args: fileName: Full path to the file. Raises: RuntimeError: in case the file does not exist.
[ "Interprets", "the", "specified", "file", "as", "an", "AMPL", "data", "file", ".", "As", "a", "side", "effect", "it", "invalidates", "all", "entities", "(", "as", "the", "passed", "file", "can", "contain", "any", "arbitrary", "command", ")", ";", "the", "lists", "of", "entities", "will", "be", "re", "-", "populated", "lazily", "(", "at", "first", "access", ")", ".", "After", "reading", "the", "file", "the", "interpreter", "is", "put", "back", "to", "model", "mode", "." ]
train
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L592-L610