idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
233,800 | def get_aside ( self , aside_usage_id ) : aside_type = self . id_reader . get_aside_type_from_usage ( aside_usage_id ) xblock_usage = self . id_reader . get_usage_id_from_aside ( aside_usage_id ) xblock_def = self . id_reader . get_definition_id ( xblock_usage ) aside_def_id , aside_usage_id = self . id_generator . create_aside ( xblock_def , xblock_usage , aside_type ) keys = ScopeIds ( self . user_id , aside_type , aside_def_id , aside_usage_id ) block = self . create_aside ( aside_type , keys ) return block | Create an XBlockAside in this runtime . | 175 | 9 |
233,801 | def parse_xml_string ( self , xml , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 2 , ) id_generator = id_generator or self . id_generator if isinstance ( xml , six . binary_type ) : io_type = BytesIO else : io_type = StringIO return self . parse_xml_file ( io_type ( xml ) , id_generator ) | Parse a string of XML returning a usage id . | 135 | 11 |
233,802 | def parse_xml_file ( self , fileobj , id_generator = None ) : root = etree . parse ( fileobj ) . getroot ( ) usage_id = self . _usage_id_from_node ( root , None , id_generator ) return usage_id | Parse an open XML file returning a usage id . | 63 | 11 |
233,803 | def _usage_id_from_node ( self , node , parent_id , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 3 , ) id_generator = id_generator or self . id_generator block_type = node . tag # remove xblock-family from elements node . attrib . pop ( 'xblock-family' , None ) # TODO: a way for this node to be a usage to an existing definition? def_id = id_generator . create_definition ( block_type ) usage_id = id_generator . create_usage ( def_id ) keys = ScopeIds ( None , block_type , def_id , usage_id ) block_class = self . mixologist . mix ( self . load_block_type ( block_type ) ) # pull the asides out of the xml payload aside_children = [ ] for child in node . iterchildren ( ) : # get xblock-family from node xblock_family = child . attrib . pop ( 'xblock-family' , None ) if xblock_family : xblock_family = self . _family_id_to_superclass ( xblock_family ) if issubclass ( xblock_family , XBlockAside ) : aside_children . append ( child ) # now process them & remove them from the xml payload for child in aside_children : self . _aside_from_xml ( child , def_id , usage_id , id_generator ) node . remove ( child ) block = block_class . parse_xml ( node , self , keys , id_generator ) block . parent = parent_id block . save ( ) return usage_id | Create a new usage id from an XML dom node . | 412 | 11 |
233,804 | def _aside_from_xml ( self , node , block_def_id , block_usage_id , id_generator ) : id_generator = id_generator or self . id_generator aside_type = node . tag aside_class = self . load_aside_type ( aside_type ) aside_def_id , aside_usage_id = id_generator . create_aside ( block_def_id , block_usage_id , aside_type ) keys = ScopeIds ( None , aside_type , aside_def_id , aside_usage_id ) aside = aside_class . parse_xml ( node , self , keys , id_generator ) aside . save ( ) | Create an aside from the xml and attach it to the given block | 159 | 13 |
233,805 | def add_node_as_child ( self , block , node , id_generator = None ) : usage_id = self . _usage_id_from_node ( node , block . scope_ids . usage_id , id_generator ) block . children . append ( usage_id ) | Called by XBlock . parse_xml to treat a child node as a child block . | 65 | 19 |
233,806 | def export_to_xml ( self , block , xmlfile ) : root = etree . Element ( "unknown_root" , nsmap = XML_NAMESPACES ) tree = etree . ElementTree ( root ) block . add_xml_to_node ( root ) # write asides as children for aside in self . get_asides ( block ) : if aside . needs_serialization ( ) : aside_node = etree . Element ( "unknown_root" , nsmap = XML_NAMESPACES ) aside . add_xml_to_node ( aside_node ) block . append ( aside_node ) tree . write ( xmlfile , xml_declaration = True , pretty_print = True , encoding = 'utf-8' ) | Export the block to XML writing the XML to xmlfile . | 170 | 14 |
233,807 | def add_block_as_child_node ( self , block , node ) : child = etree . SubElement ( node , "unknown" ) block . add_xml_to_node ( child ) | Export block as a child node of node . | 44 | 9 |
233,808 | def render ( self , block , view_name , context = None ) : # Set the active view so that :function:`render_child` can use it # as a default old_view_name = self . _view_name self . _view_name = view_name try : view_fn = getattr ( block , view_name , None ) if view_fn is None : view_fn = getattr ( block , "fallback_view" , None ) if view_fn is None : raise NoSuchViewError ( block , view_name ) view_fn = functools . partial ( view_fn , view_name ) frag = view_fn ( context ) # Explicitly save because render action may have changed state block . save ( ) updated_frag = self . wrap_xblock ( block , view_name , frag , context ) return self . render_asides ( block , view_name , updated_frag , context ) finally : # Reset the active view to what it was before entering this method self . _view_name = old_view_name | Render a block by invoking its view . | 233 | 8 |
233,809 | def render_child ( self , child , view_name = None , context = None ) : return child . render ( view_name or self . _view_name , context ) | A shortcut to render a child block . | 38 | 8 |
233,810 | def render_children ( self , block , view_name = None , context = None ) : results = [ ] for child_id in block . children : child = self . get_block ( child_id ) result = self . render_child ( child , view_name , context ) results . append ( result ) return results | Render a block s children returning a list of results . | 69 | 11 |
233,811 | def wrap_xblock ( self , block , view , frag , context ) : # pylint: disable=W0613 if hasattr ( self , 'wrap_child' ) : log . warning ( "wrap_child is deprecated in favor of wrap_xblock and wrap_aside %s" , self . __class__ ) return self . wrap_child ( block , view , frag , context ) # pylint: disable=no-member extra_data = { 'name' : block . name } if block . name else { } return self . _wrap_ele ( block , view , frag , extra_data ) | Creates a div which identifies the xblock and writes out the json_init_args into a script tag . | 135 | 23 |
233,812 | def wrap_aside ( self , block , aside , view , frag , context ) : # pylint: disable=unused-argument return self . _wrap_ele ( aside , view , frag , { 'block_id' : block . scope_ids . usage_id , 'url_selector' : 'asideBaseUrl' , } ) | Creates a div which identifies the aside points to the original block and writes out the json_init_args into a script tag . | 77 | 27 |
233,813 | def _wrap_ele ( self , block , view , frag , extra_data = None ) : wrapped = Fragment ( ) data = { 'usage' : block . scope_ids . usage_id , 'block-type' : block . scope_ids . block_type , } data . update ( extra_data ) if frag . js_init_fn : data [ 'init' ] = frag . js_init_fn data [ 'runtime-version' ] = frag . js_init_version json_init = "" # TODO/Note: We eventually want to remove: hasattr(frag, 'json_init_args') # However, I'd like to maintain backwards-compatibility with older XBlock # for at least a little while so as not to adversely effect developers. # pmitros/Jun 28, 2014. if hasattr ( frag , 'json_init_args' ) and frag . json_init_args is not None : json_init = ( '<script type="json/xblock-args" class="xblock_json_init_args">' '{data}</script>' ) . format ( data = json . dumps ( frag . json_init_args ) ) block_css_entrypoint = block . entry_point . replace ( '.' , '-' ) css_classes = [ block_css_entrypoint , '{}-{}' . format ( block_css_entrypoint , view ) , ] html = "<div class='{}'{properties}>{body}{js}</div>" . format ( markupsafe . escape ( ' ' . join ( css_classes ) ) , properties = "" . join ( " data-%s='%s'" % item for item in list ( data . items ( ) ) ) , body = frag . body_html ( ) , js = json_init ) wrapped . add_content ( html ) wrapped . add_fragment_resources ( frag ) return wrapped | Does the guts of the wrapping the same way for both xblocks and asides . Their wrappers provide other info in extra_data which gets put into the dom data - attrs . | 426 | 38 |
233,814 | 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 . | 81 | 15 |
233,815 | 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 . | 262 | 17 |
233,816 | 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 . | 139 | 26 |
233,817 | 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 | 129 | 39 |
233,818 | 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 . | 184 | 11 |
233,819 | 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 . | 104 | 6 |
233,820 | 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 . | 488 | 9 |
233,821 | 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 | 52 | 9 |
233,822 | 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 . | 263 | 13 |
233,823 | 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 | 38 | 13 |
233,824 | 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 . | 114 | 12 |
233,825 | 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 . | 46 | 12 |
233,826 | 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 . | 47 | 13 |
233,827 | 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 . | 126 | 22 |
233,828 | 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 . | 197 | 9 |
233,829 | 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 . | 28 | 20 |
233,830 | 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 . | 39 | 9 |
233,831 | 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 . | 80 | 41 |
233,832 | 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 . | 196 | 10 |
233,833 | def handle ( self , handler_name , request , suffix = '' ) : return self . runtime . handle ( self , handler_name , request , suffix ) | Handle request with this block s runtime . | 33 | 8 |
233,834 | 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 . | 105 | 19 |
233,835 | 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 . | 80 | 15 |
233,836 | 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 . | 80 | 15 |
233,837 | 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 . | 75 | 15 |
233,838 | 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 . | 77 | 9 |
233,839 | 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 . | 67 | 12 |
233,840 | 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 . | 62 | 9 |
233,841 | 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 . | 270 | 8 |
233,842 | 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 . | 172 | 9 |
233,843 | 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 . | 113 | 14 |
233,844 | 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 . | 258 | 8 |
233,845 | def supports ( cls , * functionalities ) : 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 | A view decorator to indicate that an xBlock view has support for the given functionalities . | 92 | 19 |
233,846 | 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 . | 136 | 33 |
233,847 | 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 . | 79 | 8 |
233,848 | 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 ) : """ 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 | Generate a unique key for a scope that can be used as a filename in a URL or in a KVS . | 611 | 24 |
233,849 | def default ( self ) : if self . MUTABLE : return copy . deepcopy ( self . _default ) else : return self . _default | Returns the static value that this defaults to . | 31 | 9 |
233,850 | 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 . | 73 | 15 |
233,851 | 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 . | 71 | 14 |
233,852 | 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 . | 77 | 10 |
233,853 | 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 | 187 | 35 |
233,854 | 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 . | 52 | 16 |
233,855 | 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 . | 105 | 14 |
233,856 | 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 . | 87 | 9 |
233,857 | 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 . | 64 | 11 |
233,858 | 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 . ) | 46 | 34 |
233,859 | 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 | 42 | 14 |
233,860 | 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 | 52 | 15 |
233,861 | 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 . | 44 | 12 |
233,862 | 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 . | 224 | 14 |
233,863 | 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 . | 72 | 14 |
233,864 | 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 . | 94 | 16 |
233,865 | 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 . | 262 | 5 |
233,866 | 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 . | 81 | 8 |
233,867 | 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 . | 76 | 16 |
233,868 | 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 . | 79 | 13 |
233,869 | def render ( self , view , context = None ) : return self . runtime . render ( self , view , context ) | Render view with this block s runtime and the supplied context | 25 | 11 |
233,870 | 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 . | 53 | 11 |
233,871 | 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 . | 100 | 18 |
233,872 | 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 | 80 | 19 |
233,873 | 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 . | 37 | 14 |
233,874 | 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 . | 43 | 9 |
233,875 | 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 . | 47 | 17 |
233,876 | 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 . | 60 | 10 |
233,877 | 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 . | 88 | 18 |
233,878 | 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 . | 297 | 34 |
233,879 | def getVariable ( self , name ) : return lock_and_call ( lambda : Variable ( self . _impl . getVariable ( name ) ) , self . _lock ) | Get the variable with the corresponding name . | 37 | 8 |
233,880 | def getConstraint ( self , name ) : return lock_and_call ( lambda : Constraint ( self . _impl . getConstraint ( name ) ) , self . _lock ) | Get the constraint with the corresponding name . | 43 | 8 |
233,881 | def getObjective ( self , name ) : return lock_and_call ( lambda : Objective ( self . _impl . getObjective ( name ) ) , self . _lock ) | Get the objective with the corresponding name . | 39 | 8 |
233,882 | def getSet ( self , name ) : return lock_and_call ( lambda : Set ( self . _impl . getSet ( name ) ) , self . _lock ) | Get the set with the corresponding name . | 37 | 8 |
233,883 | def getParameter ( self , name ) : return lock_and_call ( lambda : Parameter ( self . _impl . getParameter ( name ) ) , self . _lock ) | Get the parameter with the corresponding name . | 38 | 8 |
233,884 | 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 . | 86 | 21 |
233,885 | 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 . | 43 | 12 |
233,886 | 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 . | 131 | 11 |
233,887 | 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 . | 73 | 9 |
233,888 | 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 . | 166 | 10 |
233,889 | 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 . | 73 | 18 |
233,890 | def getValue ( self , scalarExpression ) : return lock_and_call ( lambda : Utils . castVariant ( self . _impl . getValue ( scalarExpression ) ) , self . _lock ) | Get a scalar value from the underlying AMPL interpreter as a double or a string . | 48 | 18 |
233,891 | def setData ( self , data , setName = None ) : if not isinstance ( data , DataFrame ) : if pd is not None and isinstance ( data , pd . DataFrame ) : data = DataFrame . fromPandas ( data ) if setName is None : lock_and_call ( lambda : self . _impl . setData ( data . _impl ) , self . _lock ) else : lock_and_call ( lambda : self . _impl . setData ( data . _impl , setName ) , self . _lock ) | Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names . | 120 | 22 |
233,892 | def writeTable ( self , tableName ) : lock_and_call ( lambda : self . _impl . writeTable ( tableName ) , self . _lock ) | Write the table corresponding to the specified name equivalent to the AMPL statement | 35 | 14 |
233,893 | def display ( self , * amplExpressions ) : exprs = list ( map ( str , amplExpressions ) ) lock_and_call ( lambda : self . _impl . displayLst ( exprs , len ( exprs ) ) , self . _lock ) | Writes on the current OutputHandler the outcome of the AMPL statement . | 57 | 15 |
233,894 | def setOutputHandler ( self , outputhandler ) : class OutputHandlerInternal ( amplpython . OutputHandler ) : def output ( self , kind , msg ) : outputhandler . output ( kind , msg ) self . _outputhandler = outputhandler self . _outputhandler_internal = OutputHandlerInternal ( ) lock_and_call ( lambda : self . _impl . setOutputHandler ( self . _outputhandler_internal ) , self . _lock ) | Sets a new output handler . | 109 | 7 |
233,895 | def setErrorHandler ( self , errorhandler ) : class ErrorHandlerWrapper ( ErrorHandler ) : def __init__ ( self , errorhandler ) : self . errorhandler = errorhandler self . last_exception = None def error ( self , exception ) : if isinstance ( exception , amplpython . AMPLException ) : exception = AMPLException ( exception ) try : self . errorhandler . error ( exception ) except Exception as e : self . last_exception = e def warning ( self , exception ) : if isinstance ( exception , amplpython . AMPLException ) : exception = AMPLException ( exception ) try : self . errorhandler . warning ( exception ) except Exception as e : self . last_exception = e def check ( self ) : if self . last_exception is not None : e , self . last_exception = self . last_exception , None raise e errorhandler_wrapper = ErrorHandlerWrapper ( errorhandler ) class InnerErrorHandler ( amplpython . ErrorHandler ) : def error ( self , exception ) : errorhandler_wrapper . error ( exception ) def warning ( self , exception ) : errorhandler_wrapper . warning ( exception ) self . _errorhandler = errorhandler self . _errorhandler_inner = InnerErrorHandler ( ) self . _errorhandler_wrapper = errorhandler_wrapper lock_and_call ( lambda : self . _impl . setErrorHandler ( self . _errorhandler_inner ) , self . _lock ) | Sets a new error handler . | 318 | 7 |
233,896 | def getVariables ( self ) : variables = lock_and_call ( lambda : self . _impl . getVariables ( ) , self . _lock ) return EntityMap ( variables , Variable ) | Get all the variables declared . | 42 | 6 |
233,897 | def getConstraints ( self ) : constraints = lock_and_call ( lambda : self . _impl . getConstraints ( ) , self . _lock ) return EntityMap ( constraints , Constraint ) | Get all the constraints declared . | 46 | 6 |
233,898 | def getObjectives ( self ) : objectives = lock_and_call ( lambda : self . _impl . getObjectives ( ) , self . _lock ) return EntityMap ( objectives , Objective ) | Get all the objectives declared . | 42 | 6 |
233,899 | def getSets ( self ) : sets = lock_and_call ( lambda : self . _impl . getSets ( ) , self . _lock ) return EntityMap ( sets , Set ) | Get all the sets declared . | 42 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.