idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
53,300
def print ( self , x : int , y : int , string : str , fg : Optional [ Tuple [ int , int , int ] ] = None , bg : Optional [ Tuple [ int , int , int ] ] = None , bg_blend : int = tcod . constants . BKGND_SET , alignment : int = tcod . constants . LEFT , ) -> None : x , y = self . _pythonic_index ( x , y ) string_ = string . encode ( "utf-8" ) lib . console_print ( self . console_c , x , y , string_ , len ( string_ ) , ( fg , ) if fg is not None else ffi . NULL , ( bg , ) if bg is not None else ffi . NULL , bg_blend , alignment , )
Print a string on a console with manual line breaks .
53,301
def draw_frame ( self , x : int , y : int , width : int , height : int , title : str = "" , clear : bool = True , fg : Optional [ Tuple [ int , int , int ] ] = None , bg : Optional [ Tuple [ int , int , int ] ] = None , bg_blend : int = tcod . constants . BKGND_SET , ) -> None : x , y = self . _pythonic_index ( x , y ) title_ = title . encode ( "utf-8" ) lib . print_frame ( self . console_c , x , y , width , height , title_ , len ( title_ ) , ( fg , ) if fg is not None else ffi . NULL , ( bg , ) if bg is not None else ffi . NULL , bg_blend , clear , )
Draw a framed rectangle with an optional title .
53,302
def draw_rect ( self , x : int , y : int , width : int , height : int , ch : int , fg : Optional [ Tuple [ int , int , int ] ] = None , bg : Optional [ Tuple [ int , int , int ] ] = None , bg_blend : int = tcod . constants . BKGND_SET , ) -> None : x , y = self . _pythonic_index ( x , y ) lib . draw_rect ( self . console_c , x , y , width , height , ch , ( fg , ) if fg is not None else ffi . NULL , ( bg , ) if bg is not None else ffi . NULL , bg_blend , )
Draw characters and colors over a rectangular region .
53,303
def blit ( self , image , x , y ) : x += self . font_bbox [ 2 ] - self . bbox [ 2 ] y += self . font_bbox [ 3 ] - self . bbox [ 3 ] x += self . font_bbox [ 0 ] - self . bbox [ 0 ] y += self . font_bbox [ 1 ] - self . bbox [ 1 ] image [ y : y + self . height , x : x + self . width ] = self . bitmap * 255
blit to the image array
53,304
def parseBits ( self , hexcode , width ) : bitarray = [ ] for byte in hexcode [ : : - 1 ] : bits = int ( byte , 16 ) for x in range ( 4 ) : bitarray . append ( bool ( ( 2 ** x ) & bits ) ) bitarray = bitarray [ : : - 1 ] return enumerate ( bitarray [ : width ] )
enumerate over bits in a line of data
53,305
def memory_warning ( config , context ) : used = psutil . Process ( os . getpid ( ) ) . memory_info ( ) . rss / 1048576 limit = float ( context . memory_limit_in_mb ) p = used / limit memory_threshold = config . get ( 'memory_warning_threshold' ) if p >= memory_threshold : config [ 'raven_client' ] . captureMessage ( 'Memory Usage Warning' , level = 'warning' , extra = { 'MemoryLimitInMB' : context . memory_limit_in_mb , 'MemoryUsedInMB' : math . floor ( used ) } ) else : Timer ( .5 , memory_warning , ( config , context ) ) . start ( )
Determines when memory usage is nearing it s max .
53,306
def install_timers ( config , context ) : timers = [ ] if config . get ( 'capture_timeout_warnings' ) : timeout_threshold = config . get ( 'timeout_warning_threshold' ) time_remaining = context . get_remaining_time_in_millis ( ) / 1000 timers . append ( Timer ( time_remaining * timeout_threshold , timeout_warning , ( config , context ) ) ) timers . append ( Timer ( max ( time_remaining - .5 , 0 ) , timeout_error , [ config ] ) ) if config . get ( 'capture_memory_warnings' ) : timers . append ( Timer ( .5 , memory_warning , ( config , context ) ) ) for t in timers : t . start ( ) return timers
Create the timers as specified by the plugin configuration .
53,307
def recurseforumcontents ( parser , token ) : bits = token . contents . split ( ) forums_contents_var = template . Variable ( bits [ 1 ] ) template_nodes = parser . parse ( ( 'endrecurseforumcontents' , ) ) parser . delete_first_token ( ) return RecurseTreeForumVisibilityContentNode ( template_nodes , forums_contents_var )
Iterates over the content nodes and renders the contained forum block for each node .
53,308
def forum_list ( context , forum_visibility_contents ) : request = context . get ( 'request' ) tracking_handler = TrackingHandler ( request = request ) data_dict = { 'forum_contents' : forum_visibility_contents , 'unread_forums' : tracking_handler . get_unread_forums_from_list ( request . user , forum_visibility_contents . forums ) , 'user' : request . user , 'request' : request , } root_level = forum_visibility_contents . root_level if root_level is not None : data_dict [ 'root_level' ] = root_level data_dict [ 'root_level_middle' ] = root_level + 1 data_dict [ 'root_level_sub' ] = root_level + 2 return data_dict
Renders the considered forum list .
53,309
def get_object ( self , request , * args , ** kwargs ) : forum_pk = kwargs . get ( 'forum_pk' , None ) descendants = kwargs . get ( 'descendants' , None ) self . user = request . user if forum_pk : forum = get_object_or_404 ( Forum , pk = forum_pk ) forums_qs = ( forum . get_descendants ( include_self = True ) if descendants else Forum . objects . filter ( pk = forum_pk ) ) self . forums = request . forum_permission_handler . get_readable_forums ( forums_qs , request . user , ) else : self . forums = request . forum_permission_handler . get_readable_forums ( Forum . objects . all ( ) , request . user , )
Handles the considered object .
53,310
def items ( self ) : return Topic . objects . filter ( forum__in = self . forums , approved = True ) . order_by ( '-last_post_on' )
Returns the items to include into the feed .
53,311
def item_link ( self , item ) : return reverse_lazy ( 'forum_conversation:topic' , kwargs = { 'forum_slug' : item . forum . slug , 'forum_pk' : item . forum . pk , 'slug' : item . slug , 'pk' : item . id , } , )
Generates a link for a specific item of the feed .
53,312
def topic_pages_inline_list ( topic ) : data_dict = { 'topic' : topic , } pages_number = ( ( topic . posts_count - 1 ) // machina_settings . TOPIC_POSTS_NUMBER_PER_PAGE ) + 1 if pages_number > 5 : data_dict [ 'first_pages' ] = range ( 1 , 5 ) data_dict [ 'last_page' ] = pages_number elif pages_number > 1 : data_dict [ 'first_pages' ] = range ( 1 , pages_number + 1 ) return data_dict
This will render an inline pagination for the posts related to the given topic .
53,313
def get_urls ( self ) : urls = super ( ) . get_urls ( ) forum_admin_urls = [ url ( r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$' , self . admin_site . admin_view ( self . moveforum_view ) , name = 'forum_forum_move' , ) , url ( r'^edit-global-permissions/$' , self . admin_site . admin_view ( self . editpermissions_index_view ) , name = 'forum_forum_editpermission_index' , ) , url ( r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$' , self . admin_site . admin_view ( self . editpermissions_user_view ) , name = 'forum_forum_editpermission_user' , ) , url ( r'^edit-global-permissions/user/anonymous/$' , self . admin_site . admin_view ( self . editpermissions_anonymous_user_view ) , name = 'forum_forum_editpermission_anonymous_user' , ) , url ( r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$' , self . admin_site . admin_view ( self . editpermissions_group_view ) , name = 'forum_forum_editpermission_group' , ) , url ( r'^(?P<forum_id>[0-9]+)/edit-permissions/$' , self . admin_site . admin_view ( self . editpermissions_index_view ) , name = 'forum_forum_editpermission_index' , ) , url ( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$' , self . admin_site . admin_view ( self . editpermissions_user_view ) , name = 'forum_forum_editpermission_user' , ) , url ( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$' , self . admin_site . admin_view ( self . editpermissions_anonymous_user_view ) , name = 'forum_forum_editpermission_anonymous_user' , ) , url ( r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$' , self . admin_site . admin_view ( self . editpermissions_group_view ) , name = 'forum_forum_editpermission_group' , ) , ] return forum_admin_urls + urls
Returns the URLs associated with the admin abstraction .
53,314
def get_forum_perms_base_context ( self , request , obj = None ) : context = { 'adminform' : { 'model_admin' : self } , 'media' : self . media , 'object' : obj , 'app_label' : self . model . _meta . app_label , 'opts' : self . model . _meta , 'has_change_permission' : self . has_change_permission ( request , obj ) , } try : context . update ( self . admin_site . each_context ( request ) ) except TypeError : context . update ( self . admin_site . each_context ( ) ) except AttributeError : pass return context
Returns the context to provide to the template for permissions contents .
53,315
def moveforum_view ( self , request , forum_id , direction ) : forum = get_object_or_404 ( Forum , pk = forum_id ) target , position = None , None if direction == 'up' : target , position = forum . get_previous_sibling ( ) , 'left' elif direction == 'down' : target , position = forum . get_next_sibling ( ) , 'right' try : assert target is not None forum . move_to ( target , position ) except ( InvalidMove , AssertionError ) : pass self . message_user ( request , _ ( "'{}' forum successfully moved" ) . format ( forum . name ) ) return HttpResponseRedirect ( reverse ( 'admin:forum_forum_changelist' ) )
Moves the given forum toward the requested direction .
53,316
def editpermissions_index_view ( self , request , forum_id = None ) : forum = get_object_or_404 ( Forum , pk = forum_id ) if forum_id else None context = self . get_forum_perms_base_context ( request , forum ) context [ 'forum' ] = forum context [ 'title' ] = _ ( 'Forum permissions' ) if forum else _ ( 'Global forum permissions' ) permissions_copied = False if forum and request . method == 'POST' : forum_form = PickForumForm ( request . POST ) if forum_form . is_valid ( ) and forum_form . cleaned_data [ 'forum' ] : self . _copy_forum_permissions ( forum_form . cleaned_data [ 'forum' ] , forum ) self . message_user ( request , _ ( 'Permissions successfully copied' ) ) permissions_copied = True context [ 'forum_form' ] = forum_form elif forum : context [ 'forum_form' ] = PickForumForm ( ) if request . method == 'POST' and not permissions_copied : user_form = PickUserForm ( request . POST , admin_site = self . admin_site ) group_form = PickGroupForm ( request . POST , admin_site = self . admin_site ) if user_form . is_valid ( ) and group_form . is_valid ( ) : user = user_form . cleaned_data . get ( 'user' , None ) if user_form . cleaned_data else None anonymous_user = ( user_form . cleaned_data . get ( 'anonymous_user' , None ) if user_form . cleaned_data else None ) group = ( group_form . cleaned_data . get ( 'group' , None ) if group_form . cleaned_data else None ) if not user and not anonymous_user and not group : user_form . _errors [ NON_FIELD_ERRORS ] = user_form . error_class ( [ _ ( 'Choose either a user ID, a group ID or the anonymous user' ) , ] ) elif user : url_kwargs = ( { 'forum_id' : forum . id , 'user_id' : user . id } if forum else { 'user_id' : user . id } ) return redirect ( reverse ( 'admin:forum_forum_editpermission_user' , kwargs = url_kwargs ) , ) elif anonymous_user : url_kwargs = { 'forum_id' : forum . id } if forum else { } return redirect ( reverse ( 'admin:forum_forum_editpermission_anonymous_user' , kwargs = url_kwargs , ) , ) elif group : url_kwargs = ( { 'forum_id' : forum . id , 'group_id' : group . id } if forum else { 'group_id' : group . id } ) return redirect ( reverse ( 'admin:forum_forum_editpermission_group' , kwargs = url_kwargs ) , ) context [ 'user_errors' ] = helpers . AdminErrorList ( user_form , [ ] ) context [ 'group_errors' ] = helpers . AdminErrorList ( group_form , [ ] ) else : user_form = PickUserForm ( admin_site = self . admin_site ) group_form = PickGroupForm ( admin_site = self . admin_site ) context [ 'user_form' ] = user_form context [ 'group_form' ] = group_form return render ( request , self . editpermissions_index_view_template_name , context )
Allows to select how to edit forum permissions .
53,317
def editpermissions_user_view ( self , request , user_id , forum_id = None ) : user_model = get_user_model ( ) user = get_object_or_404 ( user_model , pk = user_id ) forum = get_object_or_404 ( Forum , pk = forum_id ) if forum_id else None context = self . get_forum_perms_base_context ( request , forum ) context [ 'forum' ] = forum context [ 'title' ] = '{} - {}' . format ( _ ( 'Forum permissions' ) , user ) context [ 'form' ] = self . _get_permissions_form ( request , UserForumPermission , { 'forum' : forum , 'user' : user } , ) return render ( request , self . editpermissions_user_view_template_name , context )
Allows to edit user permissions for the considered forum .
53,318
def editpermissions_anonymous_user_view ( self , request , forum_id = None ) : forum = get_object_or_404 ( Forum , pk = forum_id ) if forum_id else None context = self . get_forum_perms_base_context ( request , forum ) context [ 'forum' ] = forum context [ 'title' ] = '{} - {}' . format ( _ ( 'Forum permissions' ) , _ ( 'Anonymous user' ) ) context [ 'form' ] = self . _get_permissions_form ( request , UserForumPermission , { 'forum' : forum , 'anonymous_user' : True } , ) return render ( request , self . editpermissions_anonymous_user_view_template_name , context )
Allows to edit anonymous user permissions for the considered forum .
53,319
def editpermissions_group_view ( self , request , group_id , forum_id = None ) : group = get_object_or_404 ( Group , pk = group_id ) forum = get_object_or_404 ( Forum , pk = forum_id ) if forum_id else None context = self . get_forum_perms_base_context ( request , forum ) context [ 'forum' ] = forum context [ 'title' ] = '{} - {}' . format ( _ ( 'Forum permissions' ) , group ) context [ 'form' ] = self . _get_permissions_form ( request , GroupForumPermission , { 'forum' : forum , 'group' : group } , ) return render ( request , self . editpermissions_group_view_template_name , context )
Allows to edit group permissions for the considered forum .
53,320
def get_permission ( context , method , * args , ** kwargs ) : request = context . get ( 'request' , None ) perm_handler = request . forum_permission_handler if request else PermissionHandler ( ) allowed_methods = inspect . getmembers ( perm_handler , predicate = inspect . ismethod ) allowed_method_names = [ a [ 0 ] for a in allowed_methods if not a [ 0 ] . startswith ( '_' ) ] if method not in allowed_method_names : raise template . TemplateSyntaxError ( 'Only the following methods are allowed through ' 'this templatetag: {}' . format ( allowed_method_names ) ) perm_method = getattr ( perm_handler , method ) return perm_method ( * args , ** kwargs )
This will return a boolean indicating if the considered permission is granted for the passed user .
53,321
def total_form_count ( self ) : total_forms = super ( ) . total_form_count ( ) if not self . data and not self . files and self . initial_form_count ( ) > 0 : total_forms -= self . extra return total_forms
This rewrite of total_form_count allows to add an empty form to the formset only when no initial data is provided .
53,322
def get_classes ( module_label , classnames ) : app_label = module_label . split ( '.' ) [ 0 ] app_module_path = _get_app_module_path ( module_label ) if not app_module_path : raise AppNotFoundError ( 'No app found matching \'{}\'' . format ( module_label ) ) module_path = app_module_path if '.' in app_module_path : base_package = app_module_path . rsplit ( '.' + app_label , 1 ) [ 0 ] module_path = '{}.{}' . format ( base_package , module_label ) local_imported_module = _import_module ( module_path , classnames ) machina_imported_module = None if not app_module_path . startswith ( 'machina.apps' ) : machina_imported_module = _import_module ( '{}.{}' . format ( 'machina.apps' , module_label ) , classnames , ) if local_imported_module is None and machina_imported_module is None : raise AppNotFoundError ( 'Error importing \'{}\'' . format ( module_path ) ) imported_modules = [ m for m in ( local_imported_module , machina_imported_module ) if m is not None ] return _pick_up_classes ( imported_modules , classnames )
Imports a set of classes from a given module .
53,323
def _import_module ( module_path , classnames ) : try : imported_module = __import__ ( module_path , fromlist = classnames ) return imported_module except ImportError : __ , __ , exc_traceback = sys . exc_info ( ) frames = traceback . extract_tb ( exc_traceback ) if len ( frames ) > 1 : raise
Tries to import the given Python module path .
53,324
def _pick_up_classes ( modules , classnames ) : klasses = [ ] for classname in classnames : klass = None for module in modules : if hasattr ( module , classname ) : klass = getattr ( module , classname ) break if not klass : raise ClassNotFoundError ( 'Error fetching \'{}\' in {}' . format ( classname , str ( [ module . __name__ for module in modules ] ) ) ) klasses . append ( klass ) return klasses
Given a list of class names to retrieve try to fetch them from the specified list of modules and returns the list of the fetched classes .
53,325
def _get_app_module_path ( module_label ) : app_name = module_label . rsplit ( '.' , 1 ) [ 0 ] for app in settings . INSTALLED_APPS : if app . endswith ( '.' + app_name ) or app == app_name : return app return None
Given a module label loop over the apps specified in the INSTALLED_APPS to find the corresponding application module path .
53,326
def get_unread_forums ( self , user ) : return self . get_unread_forums_from_list ( user , self . perm_handler . get_readable_forums ( Forum . objects . all ( ) , user ) )
Returns the list of unread forums for the given user .
53,327
def get_unread_forums_from_list ( self , user , forums ) : unread_forums = [ ] if not user . is_authenticated : return unread_forums unread = ForumReadTrack . objects . get_unread_forums_from_list ( forums , user ) unread_forums . extend ( unread ) return unread_forums
Returns the list of unread forums for the given user from a given list of forums .
53,328
def get_unread_topics ( self , topics , user ) : unread_topics = [ ] if not user . is_authenticated or topics is None or not len ( topics ) : return unread_topics topic_ids = [ topic . id for topic in topics ] topic_tracks = TopicReadTrack . objects . filter ( topic__in = topic_ids , user = user ) tracked_topics = dict ( topic_tracks . values_list ( 'topic__pk' , 'mark_time' ) ) if tracked_topics : for topic in topics : topic_last_modification_date = topic . last_post_on or topic . created if ( topic . id in tracked_topics . keys ( ) and topic_last_modification_date > tracked_topics [ topic . id ] ) : unread_topics . append ( topic ) forum_ids = [ topic . forum_id for topic in topics ] forum_tracks = ForumReadTrack . objects . filter ( forum_id__in = forum_ids , user = user ) tracked_forums = dict ( forum_tracks . values_list ( 'forum__pk' , 'mark_time' ) ) if tracked_forums : for topic in topics : topic_last_modification_date = topic . last_post_on or topic . created if ( ( topic . forum_id in tracked_forums . keys ( ) and topic . id not in tracked_topics ) and topic_last_modification_date > tracked_forums [ topic . forum_id ] ) : unread_topics . append ( topic ) for topic in topics : if topic . forum_id not in tracked_forums and topic . id not in tracked_topics : unread_topics . append ( topic ) return list ( set ( unread_topics ) )
Returns a list of unread topics for the given user from a given set of topics .
53,329
def mark_forums_read ( self , forums , user ) : if not forums or not user . is_authenticated : return forums = sorted ( forums , key = lambda f : f . level ) for forum in forums : forum_track = ForumReadTrack . objects . get_or_create ( forum = forum , user = user ) [ 0 ] forum_track . save ( ) TopicReadTrack . objects . filter ( topic__forum__in = forums , user = user ) . delete ( ) self . _update_parent_forum_tracks ( forums [ 0 ] , user )
Marks a list of forums as read .
53,330
def mark_topic_read ( self , topic , user ) : if not user . is_authenticated : return forum = topic . forum try : forum_track = ForumReadTrack . objects . get ( forum = forum , user = user ) except ForumReadTrack . DoesNotExist : forum_track = None if ( forum_track is None or ( topic . last_post_on and forum_track . mark_time < topic . last_post_on ) ) : topic_track , created = TopicReadTrack . objects . get_or_create ( topic = topic , user = user ) if not created : topic_track . save ( ) unread_topics = ( forum . topics . filter ( Q ( tracks__user = user , tracks__mark_time__lt = F ( 'last_post_on' ) ) | Q ( forum__tracks__user = user , forum__tracks__mark_time__lt = F ( 'last_post_on' ) , tracks__isnull = True , ) ) . exclude ( id = topic . id ) ) forum_topic_tracks = TopicReadTrack . objects . filter ( topic__forum = forum , user = user ) if ( not unread_topics . exists ( ) and ( forum_track is not None or forum_topic_tracks . count ( ) == forum . topics . filter ( approved = True ) . count ( ) ) ) : TopicReadTrack . objects . filter ( topic__forum = forum , user = user ) . delete ( ) forum_track , _ = ForumReadTrack . objects . get_or_create ( forum = forum , user = user ) forum_track . save ( ) self . _update_parent_forum_tracks ( forum , user )
Marks a topic as read .
53,331
def clean ( self ) : super ( ) . clean ( ) if self . parent and self . parent . is_link : raise ValidationError ( _ ( 'A forum can not have a link forum as parent' ) ) if self . is_category and self . parent and self . parent . is_category : raise ValidationError ( _ ( 'A category can not have another category as parent' ) ) if self . is_link and not self . link : raise ValidationError ( _ ( 'A link forum must have a link associated with it' ) )
Validates the forum instance .
53,332
def get_image_upload_to ( self , filename ) : dummy , ext = os . path . splitext ( filename ) return os . path . join ( machina_settings . FORUM_IMAGE_UPLOAD_TO , '{id}{ext}' . format ( id = str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) , ext = ext ) , )
Returns the path to upload a new associated image to .
53,333
def save ( self , * args , ** kwargs ) : old_instance = None if self . pk : old_instance = self . __class__ . _default_manager . get ( pk = self . pk ) self . slug = slugify ( force_text ( self . name ) , allow_unicode = True ) super ( ) . save ( * args , ** kwargs ) if old_instance and old_instance . parent != self . parent : self . update_trackers ( ) signals . forum_moved . send ( sender = self , previous_parent = old_instance . parent )
Saves the forum instance .
53,334
def update_trackers ( self ) : direct_approved_topics = self . topics . filter ( approved = True ) . order_by ( '-last_post_on' ) self . direct_topics_count = direct_approved_topics . count ( ) self . direct_posts_count = direct_approved_topics . aggregate ( total_posts_count = Sum ( 'posts_count' ) ) [ 'total_posts_count' ] or 0 if direct_approved_topics . exists ( ) : self . last_post_id = direct_approved_topics [ 0 ] . last_post_id self . last_post_on = direct_approved_topics [ 0 ] . last_post_on else : self . last_post_id = None self . last_post_on = None self . _simple_save ( )
Updates the denormalized trackers associated with the forum instance .
53,335
def get_unread_topics ( context , topics , user ) : request = context . get ( 'request' , None ) return TrackingHandler ( request = request ) . get_unread_topics ( topics , user )
This will return a list of unread topics for the given user from a given set of topics .
53,336
def resize_image ( self , data , size ) : from machina . core . compat import PILImage as Image image = Image . open ( BytesIO ( data ) ) image . thumbnail ( size , Image . ANTIALIAS ) string = BytesIO ( ) image . save ( string , format = 'PNG' ) return string . getvalue ( )
Resizes the given image to fit inside a box of the given size .
53,337
def get_backend ( self ) : try : cache = caches [ machina_settings . ATTACHMENT_CACHE_NAME ] except InvalidCacheBackendError : raise ImproperlyConfigured ( 'The attachment cache backend ({}) is not configured' . format ( machina_settings . ATTACHMENT_CACHE_NAME , ) , ) return cache
Returns the associated cache backend .
53,338
def set ( self , key , files ) : files_states = { } for name , upload in files . items ( ) : state = { 'name' : upload . name , 'size' : upload . size , 'content_type' : upload . content_type , 'charset' : upload . charset , 'content' : upload . file . read ( ) , } files_states [ name ] = state upload . file . seek ( 0 ) self . backend . set ( key , files_states )
Stores the state of each file embedded in the request . FILES MultiValueDict instance .
53,339
def get ( self , key ) : upload = None files_states = self . backend . get ( key ) files = MultiValueDict ( ) if files_states : for name , state in files_states . items ( ) : f = BytesIO ( ) f . write ( state [ 'content' ] ) if state [ 'size' ] > settings . FILE_UPLOAD_MAX_MEMORY_SIZE : upload = TemporaryUploadedFile ( state [ 'name' ] , state [ 'content_type' ] , state [ 'size' ] , state [ 'charset' ] , ) upload . file = f else : f = BytesIO ( ) f . write ( state [ 'content' ] ) upload = InMemoryUploadedFile ( file = f , field_name = name , name = state [ 'name' ] , content_type = state [ 'content_type' ] , size = state [ 'size' ] , charset = state [ 'charset' ] , ) files [ name ] = upload upload . file . seek ( 0 ) return files
Regenerates a MultiValueDict instance containing the files related to all file states stored for the given key .
53,340
def get_readable_forums ( self , forums , user ) : if user . is_superuser : return forums readable_forums = self . _get_forums_for_user ( user , [ 'can_read_forum' , ] , use_tree_hierarchy = True ) return forums . filter ( id__in = [ f . id for f in readable_forums ] ) if isinstance ( forums , ( models . Manager , models . QuerySet ) ) else list ( filter ( lambda f : f in readable_forums , forums ) )
Returns a queryset of forums that can be read by the considered user .
53,341
def can_add_post ( self , topic , user ) : can_add_post = self . _perform_basic_permission_check ( topic . forum , user , 'can_reply_to_topics' , ) can_add_post &= ( not topic . is_locked or self . _perform_basic_permission_check ( topic . forum , user , 'can_reply_to_locked_topics' ) ) return can_add_post
Given a topic checks whether the user can append posts to it .
53,342
def can_edit_post ( self , post , user ) : checker = self . _get_checker ( user ) is_author = self . _is_post_author ( post , user ) can_edit = ( user . is_superuser or ( is_author and checker . has_perm ( 'can_edit_own_posts' , post . topic . forum ) and not post . topic . is_locked ) or checker . has_perm ( 'can_edit_posts' , post . topic . forum ) ) return can_edit
Given a forum post checks whether the user can edit the latter .
53,343
def can_delete_post ( self , post , user ) : checker = self . _get_checker ( user ) is_author = self . _is_post_author ( post , user ) can_delete = ( user . is_superuser or ( is_author and checker . has_perm ( 'can_delete_own_posts' , post . topic . forum ) ) or checker . has_perm ( 'can_delete_posts' , post . topic . forum ) ) return can_delete
Given a forum post checks whether the user can delete the latter .
53,344
def can_vote_in_poll ( self , poll , user ) : if poll . duration : poll_dtend = poll . created + dt . timedelta ( days = poll . duration ) if poll_dtend < now ( ) : return False can_vote = ( self . _perform_basic_permission_check ( poll . topic . forum , user , 'can_vote_in_polls' ) and not poll . topic . is_locked ) user_votes = TopicPollVote . objects . filter ( poll_option__poll = poll ) if user . is_anonymous : forum_key = get_anonymous_user_forum_key ( user ) if forum_key : user_votes = user_votes . filter ( anonymous_key = forum_key ) else : user_votes = user_votes . none ( ) can_vote = False else : user_votes = user_votes . filter ( voter = user ) if user_votes . exists ( ) and can_vote : can_vote = poll . user_changes return can_vote
Given a poll checks whether the user can answer to it .
53,345
def can_subscribe_to_topic ( self , topic , user ) : return ( user . is_authenticated and not topic . has_subscriber ( user ) and self . _perform_basic_permission_check ( topic . forum , user , 'can_read_forum' ) )
Given a topic checks whether the user can add it to their subscription list .
53,346
def can_unsubscribe_from_topic ( self , topic , user ) : return ( user . is_authenticated and topic . has_subscriber ( user ) and self . _perform_basic_permission_check ( topic . forum , user , 'can_read_forum' ) )
Given a topic checks whether the user can remove it from their subscription list .
53,347
def get_target_forums_for_moved_topics ( self , user ) : return [ f for f in self . _get_forums_for_user ( user , [ 'can_move_topics' , ] ) if f . is_forum ]
Returns a list of forums in which the considered user can add topics that have been moved from another forum .
53,348
def can_update_topics_to_sticky_topics ( self , forum , user ) : return ( self . _perform_basic_permission_check ( forum , user , 'can_edit_posts' ) and self . _perform_basic_permission_check ( forum , user , 'can_post_stickies' ) )
Given a forum checks whether the user can change its topic types to sticky topics .
53,349
def can_update_topics_to_announces ( self , forum , user ) : return ( self . _perform_basic_permission_check ( forum , user , 'can_edit_posts' ) and self . _perform_basic_permission_check ( forum , user , 'can_post_announcements' ) )
Given a forum checks whether the user can change its topic types to announces .
53,350
def _get_hidden_forum_ids ( self , forums , user ) : visible_forums = self . _get_forums_for_user ( user , [ 'can_see_forum' , 'can_read_forum' , ] , use_tree_hierarchy = True , ) return forums . exclude ( id__in = [ f . id for f in visible_forums ] )
Given a set of forums and a user returns the list of forums that are not visible by this user .
53,351
def _perform_basic_permission_check ( self , forum , user , permission ) : checker = self . _get_checker ( user ) check = ( user . is_superuser or checker . has_perm ( permission , forum ) ) return check
Given a forum and a user checks whether the latter has the passed permission .
53,352
def _get_checker ( self , user ) : user_perm_checkers_cache_key = user . id if not user . is_anonymous else 'anonymous' if user_perm_checkers_cache_key in self . _user_perm_checkers_cache : return self . _user_perm_checkers_cache [ user_perm_checkers_cache_key ] checker = ForumPermissionChecker ( user ) self . _user_perm_checkers_cache [ user_perm_checkers_cache_key ] = checker return checker
Return a ForumPermissionChecker instance for the given user .
53,353
def _get_all_forums ( self ) : if not hasattr ( self , '_all_forums' ) : self . _all_forums = list ( Forum . objects . all ( ) ) return self . _all_forums
Returns all forums .
53,354
def get_forum ( self ) : if not hasattr ( self , 'forum' ) : self . forum = get_object_or_404 ( Forum , pk = self . kwargs [ 'pk' ] ) return self . forum
Returns the forum to consider .
53,355
def send_signal ( self , request , response , forum ) : self . view_signal . send ( sender = self , forum = forum , user = request . user , request = request , response = response , )
Sends the signal associated with the view .
53,356
def has_subscriber ( self , user ) : if not hasattr ( self , '_subscribers' ) : self . _subscribers = list ( self . subscribers . all ( ) ) return user in self . _subscribers
Returns True if the given user is a subscriber of this topic .
53,357
def clean ( self ) : super ( ) . clean ( ) if self . forum . is_category or self . forum . is_link : raise ValidationError ( _ ( 'A topic can not be associated with a category or a link forum' ) )
Validates the topic instance .
53,358
def save ( self , * args , ** kwargs ) : old_instance = None if self . pk : old_instance = self . __class__ . _default_manager . get ( pk = self . pk ) self . slug = slugify ( force_text ( self . subject ) , allow_unicode = True ) super ( ) . save ( * args , ** kwargs ) if old_instance and old_instance . forum != self . forum : self . update_trackers ( ) if old_instance . forum : old_forum = old_instance . forum old_forum . refresh_from_db ( ) old_forum . update_trackers ( )
Saves the topic instance .
53,359
def update_trackers ( self ) : self . posts_count = self . posts . filter ( approved = True ) . count ( ) first_post = self . posts . all ( ) . order_by ( 'created' ) . first ( ) last_post = self . posts . filter ( approved = True ) . order_by ( '-created' ) . first ( ) self . first_post = first_post self . last_post = last_post self . last_post_on = last_post . created if last_post else None self . _simple_save ( ) self . forum . update_trackers ( )
Updates the denormalized trackers associated with the topic instance .
53,360
def is_topic_head ( self ) : return self . topic . first_post . id == self . id if self . topic . first_post else False
Returns True if the post is the first post of the topic .
53,361
def is_topic_tail ( self ) : return self . topic . last_post . id == self . id if self . topic . last_post else False
Returns True if the post is the last post of the topic .
53,362
def position ( self ) : position = self . topic . posts . filter ( Q ( created__lt = self . created ) | Q ( id = self . id ) ) . count ( ) return position
Returns an integer corresponding to the position of the post in the topic .
53,363
def clean ( self ) : super ( ) . clean ( ) if self . poster is None and self . anonymous_key is None : raise ValidationError ( _ ( 'A user id or an anonymous key must be associated with a post.' ) , ) if self . poster and self . anonymous_key : raise ValidationError ( _ ( 'A user id or an anonymous key must be associated with a post, but not both.' ) , ) if self . anonymous_key and not self . username : raise ValidationError ( _ ( 'A username must be specified if the poster is anonymous' ) )
Validates the post instance .
53,364
def save ( self , * args , ** kwargs ) : new_post = self . pk is None super ( ) . save ( * args , ** kwargs ) if ( new_post and self . topic . first_post is None ) or self . is_topic_head : if self . subject != self . topic . subject or self . approved != self . topic . approved : self . topic . subject = self . subject self . topic . approved = self . approved self . topic . update_trackers ( )
Saves the post instance .
53,365
def delete ( self , using = None ) : if self . is_alone : self . topic . delete ( ) else : super ( AbstractPost , self ) . delete ( using ) self . topic . update_trackers ( )
Deletes the post instance .
53,366
def from_forums ( cls , forums ) : root_level = None current_path = [ ] nodes = [ ] forums = ( forums . select_related ( 'last_post' , 'last_post__poster' ) if isinstance ( forums , QuerySet ) else forums ) for forum in forums : level = forum . level if root_level is None : root_level = level vcontent_node = ForumVisibilityContentNode ( forum ) relative_level = level - root_level vcontent_node . relative_level = relative_level vcontent_node . children = [ ] while len ( current_path ) > relative_level : current_path . pop ( - 1 ) if level != root_level : parent_node = current_path [ - 1 ] vcontent_node . parent = parent_node parent_node . children . append ( vcontent_node ) vcontent_node . visible = ( ( relative_level == 0 ) or ( forum . display_sub_forum_list and relative_level == 1 ) or ( forum . is_category and relative_level == 1 ) or ( relative_level == 2 and vcontent_node . parent . parent . obj . is_category and vcontent_node . parent . obj . is_forum ) ) current_path . append ( vcontent_node ) nodes . append ( vcontent_node ) tree = cls ( nodes = nodes ) for node in tree . nodes : node . tree = tree return tree
Initializes a ForumVisibilityContentTree instance from a list of forums .
53,367
def last_post ( self ) : posts = [ n . last_post for n in self . children if n . last_post is not None ] children_last_post = max ( posts , key = lambda p : p . created ) if posts else None if children_last_post and self . obj . last_post_id : return max ( self . obj . last_post , children_last_post , key = lambda p : p . created ) return children_last_post or self . obj . last_post
Returns the latest post associated with the node or one of its descendants .
53,368
def last_post_on ( self ) : dates = [ n . last_post_on for n in self . children if n . last_post_on is not None ] children_last_post_on = max ( dates ) if dates else None if children_last_post_on and self . obj . last_post_on : return max ( self . obj . last_post_on , children_last_post_on ) return children_last_post_on or self . obj . last_post_on
Returns the latest post date associated with the node or one of its descendants .
53,369
def next_sibling ( self ) : if self . parent : nodes = self . parent . children index = nodes . index ( self ) sibling = nodes [ index + 1 ] if index < len ( nodes ) - 1 else None else : nodes = self . tree . nodes index = nodes . index ( self ) sibling = ( next ( ( n for n in nodes [ index + 1 : ] if n . level == self . level ) , None ) if index < len ( nodes ) - 1 else None ) return sibling
Returns the next sibling of the current node .
53,370
def posts_count ( self ) : return self . obj . direct_posts_count + sum ( n . posts_count for n in self . children )
Returns the number of posts associated with the current node and its descendants .
53,371
def previous_sibling ( self ) : if self . parent : nodes = self . parent . children index = nodes . index ( self ) sibling = nodes [ index - 1 ] if index > 0 else None else : nodes = self . tree . nodes index = nodes . index ( self ) sibling = ( next ( ( n for n in reversed ( nodes [ : index ] ) if n . level == self . level ) , None ) if index > 0 else None ) return sibling
Returns the previous sibling of the current node .
53,372
def topics_count ( self ) : return self . obj . direct_topics_count + sum ( n . topics_count for n in self . children )
Returns the number of topics associated with the current node and its descendants .
53,373
def has_perm ( self , perm , forum ) : if not self . user . is_anonymous and not self . user . is_active : return False elif self . user and self . user . is_superuser : return True return perm in self . get_perms ( forum )
Checks if the considered user has given permission for the passed forum .
53,374
def save ( self , commit = True , ** kwargs ) : if self . post : for form in self . forms : form . instance . post = self . post super ( ) . save ( commit )
Saves the considered instances .
53,375
def get_required_permissions ( self , request ) : perms = [ ] if not self . permission_required : return perms if isinstance ( self . permission_required , string_types ) : perms = [ self . permission_required , ] elif isinstance ( self . permission_required , Iterable ) : perms = [ perm for perm in self . permission_required ] else : raise ImproperlyConfigured ( '\'PermissionRequiredMixin\' requires \'permission_required\' ' 'attribute to be set to \'<app_label>.<permission codename>\' but is set to {} ' 'instead' . format ( self . permission_required ) ) return perms
Returns the required permissions to access the considered object .
53,376
def check_permissions ( self , request ) : obj = ( hasattr ( self , 'get_controlled_object' ) and self . get_controlled_object ( ) or hasattr ( self , 'get_object' ) and self . get_object ( ) or getattr ( self , 'object' , None ) ) user = request . user perms = self . get_required_permissions ( self ) has_permissions = self . perform_permissions_check ( user , obj , perms ) if not has_permissions and not user . is_authenticated : return HttpResponseRedirect ( '{}?{}={}' . format ( resolve_url ( self . login_url ) , self . redirect_field_name , urlquote ( request . get_full_path ( ) ) ) ) elif not has_permissions : raise PermissionDenied
Retrieves the controlled object and perform the permissions check .
53,377
def dispatch ( self , request , * args , ** kwargs ) : self . request = request self . args = args self . kwargs = kwargs response = self . check_permissions ( request ) if response : return response return super ( ) . dispatch ( request , * args , ** kwargs )
Dispatches an incoming request .
53,378
def update_user_trackers ( sender , topic , user , request , response , ** kwargs ) : TrackingHandler = get_class ( 'forum_tracking.handler' , 'TrackingHandler' ) track_handler = TrackingHandler ( ) track_handler . mark_topic_read ( topic , user )
Receiver to mark a topic being viewed as read .
53,379
def update_forum_redirects_counter ( sender , forum , user , request , response , ** kwargs ) : if forum . is_link and forum . link_redirects : forum . link_redirects_count = F ( 'link_redirects_count' ) + 1 forum . save ( )
Handles the update of the link redirects counter associated with link forums .
53,380
def get_avatar_upload_to ( self , filename ) : dummy , ext = os . path . splitext ( filename ) return os . path . join ( machina_settings . PROFILE_AVATAR_UPLOAD_TO , '{id}{ext}' . format ( id = str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) , ext = ext ) , )
Returns the path to upload the associated avatar to .
53,381
def get_queryset ( self ) : qs = super ( ) . get_queryset ( ) qs = qs . filter ( approved = True ) return qs
Returns all the approved topics or posts .
53,382
def votes ( self ) : votes = [ ] for option in self . options . all ( ) : votes += option . votes . all ( ) return votes
Returns all the votes related to this topic poll .
53,383
def clean ( self ) : super ( ) . clean ( ) if self . voter is None and self . anonymous_key is None : raise ValidationError ( _ ( 'A user id or an anonymous key must be used.' ) ) if self . voter and self . anonymous_key : raise ValidationError ( _ ( 'A user id or an anonymous key must be used, but not both.' ) )
Validates the considered instance .
53,384
def get_top_level_forum_url ( self ) : return ( reverse ( 'forum:index' ) if self . top_level_forum is None else reverse ( 'forum:forum' , kwargs = { 'slug' : self . top_level_forum . slug , 'pk' : self . kwargs [ 'pk' ] } , ) )
Returns the parent forum from which forums are marked as read .
53,385
def mark_as_read ( self , request , pk ) : if self . top_level_forum is not None : forums = request . forum_permission_handler . get_readable_forums ( self . top_level_forum . get_descendants ( include_self = True ) , request . user , ) else : forums = request . forum_permission_handler . get_readable_forums ( Forum . objects . all ( ) , request . user , ) track_handler . mark_forums_read ( forums , request . user ) if len ( forums ) : messages . success ( request , self . success_message ) return HttpResponseRedirect ( self . get_top_level_forum_url ( ) )
Marks the considered forums as read .
53,386
def get_forum_url ( self ) : return reverse ( 'forum:forum' , kwargs = { 'slug' : self . forum . slug , 'pk' : self . forum . pk } )
Returns the url of the forum whose topics will be marked read .
53,387
def mark_topics_read ( self , request , pk ) : track_handler . mark_forums_read ( [ self . forum , ] , request . user ) messages . success ( request , self . success_message ) return HttpResponseRedirect ( self . get_forum_url ( ) )
Marks forum topics as read .
53,388
def get_model ( app_label , model_name ) : try : return apps . get_model ( app_label , model_name ) except AppRegistryNotReady : if apps . apps_ready and not apps . models_ready : app_config = apps . get_app_config ( app_label ) import_module ( '%s.%s' % ( app_config . name , MODELS_MODULE_NAME ) ) return apps . get_registered_model ( app_label , model_name ) else : raise
Given an app label and a model name returns the corresponding model class .
53,389
def is_model_registered ( app_label , model_name ) : try : apps . get_registered_model ( app_label , model_name ) except LookupError : return False else : return True
Checks whether the given model is registered or not .
53,390
def clean ( self ) : super ( ) . clean ( ) if ( ( self . user is None and not self . anonymous_user ) or ( self . user and self . anonymous_user ) ) : raise ValidationError ( _ ( 'A permission should target either a user or an anonymous user' ) , )
Validates the current instance .
53,391
def render_to_response ( self , context , ** response_kwargs ) : filename = os . path . basename ( self . object . file . name ) content_type , _ = mimetypes . guess_type ( self . object . file . name ) if not content_type : content_type = 'text/plain' response = HttpResponse ( self . object . file , content_type = content_type ) response [ 'Content-Disposition' ] = 'attachment; filename={}' . format ( filename ) return response
Generates the appropriate response .
53,392
def get_form_kwargs ( self ) : kwargs = super ( ModelFormMixin , self ) . get_form_kwargs ( ) kwargs [ 'poll' ] = self . object return kwargs
Returns the keyword arguments to provide tp the associated form .
53,393
def form_invalid ( self , form ) : messages . error ( self . request , form . errors [ NON_FIELD_ERRORS ] ) return redirect ( reverse ( 'forum_conversation:topic' , kwargs = { 'forum_slug' : self . object . topic . forum . slug , 'forum_pk' : self . object . topic . forum . pk , 'slug' : self . object . topic . slug , 'pk' : self . object . topic . pk } , ) , )
Handles an invalid form .
53,394
def has_been_completed_by ( poll , user ) : user_votes = TopicPollVote . objects . filter ( poll_option__poll = poll ) if user . is_anonymous : forum_key = get_anonymous_user_forum_key ( user ) user_votes = user_votes . filter ( anonymous_key = forum_key ) if forum_key else user_votes . none ( ) else : user_votes = user_votes . filter ( voter = user ) return user_votes . exists ( )
This will return a boolean indicating if the passed user has already voted in the given poll .
53,395
def get_unread_forums_from_list ( self , forums , user ) : unread_forums = [ ] visibility_contents = ForumVisibilityContentTree . from_forums ( forums ) forum_ids_to_visibility_nodes = visibility_contents . as_dict tracks = super ( ) . get_queryset ( ) . select_related ( 'forum' ) . filter ( user = user , forum__in = forums ) tracked_forums = [ ] for track in tracks : forum_last_post_on = forum_ids_to_visibility_nodes [ track . forum_id ] . last_post_on if ( forum_last_post_on and track . mark_time < forum_last_post_on ) and track . forum not in unread_forums : unread_forums . extend ( track . forum . get_ancestors ( include_self = True ) ) tracked_forums . append ( track . forum ) for forum in forums : if forum not in tracked_forums and forum not in unread_forums and forum . direct_topics_count > 0 : unread_forums . extend ( forum . get_ancestors ( include_self = True ) ) return list ( set ( unread_forums ) )
Filter a list of forums and return only those which are unread .
53,396
def increase_posts_count ( sender , instance , ** kwargs ) : if instance . poster is None : return profile , dummy = ForumProfile . objects . get_or_create ( user = instance . poster ) increase_posts_count = False if instance . pk : try : old_instance = instance . __class__ . _default_manager . get ( pk = instance . pk ) except ObjectDoesNotExist : increase_posts_count = True old_instance = None if old_instance and old_instance . approved is False and instance . approved is True : increase_posts_count = True elif instance . approved : increase_posts_count = True if increase_posts_count : profile . posts_count = F ( 'posts_count' ) + 1 profile . save ( )
Increases the member s post count after a post save .
53,397
def decrease_posts_count_after_post_unaproval ( sender , instance , ** kwargs ) : if not instance . pk : return profile , dummy = ForumProfile . objects . get_or_create ( user = instance . poster ) try : old_instance = instance . __class__ . _default_manager . get ( pk = instance . pk ) except ObjectDoesNotExist : return if old_instance and old_instance . approved is True and instance . approved is False : profile . posts_count = F ( 'posts_count' ) - 1 profile . save ( )
Decreases the member s post count after a post unaproval .
53,398
def decrease_posts_count_after_post_deletion ( sender , instance , ** kwargs ) : if not instance . approved : return try : assert instance . poster_id is not None poster = User . objects . get ( pk = instance . poster_id ) except AssertionError : return except ObjectDoesNotExist : return profile , dummy = ForumProfile . objects . get_or_create ( user = poster ) if profile . posts_count : profile . posts_count = F ( 'posts_count' ) - 1 profile . save ( )
Decreases the member s post count after a post deletion .
53,399
def lock ( self , request , * args , ** kwargs ) : self . object = self . get_object ( ) success_url = self . get_success_url ( ) self . object . status = Topic . TOPIC_LOCKED self . object . save ( ) messages . success ( self . request , self . success_message ) return HttpResponseRedirect ( success_url )
Locks the considered topic and retirects the user to the success URL .