repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
ellmetha/django-machina
machina/templatetags/forum_tracking_tags.py
get_unread_topics
def get_unread_topics(context, topics, user): """ This will return a list of unread topics for the given user from a given set of topics. Usage:: {% get_unread_topics topics request.user as unread_topics %} """ request = context.get('request', None) return TrackingHandler(request=request).get_unread_topics(topics, user)
python
def get_unread_topics(context, topics, user): """ This will return a list of unread topics for the given user from a given set of topics. Usage:: {% get_unread_topics topics request.user as unread_topics %} """ request = context.get('request', None) return TrackingHandler(request=request).get_unread_topics(topics, user)
[ "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. Usage:: {% get_unread_topics topics request.user as unread_topics %}
[ "This", "will", "return", "a", "list", "of", "unread", "topics", "for", "the", "given", "user", "from", "a", "given", "set", "of", "topics", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tracking_tags.py#L12-L21
train
ellmetha/django-machina
machina/models/fields.py
ExtendedImageField.resize_image
def resize_image(self, data, size): """ Resizes the given image to fit inside a box of the given size. """ from machina.core.compat import PILImage as Image image = Image.open(BytesIO(data)) # Resize! image.thumbnail(size, Image.ANTIALIAS) string = BytesIO() image.save(string, format='PNG') return string.getvalue()
python
def resize_image(self, data, size): """ Resizes the given image to fit inside a box of the given size. """ from machina.core.compat import PILImage as Image image = Image.open(BytesIO(data)) # Resize! image.thumbnail(size, Image.ANTIALIAS) string = BytesIO() image.save(string, format='PNG') return string.getvalue()
[ "def", "resize_image", "(", "self", ",", "data", ",", "size", ")", ":", "from", "machina", ".", "core", ".", "compat", "import", "PILImage", "as", "Image", "image", "=", "Image", ".", "open", "(", "BytesIO", "(", "data", ")", ")", "# Resize!", "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.
[ "Resizes", "the", "given", "image", "to", "fit", "inside", "a", "box", "of", "the", "given", "size", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/models/fields.py#L260-L270
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/cache.py
AttachmentCache.get_backend
def get_backend(self): """ Returns the associated cache backend. """ 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
python
def get_backend(self): """ Returns the associated cache backend. """ 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
[ "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.
[ "Returns", "the", "associated", "cache", "backend", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L33-L43
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/cache.py
AttachmentCache.set
def set(self, key, files): """ Stores the state of each file embedded in the request.FILES MultiValueDict instance. This instance is assumed to be passed as the 'files' argument. Each state stored in the cache is a dictionary containing the following values: name The name of the uploaded file. size The size of the uploaded file. content_type The content type of the uploaded file. content_length The content length of the uploaded file. charset The charset of the uploaded file. content The content of the uploaded file. """ files_states = {} for name, upload in files.items(): # Generates the state of the file state = { 'name': upload.name, 'size': upload.size, 'content_type': upload.content_type, 'charset': upload.charset, 'content': upload.file.read(), } files_states[name] = state # Go to the first byte in the file for future use upload.file.seek(0) self.backend.set(key, files_states)
python
def set(self, key, files): """ Stores the state of each file embedded in the request.FILES MultiValueDict instance. This instance is assumed to be passed as the 'files' argument. Each state stored in the cache is a dictionary containing the following values: name The name of the uploaded file. size The size of the uploaded file. content_type The content type of the uploaded file. content_length The content length of the uploaded file. charset The charset of the uploaded file. content The content of the uploaded file. """ files_states = {} for name, upload in files.items(): # Generates the state of the file state = { 'name': upload.name, 'size': upload.size, 'content_type': upload.content_type, 'charset': upload.charset, 'content': upload.file.read(), } files_states[name] = state # Go to the first byte in the file for future use upload.file.seek(0) self.backend.set(key, files_states)
[ "def", "set", "(", "self", ",", "key", ",", "files", ")", ":", "files_states", "=", "{", "}", "for", "name", ",", "upload", "in", "files", ".", "items", "(", ")", ":", "# Generates the state of the file", "state", "=", "{", "'name'", ":", "upload", ".", "name", ",", "'size'", ":", "upload", ".", "size", ",", "'content_type'", ":", "upload", ".", "content_type", ",", "'charset'", ":", "upload", ".", "charset", ",", "'content'", ":", "upload", ".", "file", ".", "read", "(", ")", ",", "}", "files_states", "[", "name", "]", "=", "state", "# Go to the first byte in the file for future use", "upload", ".", "file", ".", "seek", "(", "0", ")", "self", ".", "backend", ".", "set", "(", "key", ",", "files_states", ")" ]
Stores the state of each file embedded in the request.FILES MultiValueDict instance. This instance is assumed to be passed as the 'files' argument. Each state stored in the cache is a dictionary containing the following values: name The name of the uploaded file. size The size of the uploaded file. content_type The content type of the uploaded file. content_length The content length of the uploaded file. charset The charset of the uploaded file. content The content of the uploaded file.
[ "Stores", "the", "state", "of", "each", "file", "embedded", "in", "the", "request", ".", "FILES", "MultiValueDict", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L45-L80
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/cache.py
AttachmentCache.get
def get(self, key): """ Regenerates a MultiValueDict instance containing the files related to all file states stored for the given 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 the post is too large, we cannot use a # InMemoryUploadedFile instance. 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 # Go to the first byte in the file for future use upload.file.seek(0) return files
python
def get(self, key): """ Regenerates a MultiValueDict instance containing the files related to all file states stored for the given 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 the post is too large, we cannot use a # InMemoryUploadedFile instance. 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 # Go to the first byte in the file for future use upload.file.seek(0) return files
[ "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 the post is too large, we cannot use a", "# InMemoryUploadedFile instance.", "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", "# Go to the first byte in the file for future use", "upload", ".", "file", ".", "seek", "(", "0", ")", "return", "files" ]
Regenerates a MultiValueDict instance containing the files related to all file states stored for the given key.
[ "Regenerates", "a", "MultiValueDict", "instance", "containing", "the", "files", "related", "to", "all", "file", "states", "stored", "for", "the", "given", "key", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L82-L120
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.get_readable_forums
def get_readable_forums(self, forums, user): """ Returns a queryset of forums that can be read by the considered user. """ # Any superuser should be able to read all the forums. if user.is_superuser: return forums # Fetches the forums that can be read by the given user. 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))
python
def get_readable_forums(self, forums, user): """ Returns a queryset of forums that can be read by the considered user. """ # Any superuser should be able to read all the forums. if user.is_superuser: return forums # Fetches the forums that can be read by the given user. 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))
[ "def", "get_readable_forums", "(", "self", ",", "forums", ",", "user", ")", ":", "# Any superuser should be able to read all the forums.", "if", "user", ".", "is_superuser", ":", "return", "forums", "# Fetches the forums that can be read by the given user.", "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.
[ "Returns", "a", "queryset", "of", "forums", "that", "can", "be", "read", "by", "the", "considered", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L74-L85
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_add_post
def can_add_post(self, topic, user): """ Given a topic, checks whether the user can append posts to it. """ 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
python
def can_add_post(self, topic, user): """ Given a topic, checks whether the user can append posts to it. """ 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
[ "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.
[ "Given", "a", "topic", "checks", "whether", "the", "user", "can", "append", "posts", "to", "it", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L114-L123
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_edit_post
def can_edit_post(self, post, user): """ Given a forum post, checks whether the user can edit the latter. """ checker = self._get_checker(user) # A user can edit a post if... # they are a superuser # they are the original poster of the forum post # they belong to the forum moderators 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
python
def can_edit_post(self, post, user): """ Given a forum post, checks whether the user can edit the latter. """ checker = self._get_checker(user) # A user can edit a post if... # they are a superuser # they are the original poster of the forum post # they belong to the forum moderators 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
[ "def", "can_edit_post", "(", "self", ",", "post", ",", "user", ")", ":", "checker", "=", "self", ".", "_get_checker", "(", "user", ")", "# A user can edit a post if...", "# they are a superuser", "# they are the original poster of the forum post", "# they belong to the forum moderators", "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.
[ "Given", "a", "forum", "post", "checks", "whether", "the", "user", "can", "edit", "the", "latter", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L125-L142
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_delete_post
def can_delete_post(self, post, user): """ Given a forum post, checks whether the user can delete the latter. """ checker = self._get_checker(user) # A user can delete a post if... # they are a superuser # they are the original poster of the forum post # they belong to the forum moderators 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
python
def can_delete_post(self, post, user): """ Given a forum post, checks whether the user can delete the latter. """ checker = self._get_checker(user) # A user can delete a post if... # they are a superuser # they are the original poster of the forum post # they belong to the forum moderators 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
[ "def", "can_delete_post", "(", "self", ",", "post", ",", "user", ")", ":", "checker", "=", "self", ".", "_get_checker", "(", "user", ")", "# A user can delete a post if...", "# they are a superuser", "# they are the original poster of the forum post", "# they belong to the forum moderators", "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.
[ "Given", "a", "forum", "post", "checks", "whether", "the", "user", "can", "delete", "the", "latter", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L144-L160
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_vote_in_poll
def can_vote_in_poll(self, poll, user): """ Given a poll, checks whether the user can answer to it. """ # First we have to check if the poll is curently open if poll.duration: poll_dtend = poll.created + dt.timedelta(days=poll.duration) if poll_dtend < now(): return False # Is this user allowed to vote in polls in the current forum? can_vote = ( self._perform_basic_permission_check(poll.topic.forum, user, 'can_vote_in_polls') and not poll.topic.is_locked ) # Retrieve the user votes for the considered poll 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: # If the forum key of the anonymous user cannot be retrieved, the user should not be # allowed to vote in the considered poll. user_votes = user_votes.none() can_vote = False else: user_votes = user_votes.filter(voter=user) # If the user has already voted, they can vote again if the vote changes are allowed if user_votes.exists() and can_vote: can_vote = poll.user_changes return can_vote
python
def can_vote_in_poll(self, poll, user): """ Given a poll, checks whether the user can answer to it. """ # First we have to check if the poll is curently open if poll.duration: poll_dtend = poll.created + dt.timedelta(days=poll.duration) if poll_dtend < now(): return False # Is this user allowed to vote in polls in the current forum? can_vote = ( self._perform_basic_permission_check(poll.topic.forum, user, 'can_vote_in_polls') and not poll.topic.is_locked ) # Retrieve the user votes for the considered poll 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: # If the forum key of the anonymous user cannot be retrieved, the user should not be # allowed to vote in the considered poll. user_votes = user_votes.none() can_vote = False else: user_votes = user_votes.filter(voter=user) # If the user has already voted, they can vote again if the vote changes are allowed if user_votes.exists() and can_vote: can_vote = poll.user_changes return can_vote
[ "def", "can_vote_in_poll", "(", "self", ",", "poll", ",", "user", ")", ":", "# First we have to check if the poll is curently open", "if", "poll", ".", "duration", ":", "poll_dtend", "=", "poll", ".", "created", "+", "dt", ".", "timedelta", "(", "days", "=", "poll", ".", "duration", ")", "if", "poll_dtend", "<", "now", "(", ")", ":", "return", "False", "# Is this user allowed to vote in polls in the current forum?", "can_vote", "=", "(", "self", ".", "_perform_basic_permission_check", "(", "poll", ".", "topic", ".", "forum", ",", "user", ",", "'can_vote_in_polls'", ")", "and", "not", "poll", ".", "topic", ".", "is_locked", ")", "# Retrieve the user votes for the considered poll", "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", ":", "# If the forum key of the anonymous user cannot be retrieved, the user should not be", "# allowed to vote in the considered poll.", "user_votes", "=", "user_votes", ".", "none", "(", ")", "can_vote", "=", "False", "else", ":", "user_votes", "=", "user_votes", ".", "filter", "(", "voter", "=", "user", ")", "# If the user has already voted, they can vote again if the vote changes are allowed", "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.
[ "Given", "a", "poll", "checks", "whether", "the", "user", "can", "answer", "to", "it", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L168-L200
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_subscribe_to_topic
def can_subscribe_to_topic(self, topic, user): """ Given a topic, checks whether the user can add it to their subscription list. """ # A user can subscribe to topics if they are authenticated and if they have the permission # to read the related forum. Of course a user can subscribe only if they have not already # subscribed to the considered topic. return ( user.is_authenticated and not topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, 'can_read_forum') )
python
def can_subscribe_to_topic(self, topic, user): """ Given a topic, checks whether the user can add it to their subscription list. """ # A user can subscribe to topics if they are authenticated and if they have the permission # to read the related forum. Of course a user can subscribe only if they have not already # subscribed to the considered topic. return ( user.is_authenticated and not topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, 'can_read_forum') )
[ "def", "can_subscribe_to_topic", "(", "self", ",", "topic", ",", "user", ")", ":", "# A user can subscribe to topics if they are authenticated and if they have the permission", "# to read the related forum. Of course a user can subscribe only if they have not already", "# subscribed to the considered topic.", "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.
[ "Given", "a", "topic", "checks", "whether", "the", "user", "can", "add", "it", "to", "their", "subscription", "list", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L214-L223
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_unsubscribe_from_topic
def can_unsubscribe_from_topic(self, topic, user): """ Given a topic, checks whether the user can remove it from their subscription list. """ # A user can unsubscribe from topics if they are authenticated and if they have the # permission to read the related forum. Of course a user can unsubscribe only if they are # already a subscriber of the considered topic. return ( user.is_authenticated and topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, 'can_read_forum') )
python
def can_unsubscribe_from_topic(self, topic, user): """ Given a topic, checks whether the user can remove it from their subscription list. """ # A user can unsubscribe from topics if they are authenticated and if they have the # permission to read the related forum. Of course a user can unsubscribe only if they are # already a subscriber of the considered topic. return ( user.is_authenticated and topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, 'can_read_forum') )
[ "def", "can_unsubscribe_from_topic", "(", "self", ",", "topic", ",", "user", ")", ":", "# A user can unsubscribe from topics if they are authenticated and if they have the", "# permission to read the related forum. Of course a user can unsubscribe only if they are", "# already a subscriber of the considered topic.", "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.
[ "Given", "a", "topic", "checks", "whether", "the", "user", "can", "remove", "it", "from", "their", "subscription", "list", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L225-L234
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.get_target_forums_for_moved_topics
def get_target_forums_for_moved_topics(self, user): """ Returns a list of forums in which the considered user can add topics that have been moved from another forum. """ return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum]
python
def get_target_forums_for_moved_topics(self, user): """ Returns a list of forums in which the considered user can add topics that have been moved from another forum. """ return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum]
[ "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.
[ "Returns", "a", "list", "of", "forums", "in", "which", "the", "considered", "user", "can", "add", "topics", "that", "have", "been", "moved", "from", "another", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L254-L258
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_update_topics_to_sticky_topics
def can_update_topics_to_sticky_topics(self, forum, user): """ Given a forum, checks whether the user can change its topic types to sticky topics. """ return ( self._perform_basic_permission_check(forum, user, 'can_edit_posts') and self._perform_basic_permission_check(forum, user, 'can_post_stickies') )
python
def can_update_topics_to_sticky_topics(self, forum, user): """ Given a forum, checks whether the user can change its topic types to sticky topics. """ return ( self._perform_basic_permission_check(forum, user, 'can_edit_posts') and self._perform_basic_permission_check(forum, user, 'can_post_stickies') )
[ "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.
[ "Given", "a", "forum", "checks", "whether", "the", "user", "can", "change", "its", "topic", "types", "to", "sticky", "topics", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L273-L278
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler.can_update_topics_to_announces
def can_update_topics_to_announces(self, forum, user): """ Given a forum, checks whether the user can change its topic types to announces. """ return ( self._perform_basic_permission_check(forum, user, 'can_edit_posts') and self._perform_basic_permission_check(forum, user, 'can_post_announcements') )
python
def can_update_topics_to_announces(self, forum, user): """ Given a forum, checks whether the user can change its topic types to announces. """ return ( self._perform_basic_permission_check(forum, user, 'can_edit_posts') and self._perform_basic_permission_check(forum, user, 'can_post_announcements') )
[ "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.
[ "Given", "a", "forum", "checks", "whether", "the", "user", "can", "change", "its", "topic", "types", "to", "announces", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L280-L285
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler._get_hidden_forum_ids
def _get_hidden_forum_ids(self, forums, user): """ Given a set of forums and a user, returns the list of forums that are not visible by this 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])
python
def _get_hidden_forum_ids(self, forums, user): """ Given a set of forums and a user, returns the list of forums that are not visible by this 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])
[ "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.
[ "Given", "a", "set", "of", "forums", "and", "a", "user", "returns", "the", "list", "of", "forums", "that", "are", "not", "visible", "by", "this", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L303-L310
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler._perform_basic_permission_check
def _perform_basic_permission_check(self, forum, user, permission): """ Given a forum and a user, checks whether the latter has the passed permission. The workflow is: 1. The permission is granted if the user is a superuser 2. If not, a check is performed with the given permission """ checker = self._get_checker(user) # The action is granted if... # the user is the superuser # the user has the permission to do so check = (user.is_superuser or checker.has_perm(permission, forum)) return check
python
def _perform_basic_permission_check(self, forum, user, permission): """ Given a forum and a user, checks whether the latter has the passed permission. The workflow is: 1. The permission is granted if the user is a superuser 2. If not, a check is performed with the given permission """ checker = self._get_checker(user) # The action is granted if... # the user is the superuser # the user has the permission to do so check = (user.is_superuser or checker.has_perm(permission, forum)) return check
[ "def", "_perform_basic_permission_check", "(", "self", ",", "forum", ",", "user", ",", "permission", ")", ":", "checker", "=", "self", ".", "_get_checker", "(", "user", ")", "# The action is granted if...", "# the user is the superuser", "# the user has the permission to do so", "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. The workflow is: 1. The permission is granted if the user is a superuser 2. If not, a check is performed with the given permission
[ "Given", "a", "forum", "and", "a", "user", "checks", "whether", "the", "latter", "has", "the", "passed", "permission", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L480-L495
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler._get_checker
def _get_checker(self, user): """ Return a ForumPermissionChecker instance for the given 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
python
def _get_checker(self, user): """ Return a ForumPermissionChecker instance for the given 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
[ "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.
[ "Return", "a", "ForumPermissionChecker", "instance", "for", "the", "given", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L497-L506
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
PermissionHandler._get_all_forums
def _get_all_forums(self): """ Returns all forums. """ if not hasattr(self, '_all_forums'): self._all_forums = list(Forum.objects.all()) return self._all_forums
python
def _get_all_forums(self): """ Returns all forums. """ if not hasattr(self, '_all_forums'): self._all_forums = list(Forum.objects.all()) return self._all_forums
[ "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.
[ "Returns", "all", "forums", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L508-L512
train
ellmetha/django-machina
machina/apps/forum/views.py
ForumView.get_forum
def get_forum(self): """ Returns the forum to consider. """ if not hasattr(self, 'forum'): self.forum = get_object_or_404(Forum, pk=self.kwargs['pk']) return self.forum
python
def get_forum(self): """ Returns the forum to consider. """ if not hasattr(self, 'forum'): self.forum = get_object_or_404(Forum, pk=self.kwargs['pk']) return self.forum
[ "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.
[ "Returns", "the", "forum", "to", "consider", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/views.py#L74-L78
train
ellmetha/django-machina
machina/apps/forum/views.py
ForumView.send_signal
def send_signal(self, request, response, forum): """ Sends the signal associated with the view. """ self.view_signal.send( sender=self, forum=forum, user=request.user, request=request, response=response, )
python
def send_signal(self, request, response, forum): """ Sends the signal associated with the view. """ self.view_signal.send( sender=self, forum=forum, user=request.user, request=request, response=response, )
[ "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.
[ "Sends", "the", "signal", "associated", "with", "the", "view", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/views.py#L123-L127
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractTopic.has_subscriber
def has_subscriber(self, user): """ Returns ``True`` if the given user is a subscriber of this topic. """ if not hasattr(self, '_subscribers'): self._subscribers = list(self.subscribers.all()) return user in self._subscribers
python
def has_subscriber(self, user): """ Returns ``True`` if the given user is a subscriber of this topic. """ if not hasattr(self, '_subscribers'): self._subscribers = list(self.subscribers.all()) return user in self._subscribers
[ "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.
[ "Returns", "True", "if", "the", "given", "user", "is", "a", "subscriber", "of", "this", "topic", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L133-L137
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractTopic.clean
def clean(self): """ Validates the topic instance. """ 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') )
python
def clean(self): """ Validates the topic instance. """ 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') )
[ "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.
[ "Validates", "the", "topic", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L139-L145
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractTopic.save
def save(self, *args, **kwargs): """ Saves the topic instance. """ # It is vital to track the changes of the forum associated with a topic in order to # maintain counters up-to-date. old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) # Update the slug field self.slug = slugify(force_text(self.subject), allow_unicode=True) # Do the save super().save(*args, **kwargs) # If any change has been made to the parent forum, trigger the update of the counters if old_instance and old_instance.forum != self.forum: self.update_trackers() # The previous parent forum counters should also be updated if old_instance.forum: old_forum = old_instance.forum old_forum.refresh_from_db() old_forum.update_trackers()
python
def save(self, *args, **kwargs): """ Saves the topic instance. """ # It is vital to track the changes of the forum associated with a topic in order to # maintain counters up-to-date. old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) # Update the slug field self.slug = slugify(force_text(self.subject), allow_unicode=True) # Do the save super().save(*args, **kwargs) # If any change has been made to the parent forum, trigger the update of the counters if old_instance and old_instance.forum != self.forum: self.update_trackers() # The previous parent forum counters should also be updated if old_instance.forum: old_forum = old_instance.forum old_forum.refresh_from_db() old_forum.update_trackers()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# It is vital to track the changes of the forum associated with a topic in order to", "# maintain counters up-to-date.", "old_instance", "=", "None", "if", "self", ".", "pk", ":", "old_instance", "=", "self", ".", "__class__", ".", "_default_manager", ".", "get", "(", "pk", "=", "self", ".", "pk", ")", "# Update the slug field", "self", ".", "slug", "=", "slugify", "(", "force_text", "(", "self", ".", "subject", ")", ",", "allow_unicode", "=", "True", ")", "# Do the save", "super", "(", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# If any change has been made to the parent forum, trigger the update of the counters", "if", "old_instance", "and", "old_instance", ".", "forum", "!=", "self", ".", "forum", ":", "self", ".", "update_trackers", "(", ")", "# The previous parent forum counters should also be updated", "if", "old_instance", ".", "forum", ":", "old_forum", "=", "old_instance", ".", "forum", "old_forum", ".", "refresh_from_db", "(", ")", "old_forum", ".", "update_trackers", "(", ")" ]
Saves the topic instance.
[ "Saves", "the", "topic", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L147-L168
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractTopic.update_trackers
def update_trackers(self): """ Updates the denormalized trackers associated with the topic instance. """ 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() # Trigger the forum-level trackers update self.forum.update_trackers()
python
def update_trackers(self): """ Updates the denormalized trackers associated with the topic instance. """ 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() # Trigger the forum-level trackers update self.forum.update_trackers()
[ "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", "(", ")", "# Trigger the forum-level trackers update", "self", ".", "forum", ".", "update_trackers", "(", ")" ]
Updates the denormalized trackers associated with the topic instance.
[ "Updates", "the", "denormalized", "trackers", "associated", "with", "the", "topic", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L188-L198
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.is_topic_head
def is_topic_head(self): """ Returns ``True`` if the post is the first post of the topic. """ return self.topic.first_post.id == self.id if self.topic.first_post else False
python
def is_topic_head(self): """ Returns ``True`` if the post is the first post of the topic. """ return self.topic.first_post.id == self.id if self.topic.first_post else False
[ "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.
[ "Returns", "True", "if", "the", "post", "is", "the", "first", "post", "of", "the", "topic", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L269-L271
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.is_topic_tail
def is_topic_tail(self): """ Returns ``True`` if the post is the last post of the topic. """ return self.topic.last_post.id == self.id if self.topic.last_post else False
python
def is_topic_tail(self): """ Returns ``True`` if the post is the last post of the topic. """ return self.topic.last_post.id == self.id if self.topic.last_post else False
[ "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.
[ "Returns", "True", "if", "the", "post", "is", "the", "last", "post", "of", "the", "topic", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L274-L276
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.position
def position(self): """ Returns an integer corresponding to the position of the post in the topic. """ position = self.topic.posts.filter(Q(created__lt=self.created) | Q(id=self.id)).count() return position
python
def position(self): """ Returns an integer corresponding to the position of the post in the topic. """ position = self.topic.posts.filter(Q(created__lt=self.created) | Q(id=self.id)).count() return position
[ "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.
[ "Returns", "an", "integer", "corresponding", "to", "the", "position", "of", "the", "post", "in", "the", "topic", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L284-L287
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.clean
def clean(self): """ Validates the post instance. """ super().clean() # At least a poster (user) or a session key must be associated with # the post. 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'))
python
def clean(self): """ Validates the post instance. """ super().clean() # At least a poster (user) or a session key must be associated with # the post. 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'))
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "# At least a poster (user) or a session key must be associated with", "# the post.", "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.
[ "Validates", "the", "post", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L289-L305
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.save
def save(self, *args, **kwargs): """ Saves the post instance. """ new_post = self.pk is None super().save(*args, **kwargs) # Ensures that the subject of the thread corresponds to the one associated # with the first post. Do the same with the 'approved' flag. 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 # Trigger the topic-level trackers update self.topic.update_trackers()
python
def save(self, *args, **kwargs): """ Saves the post instance. """ new_post = self.pk is None super().save(*args, **kwargs) # Ensures that the subject of the thread corresponds to the one associated # with the first post. Do the same with the 'approved' flag. 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 # Trigger the topic-level trackers update self.topic.update_trackers()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_post", "=", "self", ".", "pk", "is", "None", "super", "(", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Ensures that the subject of the thread corresponds to the one associated", "# with the first post. Do the same with the 'approved' flag.", "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", "# Trigger the topic-level trackers update", "self", ".", "topic", ".", "update_trackers", "(", ")" ]
Saves the post instance.
[ "Saves", "the", "post", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L307-L320
train
ellmetha/django-machina
machina/apps/forum_conversation/abstract_models.py
AbstractPost.delete
def delete(self, using=None): """ Deletes the post instance. """ if self.is_alone: # The default way of operating is to trigger the deletion of the associated topic # only if the considered post is the only post embedded in the topic self.topic.delete() else: super(AbstractPost, self).delete(using) self.topic.update_trackers()
python
def delete(self, using=None): """ Deletes the post instance. """ if self.is_alone: # The default way of operating is to trigger the deletion of the associated topic # only if the considered post is the only post embedded in the topic self.topic.delete() else: super(AbstractPost, self).delete(using) self.topic.update_trackers()
[ "def", "delete", "(", "self", ",", "using", "=", "None", ")", ":", "if", "self", ".", "is_alone", ":", "# The default way of operating is to trigger the deletion of the associated topic", "# only if the considered post is the only post embedded in the topic", "self", ".", "topic", ".", "delete", "(", ")", "else", ":", "super", "(", "AbstractPost", ",", "self", ")", ".", "delete", "(", "using", ")", "self", ".", "topic", ".", "update_trackers", "(", ")" ]
Deletes the post instance.
[ "Deletes", "the", "post", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L322-L330
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentTree.from_forums
def from_forums(cls, forums): """ Initializes a ``ForumVisibilityContentTree`` instance from a list of forums. """ root_level = None current_path = [] nodes = [] # Ensures forums last posts and related poster relations are "followed" for better # performance (only if we're considering a queryset). forums = ( forums.select_related('last_post', 'last_post__poster') if isinstance(forums, QuerySet) else forums ) for forum in forums: level = forum.level # Set the root level to the top node level at the first iteration. if root_level is None: root_level = level # Initializes a visibility forum node associated with current forum instance. vcontent_node = ForumVisibilityContentNode(forum) # Computes a relative level associated to the node. relative_level = level - root_level vcontent_node.relative_level = relative_level # All children nodes will be stored in an array attached to the current node. vcontent_node.children = [] # Removes the forum that are not in the current branch. while len(current_path) > relative_level: current_path.pop(-1) if level != root_level: # Update the parent of the current forum. parent_node = current_path[-1] vcontent_node.parent = parent_node parent_node.children.append(vcontent_node) # Sets visible flag if applicable. The visible flag is used to determine whether a forum # can be seen in a forum list or not. A forum can be seen if one of the following # statements is true: # # * the forum is a direct child of the starting forum for the considered level # * the forum have a parent which is a category and this category is a direct child of # the starting forum # * the forum have its 'display_sub_forum_list' option set to True and have a parent # which is another forum. The latter is a direct child of the starting forum # * the forum have its 'display_sub_forum_list' option set to True and have a parent # which is another forum. The later have a parent which is a category and this # category is a direct child of the starting forum # # If forums at the root level don't have parents, the visible forums are those that can # be seen from the root of the forums tree. 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 ) ) # Add the current forum to the end of the current branch and inserts the node inside the # final node dictionary. current_path.append(vcontent_node) nodes.append(vcontent_node) tree = cls(nodes=nodes) for node in tree.nodes: node.tree = tree return tree
python
def from_forums(cls, forums): """ Initializes a ``ForumVisibilityContentTree`` instance from a list of forums. """ root_level = None current_path = [] nodes = [] # Ensures forums last posts and related poster relations are "followed" for better # performance (only if we're considering a queryset). forums = ( forums.select_related('last_post', 'last_post__poster') if isinstance(forums, QuerySet) else forums ) for forum in forums: level = forum.level # Set the root level to the top node level at the first iteration. if root_level is None: root_level = level # Initializes a visibility forum node associated with current forum instance. vcontent_node = ForumVisibilityContentNode(forum) # Computes a relative level associated to the node. relative_level = level - root_level vcontent_node.relative_level = relative_level # All children nodes will be stored in an array attached to the current node. vcontent_node.children = [] # Removes the forum that are not in the current branch. while len(current_path) > relative_level: current_path.pop(-1) if level != root_level: # Update the parent of the current forum. parent_node = current_path[-1] vcontent_node.parent = parent_node parent_node.children.append(vcontent_node) # Sets visible flag if applicable. The visible flag is used to determine whether a forum # can be seen in a forum list or not. A forum can be seen if one of the following # statements is true: # # * the forum is a direct child of the starting forum for the considered level # * the forum have a parent which is a category and this category is a direct child of # the starting forum # * the forum have its 'display_sub_forum_list' option set to True and have a parent # which is another forum. The latter is a direct child of the starting forum # * the forum have its 'display_sub_forum_list' option set to True and have a parent # which is another forum. The later have a parent which is a category and this # category is a direct child of the starting forum # # If forums at the root level don't have parents, the visible forums are those that can # be seen from the root of the forums tree. 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 ) ) # Add the current forum to the end of the current branch and inserts the node inside the # final node dictionary. current_path.append(vcontent_node) nodes.append(vcontent_node) tree = cls(nodes=nodes) for node in tree.nodes: node.tree = tree return tree
[ "def", "from_forums", "(", "cls", ",", "forums", ")", ":", "root_level", "=", "None", "current_path", "=", "[", "]", "nodes", "=", "[", "]", "# Ensures forums last posts and related poster relations are \"followed\" for better", "# performance (only if we're considering a queryset).", "forums", "=", "(", "forums", ".", "select_related", "(", "'last_post'", ",", "'last_post__poster'", ")", "if", "isinstance", "(", "forums", ",", "QuerySet", ")", "else", "forums", ")", "for", "forum", "in", "forums", ":", "level", "=", "forum", ".", "level", "# Set the root level to the top node level at the first iteration.", "if", "root_level", "is", "None", ":", "root_level", "=", "level", "# Initializes a visibility forum node associated with current forum instance.", "vcontent_node", "=", "ForumVisibilityContentNode", "(", "forum", ")", "# Computes a relative level associated to the node.", "relative_level", "=", "level", "-", "root_level", "vcontent_node", ".", "relative_level", "=", "relative_level", "# All children nodes will be stored in an array attached to the current node.", "vcontent_node", ".", "children", "=", "[", "]", "# Removes the forum that are not in the current branch.", "while", "len", "(", "current_path", ")", ">", "relative_level", ":", "current_path", ".", "pop", "(", "-", "1", ")", "if", "level", "!=", "root_level", ":", "# Update the parent of the current forum.", "parent_node", "=", "current_path", "[", "-", "1", "]", "vcontent_node", ".", "parent", "=", "parent_node", "parent_node", ".", "children", ".", "append", "(", "vcontent_node", ")", "# Sets visible flag if applicable. The visible flag is used to determine whether a forum", "# can be seen in a forum list or not. A forum can be seen if one of the following", "# statements is true:", "#", "# * the forum is a direct child of the starting forum for the considered level", "# * the forum have a parent which is a category and this category is a direct child of", "# the starting forum", "# * the forum have its 'display_sub_forum_list' option set to True and have a parent", "# which is another forum. The latter is a direct child of the starting forum", "# * the forum have its 'display_sub_forum_list' option set to True and have a parent", "# which is another forum. The later have a parent which is a category and this", "# category is a direct child of the starting forum", "#", "# If forums at the root level don't have parents, the visible forums are those that can", "# be seen from the root of the forums tree.", "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", ")", ")", "# Add the current forum to the end of the current branch and inserts the node inside the", "# final node dictionary.", "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.
[ "Initializes", "a", "ForumVisibilityContentTree", "instance", "from", "a", "list", "of", "forums", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L33-L108
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.last_post
def last_post(self): """ Returns the latest post associated with the node or one of its descendants. """ 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
python
def last_post(self): """ Returns the latest post associated with the node or one of its descendants. """ 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
[ "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.
[ "Returns", "the", "latest", "post", "associated", "with", "the", "node", "or", "one", "of", "its", "descendants", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L158-L164
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.last_post_on
def last_post_on(self): """ Returns the latest post date associated with the node or one of its descendants. """ 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
python
def last_post_on(self): """ Returns the latest post date associated with the node or one of its descendants. """ 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
[ "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.
[ "Returns", "the", "latest", "post", "date", "associated", "with", "the", "node", "or", "one", "of", "its", "descendants", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L167-L173
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.next_sibling
def next_sibling(self): """ Returns the next sibling of the current node. The next sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance. """ 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
python
def next_sibling(self): """ Returns the next sibling of the current node. The next sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance. """ 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
[ "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. The next sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance.
[ "Returns", "the", "next", "sibling", "of", "the", "current", "node", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L176-L194
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.posts_count
def posts_count(self): """ Returns the number of posts associated with the current node and its descendants. """ return self.obj.direct_posts_count + sum(n.posts_count for n in self.children)
python
def posts_count(self): """ Returns the number of posts associated with the current node and its descendants. """ return self.obj.direct_posts_count + sum(n.posts_count for n in self.children)
[ "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.
[ "Returns", "the", "number", "of", "posts", "associated", "with", "the", "current", "node", "and", "its", "descendants", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L197-L199
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.previous_sibling
def previous_sibling(self): """ Returns the previous sibling of the current node. The previous sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance. """ 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
python
def previous_sibling(self): """ Returns the previous sibling of the current node. The previous sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance. """ 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
[ "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. The previous sibling is searched in the parent node if we are not considering a top-level node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that is associated with the considered tree instance.
[ "Returns", "the", "previous", "sibling", "of", "the", "current", "node", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L202-L220
train
ellmetha/django-machina
machina/apps/forum/visibility.py
ForumVisibilityContentNode.topics_count
def topics_count(self): """ Returns the number of topics associated with the current node and its descendants. """ return self.obj.direct_topics_count + sum(n.topics_count for n in self.children)
python
def topics_count(self): """ Returns the number of topics associated with the current node and its descendants. """ return self.obj.direct_topics_count + sum(n.topics_count for n in self.children)
[ "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.
[ "Returns", "the", "number", "of", "topics", "associated", "with", "the", "current", "node", "and", "its", "descendants", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L223-L225
train
ellmetha/django-machina
machina/apps/forum_permission/checker.py
ForumPermissionChecker.has_perm
def has_perm(self, perm, forum): """ Checks if the considered user has given permission for the passed forum. """ if not self.user.is_anonymous and not self.user.is_active: # An inactive user cannot have permissions return False elif self.user and self.user.is_superuser: # The superuser have all permissions return True return perm in self.get_perms(forum)
python
def has_perm(self, perm, forum): """ Checks if the considered user has given permission for the passed forum. """ if not self.user.is_anonymous and not self.user.is_active: # An inactive user cannot have permissions return False elif self.user and self.user.is_superuser: # The superuser have all permissions return True return perm in self.get_perms(forum)
[ "def", "has_perm", "(", "self", ",", "perm", ",", "forum", ")", ":", "if", "not", "self", ".", "user", ".", "is_anonymous", "and", "not", "self", ".", "user", ".", "is_active", ":", "# An inactive user cannot have permissions", "return", "False", "elif", "self", ".", "user", "and", "self", ".", "user", ".", "is_superuser", ":", "# The superuser have all permissions", "return", "True", "return", "perm", "in", "self", ".", "get_perms", "(", "forum", ")" ]
Checks if the considered user has given permission for the passed forum.
[ "Checks", "if", "the", "considered", "user", "has", "given", "permission", "for", "the", "passed", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/checker.py#L29-L37
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/forms.py
BaseAttachmentFormset.save
def save(self, commit=True, **kwargs): """ Saves the considered instances. """ if self.post: for form in self.forms: form.instance.post = self.post super().save(commit)
python
def save(self, commit=True, **kwargs): """ Saves the considered instances. """ if self.post: for form in self.forms: form.instance.post = self.post super().save(commit)
[ "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.
[ "Saves", "the", "considered", "instances", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/forms.py#L34-L39
train
ellmetha/django-machina
machina/apps/forum_permission/viewmixins.py
PermissionRequiredMixin.get_required_permissions
def get_required_permissions(self, request): """ Returns the required permissions to access the considered object. """ 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
python
def get_required_permissions(self, request): """ Returns the required permissions to access the considered object. """ 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
[ "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.
[ "Returns", "the", "required", "permissions", "to", "access", "the", "considered", "object", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L51-L68
train
ellmetha/django-machina
machina/apps/forum_permission/viewmixins.py
PermissionRequiredMixin.check_permissions
def check_permissions(self, request): """ Retrieves the controlled object and perform the permissions check. """ 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 # Get the permissions to check perms = self.get_required_permissions(self) # Check permissions 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
python
def check_permissions(self, request): """ Retrieves the controlled object and perform the permissions check. """ 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 # Get the permissions to check perms = self.get_required_permissions(self) # Check permissions 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
[ "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", "# Get the permissions to check", "perms", "=", "self", ".", "get_required_permissions", "(", "self", ")", "# Check permissions", "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.
[ "Retrieves", "the", "controlled", "object", "and", "perform", "the", "permissions", "check", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L84-L105
train
ellmetha/django-machina
machina/apps/forum_permission/viewmixins.py
PermissionRequiredMixin.dispatch
def dispatch(self, request, *args, **kwargs): """ Dispatches an incoming request. """ self.request = request self.args = args self.kwargs = kwargs response = self.check_permissions(request) if response: return response return super().dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): """ Dispatches an incoming request. """ self.request = request self.args = args self.kwargs = kwargs response = self.check_permissions(request) if response: return response return super().dispatch(request, *args, **kwargs)
[ "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.
[ "Dispatches", "an", "incoming", "request", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L107-L115
train
ellmetha/django-machina
machina/apps/forum_tracking/receivers.py
update_user_trackers
def update_user_trackers(sender, topic, user, request, response, **kwargs): """ Receiver to mark a topic being viewed as read. This can result in marking the related forum tracker as read. """ TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') # noqa track_handler = TrackingHandler() track_handler.mark_topic_read(topic, user)
python
def update_user_trackers(sender, topic, user, request, response, **kwargs): """ Receiver to mark a topic being viewed as read. This can result in marking the related forum tracker as read. """ TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') # noqa track_handler = TrackingHandler() track_handler.mark_topic_read(topic, user)
[ "def", "update_user_trackers", "(", "sender", ",", "topic", ",", "user", ",", "request", ",", "response", ",", "*", "*", "kwargs", ")", ":", "TrackingHandler", "=", "get_class", "(", "'forum_tracking.handler'", ",", "'TrackingHandler'", ")", "# noqa", "track_handler", "=", "TrackingHandler", "(", ")", "track_handler", ".", "mark_topic_read", "(", "topic", ",", "user", ")" ]
Receiver to mark a topic being viewed as read. This can result in marking the related forum tracker as read.
[ "Receiver", "to", "mark", "a", "topic", "being", "viewed", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/receivers.py#L18-L26
train
ellmetha/django-machina
machina/apps/forum/receivers.py
update_forum_redirects_counter
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs): """ Handles the update of the link redirects counter associated with link forums. """ if forum.is_link and forum.link_redirects: forum.link_redirects_count = F('link_redirects_count') + 1 forum.save()
python
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs): """ Handles the update of the link redirects counter associated with link forums. """ if forum.is_link and forum.link_redirects: forum.link_redirects_count = F('link_redirects_count') + 1 forum.save()
[ "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.
[ "Handles", "the", "update", "of", "the", "link", "redirects", "counter", "associated", "with", "link", "forums", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/receivers.py#L16-L20
train
ellmetha/django-machina
machina/apps/forum_member/abstract_models.py
AbstractForumProfile.get_avatar_upload_to
def get_avatar_upload_to(self, filename): """ Returns the path to upload the associated avatar to. """ 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), )
python
def get_avatar_upload_to(self, filename): """ Returns the path to upload the associated avatar to. """ 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), )
[ "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.
[ "Returns", "the", "path", "to", "upload", "the", "associated", "avatar", "to", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/abstract_models.py#L60-L66
train
ellmetha/django-machina
machina/apps/forum_conversation/managers.py
ApprovedManager.get_queryset
def get_queryset(self): """ Returns all the approved topics or posts. """ qs = super().get_queryset() qs = qs.filter(approved=True) return qs
python
def get_queryset(self): """ Returns all the approved topics or posts. """ qs = super().get_queryset() qs = qs.filter(approved=True) return qs
[ "def", "get_queryset", "(", "self", ")", ":", "qs", "=", "super", "(", ")", ".", "get_queryset", "(", ")", "qs", "=", "qs", ".", "filter", "(", "approved", "=", "True", ")", "return", "qs" ]
Returns all the approved topics or posts.
[ "Returns", "all", "the", "approved", "topics", "or", "posts", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/managers.py#L13-L17
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_polls/abstract_models.py
AbstractTopicPoll.votes
def votes(self): """ Returns all the votes related to this topic poll. """ votes = [] for option in self.options.all(): votes += option.votes.all() return votes
python
def votes(self): """ Returns all the votes related to this topic poll. """ votes = [] for option in self.options.all(): votes += option.votes.all() return votes
[ "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.
[ "Returns", "all", "the", "votes", "related", "to", "this", "topic", "poll", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/abstract_models.py#L56-L61
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_polls/abstract_models.py
AbstractTopicPollVote.clean
def clean(self): """ Validates the considered instance. """ super().clean() # At least a poster (user) or a session key must be associated with # the vote instance. 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.'))
python
def clean(self): """ Validates the considered instance. """ super().clean() # At least a poster (user) or a session key must be associated with # the vote instance. 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.'))
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "# At least a poster (user) or a session key must be associated with", "# the vote instance.", "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.
[ "Validates", "the", "considered", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/abstract_models.py#L114-L123
train
ellmetha/django-machina
machina/apps/forum_tracking/views.py
MarkForumsReadView.get_top_level_forum_url
def get_top_level_forum_url(self): """ Returns the parent forum from which forums are marked as read. """ 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']}, ) )
python
def get_top_level_forum_url(self): """ Returns the parent forum from which forums are marked as read. """ 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']}, ) )
[ "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.
[ "Returns", "the", "parent", "forum", "from", "which", "forums", "are", "marked", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L53-L61
train
ellmetha/django-machina
machina/apps/forum_tracking/views.py
MarkForumsReadView.mark_as_read
def mark_as_read(self, request, pk): """ Marks the considered forums as read. """ 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, ) # Marks forums as read 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())
python
def mark_as_read(self, request, pk): """ Marks the considered forums as read. """ 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, ) # Marks forums as read 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())
[ "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", ",", ")", "# Marks forums as read", "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.
[ "Marks", "the", "considered", "forums", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L63-L80
train
ellmetha/django-machina
machina/apps/forum_tracking/views.py
MarkTopicsReadView.get_forum_url
def get_forum_url(self): """ Returns the url of the forum whose topics will be marked read. """ return reverse('forum:forum', kwargs={'slug': self.forum.slug, 'pk': self.forum.pk})
python
def get_forum_url(self): """ Returns the url of the forum whose topics will be marked read. """ return reverse('forum:forum', kwargs={'slug': self.forum.slug, 'pk': self.forum.pk})
[ "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.
[ "Returns", "the", "url", "of", "the", "forum", "whose", "topics", "will", "be", "marked", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L113-L115
train
ellmetha/django-machina
machina/apps/forum_tracking/views.py
MarkTopicsReadView.mark_topics_read
def mark_topics_read(self, request, pk): """ Marks forum topics as read. """ track_handler.mark_forums_read([self.forum, ], request.user) messages.success(request, self.success_message) return HttpResponseRedirect(self.get_forum_url())
python
def mark_topics_read(self, request, pk): """ Marks forum topics as read. """ track_handler.mark_forums_read([self.forum, ], request.user) messages.success(request, self.success_message) return HttpResponseRedirect(self.get_forum_url())
[ "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.
[ "Marks", "forum", "topics", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L117-L121
train
ellmetha/django-machina
machina/core/db/models.py
get_model
def get_model(app_label, model_name): """ Given an app label and a model name, returns the corresponding model class. """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If the models module of the considered app has not been loaded yet, # we try to import it manually in order to retrieve the model class. # This trick is usefull in order to get the model class during the # ``apps.populate()`` call and the execution of related methods of AppConfig # instances (eg. ``ready``). # Firts, the config of the consideration must be retrieved app_config = apps.get_app_config(app_label) # Then the models module is manually imported import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # Finally, tries to return the registered model class return apps.get_registered_model(app_label, model_name) else: raise
python
def get_model(app_label, model_name): """ Given an app label and a model name, returns the corresponding model class. """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If the models module of the considered app has not been loaded yet, # we try to import it manually in order to retrieve the model class. # This trick is usefull in order to get the model class during the # ``apps.populate()`` call and the execution of related methods of AppConfig # instances (eg. ``ready``). # Firts, the config of the consideration must be retrieved app_config = apps.get_app_config(app_label) # Then the models module is manually imported import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # Finally, tries to return the registered model class return apps.get_registered_model(app_label, model_name) else: raise
[ "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", ":", "# If the models module of the considered app has not been loaded yet,", "# we try to import it manually in order to retrieve the model class.", "# This trick is usefull in order to get the model class during the", "# ``apps.populate()`` call and the execution of related methods of AppConfig", "# instances (eg. ``ready``).", "# Firts, the config of the consideration must be retrieved", "app_config", "=", "apps", ".", "get_app_config", "(", "app_label", ")", "# Then the models module is manually imported", "import_module", "(", "'%s.%s'", "%", "(", "app_config", ".", "name", ",", "MODELS_MODULE_NAME", ")", ")", "# Finally, tries to return the registered model class", "return", "apps", ".", "get_registered_model", "(", "app_label", ",", "model_name", ")", "else", ":", "raise" ]
Given an app label and a model name, returns the corresponding model class.
[ "Given", "an", "app", "label", "and", "a", "model", "name", "returns", "the", "corresponding", "model", "class", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/db/models.py#L12-L31
train
ellmetha/django-machina
machina/core/db/models.py
is_model_registered
def is_model_registered(app_label, model_name): """ Checks whether the given model is registered or not. It is usefull to prevent Machina models for being registered if they are overridden by local apps. """ try: apps.get_registered_model(app_label, model_name) except LookupError: return False else: return True
python
def is_model_registered(app_label, model_name): """ Checks whether the given model is registered or not. It is usefull to prevent Machina models for being registered if they are overridden by local apps. """ try: apps.get_registered_model(app_label, model_name) except LookupError: return False else: return True
[ "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. It is usefull to prevent Machina models for being registered if they are overridden by local apps.
[ "Checks", "whether", "the", "given", "model", "is", "registered", "or", "not", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/db/models.py#L34-L46
train
ellmetha/django-machina
machina/apps/forum_permission/abstract_models.py
AbstractUserForumPermission.clean
def clean(self): """ Validates the current instance. """ 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'), )
python
def clean(self): """ Validates the current instance. """ 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'), )
[ "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.
[ "Validates", "the", "current", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/abstract_models.py#L94-L103
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_attachments/views.py
AttachmentView.render_to_response
def render_to_response(self, context, **response_kwargs): """ Generates the appropriate response. """ filename = os.path.basename(self.object.file.name) # Try to guess the content type of the given file 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
python
def render_to_response(self, context, **response_kwargs): """ Generates the appropriate response. """ filename = os.path.basename(self.object.file.name) # Try to guess the content type of the given file 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
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "object", ".", "file", ".", "name", ")", "# Try to guess the content type of the given file", "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.
[ "Generates", "the", "appropriate", "response", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/views.py#L29-L41
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_polls/views.py
TopicPollVoteView.get_form_kwargs
def get_form_kwargs(self): """ Returns the keyword arguments to provide tp the associated form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() kwargs['poll'] = self.object return kwargs
python
def get_form_kwargs(self): """ Returns the keyword arguments to provide tp the associated form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() kwargs['poll'] = self.object return kwargs
[ "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.
[ "Returns", "the", "keyword", "arguments", "to", "provide", "tp", "the", "associated", "form", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/views.py#L37-L41
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_polls/views.py
TopicPollVoteView.form_invalid
def form_invalid(self, form): """ Handles an invalid 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 }, ), )
python
def form_invalid(self, form): """ Handles an invalid 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 }, ), )
[ "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.
[ "Handles", "an", "invalid", "form", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/views.py#L62-L75
train
ellmetha/django-machina
machina/templatetags/forum_polls_tags.py
has_been_completed_by
def has_been_completed_by(poll, user): """ This will return a boolean indicating if the passed user has already voted in the given poll. Usage:: {% if poll|has_been_completed_by:user %}...{% endif %} """ 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()
python
def has_been_completed_by(poll, user): """ This will return a boolean indicating if the passed user has already voted in the given poll. Usage:: {% if poll|has_been_completed_by:user %}...{% endif %} """ 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()
[ "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. Usage:: {% if poll|has_been_completed_by:user %}...{% endif %}
[ "This", "will", "return", "a", "boolean", "indicating", "if", "the", "passed", "user", "has", "already", "voted", "in", "the", "given", "poll", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_polls_tags.py#L17-L33
train
ellmetha/django-machina
machina/apps/forum_tracking/managers.py
ForumReadTrackManager.get_unread_forums_from_list
def get_unread_forums_from_list(self, forums, user): """ Filter a list of forums and return only those which are unread. Given a list of forums find and returns the list of forums that are unread for the passed user. If a forum is unread all of its ancestors are also unread and will be included in the final list. """ 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))
python
def get_unread_forums_from_list(self, forums, user): """ Filter a list of forums and return only those which are unread. Given a list of forums find and returns the list of forums that are unread for the passed user. If a forum is unread all of its ancestors are also unread and will be included in the final list. """ 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))
[ "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. Given a list of forums find and returns the list of forums that are unread for the passed user. If a forum is unread all of its ancestors are also unread and will be included in the final list.
[ "Filter", "a", "list", "of", "forums", "and", "return", "only", "those", "which", "are", "unread", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/managers.py#L20-L48
train
ellmetha/django-machina
machina/apps/forum_member/receivers.py
increase_posts_count
def increase_posts_count(sender, instance, **kwargs): """ Increases the member's post count after a post save. This receiver handles the update of the profile related to the user who is the poster of the forum post being created or updated. """ if instance.poster is None: # An anonymous post is considered. No profile can be updated in # that case. 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: # pragma: no cover # This should never happen (except with django loaddata command) 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()
python
def increase_posts_count(sender, instance, **kwargs): """ Increases the member's post count after a post save. This receiver handles the update of the profile related to the user who is the poster of the forum post being created or updated. """ if instance.poster is None: # An anonymous post is considered. No profile can be updated in # that case. 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: # pragma: no cover # This should never happen (except with django loaddata command) 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()
[ "def", "increase_posts_count", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "poster", "is", "None", ":", "# An anonymous post is considered. No profile can be updated in", "# that case.", "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", ":", "# pragma: no cover", "# This should never happen (except with django loaddata command)", "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. This receiver handles the update of the profile related to the user who is the poster of the forum post being created or updated.
[ "Increases", "the", "member", "s", "post", "count", "after", "a", "post", "save", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/receivers.py#L25-L54
train
ellmetha/django-machina
machina/apps/forum_member/receivers.py
decrease_posts_count_after_post_unaproval
def decrease_posts_count_after_post_unaproval(sender, instance, **kwargs): """ Decreases the member's post count after a post unaproval. This receiver handles the unaproval of a forum post: the posts count associated with the post's author is decreased. """ if not instance.pk: # Do not consider posts being created. return profile, dummy = ForumProfile.objects.get_or_create(user=instance.poster) try: old_instance = instance.__class__._default_manager.get(pk=instance.pk) except ObjectDoesNotExist: # pragma: no cover # This should never happen (except with django loaddata command) return if old_instance and old_instance.approved is True and instance.approved is False: profile.posts_count = F('posts_count') - 1 profile.save()
python
def decrease_posts_count_after_post_unaproval(sender, instance, **kwargs): """ Decreases the member's post count after a post unaproval. This receiver handles the unaproval of a forum post: the posts count associated with the post's author is decreased. """ if not instance.pk: # Do not consider posts being created. return profile, dummy = ForumProfile.objects.get_or_create(user=instance.poster) try: old_instance = instance.__class__._default_manager.get(pk=instance.pk) except ObjectDoesNotExist: # pragma: no cover # This should never happen (except with django loaddata command) return if old_instance and old_instance.approved is True and instance.approved is False: profile.posts_count = F('posts_count') - 1 profile.save()
[ "def", "decrease_posts_count_after_post_unaproval", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "not", "instance", ".", "pk", ":", "# Do not consider posts being created.", "return", "profile", ",", "dummy", "=", "ForumProfile", ".", "objects", ".", "get_or_create", "(", "user", "=", "instance", ".", "poster", ")", "try", ":", "old_instance", "=", "instance", ".", "__class__", ".", "_default_manager", ".", "get", "(", "pk", "=", "instance", ".", "pk", ")", "except", "ObjectDoesNotExist", ":", "# pragma: no cover", "# This should never happen (except with django loaddata command)", "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. This receiver handles the unaproval of a forum post: the posts count associated with the post's author is decreased.
[ "Decreases", "the", "member", "s", "post", "count", "after", "a", "post", "unaproval", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/receivers.py#L58-L78
train
ellmetha/django-machina
machina/apps/forum_member/receivers.py
decrease_posts_count_after_post_deletion
def decrease_posts_count_after_post_deletion(sender, instance, **kwargs): """ Decreases the member's post count after a post deletion. This receiver handles the deletion of a forum post: the posts count related to the post's author is decreased. """ if not instance.approved: # If a post has not been approved, it has not been counted. # So do not decrement count return try: assert instance.poster_id is not None poster = User.objects.get(pk=instance.poster_id) except AssertionError: # An anonymous post is considered. No profile can be updated in # that case. return except ObjectDoesNotExist: # pragma: no cover # This can happen if a User instance is deleted. In that case the # User instance is not available and the receiver should return. return profile, dummy = ForumProfile.objects.get_or_create(user=poster) if profile.posts_count: profile.posts_count = F('posts_count') - 1 profile.save()
python
def decrease_posts_count_after_post_deletion(sender, instance, **kwargs): """ Decreases the member's post count after a post deletion. This receiver handles the deletion of a forum post: the posts count related to the post's author is decreased. """ if not instance.approved: # If a post has not been approved, it has not been counted. # So do not decrement count return try: assert instance.poster_id is not None poster = User.objects.get(pk=instance.poster_id) except AssertionError: # An anonymous post is considered. No profile can be updated in # that case. return except ObjectDoesNotExist: # pragma: no cover # This can happen if a User instance is deleted. In that case the # User instance is not available and the receiver should return. return profile, dummy = ForumProfile.objects.get_or_create(user=poster) if profile.posts_count: profile.posts_count = F('posts_count') - 1 profile.save()
[ "def", "decrease_posts_count_after_post_deletion", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "not", "instance", ".", "approved", ":", "# If a post has not been approved, it has not been counted.", "# So do not decrement count", "return", "try", ":", "assert", "instance", ".", "poster_id", "is", "not", "None", "poster", "=", "User", ".", "objects", ".", "get", "(", "pk", "=", "instance", ".", "poster_id", ")", "except", "AssertionError", ":", "# An anonymous post is considered. No profile can be updated in", "# that case.", "return", "except", "ObjectDoesNotExist", ":", "# pragma: no cover", "# This can happen if a User instance is deleted. In that case the", "# User instance is not available and the receiver should return.", "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. This receiver handles the deletion of a forum post: the posts count related to the post's author is decreased.
[ "Decreases", "the", "member", "s", "post", "count", "after", "a", "post", "deletion", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/receivers.py#L82-L108
train
ellmetha/django-machina
machina/apps/forum_moderation/views.py
TopicLockView.lock
def lock(self, request, *args, **kwargs): """ Locks the considered topic and retirects the user to the success URL. """ 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)
python
def lock(self, request, *args, **kwargs): """ Locks the considered topic and retirects the user to the success URL. """ 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)
[ "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.
[ "Locks", "the", "considered", "topic", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L42-L49
train
ellmetha/django-machina
machina/apps/forum_moderation/views.py
TopicUnlockView.unlock
def unlock(self, request, *args, **kwargs): """ Unlocks the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.status = Topic.TOPIC_UNLOCKED self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
python
def unlock(self, request, *args, **kwargs): """ Unlocks the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.status = Topic.TOPIC_UNLOCKED self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
[ "def", "unlock", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", ".", "status", "=", "Topic", ".", "TOPIC_UNLOCKED", "self", ".", "object", ".", "save", "(", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "success_url", ")" ]
Unlocks the considered topic and retirects the user to the success URL.
[ "Unlocks", "the", "considered", "topic", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L91-L98
train
ellmetha/django-machina
machina/apps/forum_moderation/views.py
TopicUpdateTypeBaseView.update_type
def update_type(self, request, *args, **kwargs): """ Updates the type of the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.type = self.target_type self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
python
def update_type(self, request, *args, **kwargs): """ Updates the type of the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.type = self.target_type self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
[ "def", "update_type", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", ".", "type", "=", "self", ".", "target_type", "self", ".", "object", ".", "save", "(", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "success_url", ")" ]
Updates the type of the considered topic and retirects the user to the success URL.
[ "Updates", "the", "type", "of", "the", "considered", "topic", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L257-L265
train
ellmetha/django-machina
machina/apps/forum_moderation/views.py
PostApproveView.approve
def approve(self, request, *args, **kwargs): """ Approves the considered post and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.approved = True self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
python
def approve(self, request, *args, **kwargs): """ Approves the considered post and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.approved = True self.object.save() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
[ "def", "approve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", ".", "approved", "=", "True", "self", ".", "object", ".", "save", "(", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "success_url", ")" ]
Approves the considered post and retirects the user to the success URL.
[ "Approves", "the", "considered", "post", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L404-L411
train
ellmetha/django-machina
machina/apps/forum_moderation/views.py
PostDisapproveView.disapprove
def disapprove(self, request, *args, **kwargs): """ Disapproves the considered post and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
python
def disapprove(self, request, *args, **kwargs): """ Disapproves the considered post and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() messages.success(self.request, self.success_message) return HttpResponseRedirect(success_url)
[ "def", "disapprove", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", ".", "delete", "(", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "success_url", ")" ]
Disapproves the considered post and retirects the user to the success URL.
[ "Disapproves", "the", "considered", "post", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L446-L452
train
ellmetha/django-machina
machina/apps/forum_member/views.py
UserPostsView.poster
def poster(self): """ Returns the considered user. """ user_model = get_user_model() return get_object_or_404(user_model, pk=self.kwargs[self.user_pk_url_kwarg])
python
def poster(self): """ Returns the considered user. """ user_model = get_user_model() return get_object_or_404(user_model, pk=self.kwargs[self.user_pk_url_kwarg])
[ "def", "poster", "(", "self", ")", ":", "user_model", "=", "get_user_model", "(", ")", "return", "get_object_or_404", "(", "user_model", ",", "pk", "=", "self", ".", "kwargs", "[", "self", ".", "user_pk_url_kwarg", "]", ")" ]
Returns the considered user.
[ "Returns", "the", "considered", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/views.py#L66-L69
train
ellmetha/django-machina
machina/apps/forum_member/views.py
TopicSubscribeView.subscribe
def subscribe(self, request, *args, **kwargs): """ Performs the subscribe action. """ self.object = self.get_object() self.object.subscribers.add(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
python
def subscribe(self, request, *args, **kwargs): """ Performs the subscribe action. """ self.object = self.get_object() self.object.subscribers.add(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
[ "def", "subscribe", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "self", ".", "object", ".", "subscribers", ".", "add", "(", "request", ".", "user", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Performs the subscribe action.
[ "Performs", "the", "subscribe", "action", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/views.py#L145-L150
train
ellmetha/django-machina
machina/apps/forum_member/views.py
TopicUnsubscribeView.unsubscribe
def unsubscribe(self, request, *args, **kwargs): """ Performs the unsubscribe action. """ self.object = self.get_object() self.object.subscribers.remove(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
python
def unsubscribe(self, request, *args, **kwargs): """ Performs the unsubscribe action. """ self.object = self.get_object() self.object.subscribers.remove(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
[ "def", "unsubscribe", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "self", ".", "object", ".", "subscribers", ".", "remove", "(", "request", ".", "user", ")", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Performs the unsubscribe action.
[ "Performs", "the", "unsubscribe", "action", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/views.py#L191-L196
train
ellmetha/django-machina
machina/apps/forum_conversation/receivers.py
update_topic_counter
def update_topic_counter(sender, topic, user, request, response, **kwargs): """ Handles the update of the views counter associated with topics. """ topic.__class__._default_manager.filter(id=topic.id).update(views_count=F('views_count') + 1)
python
def update_topic_counter(sender, topic, user, request, response, **kwargs): """ Handles the update of the views counter associated with topics. """ topic.__class__._default_manager.filter(id=topic.id).update(views_count=F('views_count') + 1)
[ "def", "update_topic_counter", "(", "sender", ",", "topic", ",", "user", ",", "request", ",", "response", ",", "*", "*", "kwargs", ")", ":", "topic", ".", "__class__", ".", "_default_manager", ".", "filter", "(", "id", "=", "topic", ".", "id", ")", ".", "update", "(", "views_count", "=", "F", "(", "'views_count'", ")", "+", "1", ")" ]
Handles the update of the views counter associated with topics.
[ "Handles", "the", "update", "of", "the", "views", "counter", "associated", "with", "topics", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/receivers.py#L16-L18
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
TopicView.get_topic
def get_topic(self): """ Returns the topic to consider. """ if not hasattr(self, 'topic'): self.topic = get_object_or_404( Topic.objects.select_related('forum').all(), pk=self.kwargs['pk'], ) return self.topic
python
def get_topic(self): """ Returns the topic to consider. """ if not hasattr(self, 'topic'): self.topic = get_object_or_404( Topic.objects.select_related('forum').all(), pk=self.kwargs['pk'], ) return self.topic
[ "def", "get_topic", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'topic'", ")", ":", "self", ".", "topic", "=", "get_object_or_404", "(", "Topic", ".", "objects", ".", "select_related", "(", "'forum'", ")", ".", "all", "(", ")", ",", "pk", "=", "self", ".", "kwargs", "[", "'pk'", "]", ",", ")", "return", "self", ".", "topic" ]
Returns the topic to consider.
[ "Returns", "the", "topic", "to", "consider", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L73-L79
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.init_attachment_cache
def init_attachment_cache(self): """ Initializes the attachment cache for the current view. """ if self.request.method == 'GET': # Invalidates previous attachments attachments_cache.delete(self.get_attachments_cache_key(self.request)) return # Try to restore previous uploaded attachments if applicable attachments_cache_key = self.get_attachments_cache_key(self.request) restored_attachments_dict = attachments_cache.get(attachments_cache_key) if restored_attachments_dict: restored_attachments_dict.update(self.request.FILES) self.request._files = restored_attachments_dict # Updates the attachment cache if files are available if self.request.FILES: attachments_cache.set(attachments_cache_key, self.request.FILES)
python
def init_attachment_cache(self): """ Initializes the attachment cache for the current view. """ if self.request.method == 'GET': # Invalidates previous attachments attachments_cache.delete(self.get_attachments_cache_key(self.request)) return # Try to restore previous uploaded attachments if applicable attachments_cache_key = self.get_attachments_cache_key(self.request) restored_attachments_dict = attachments_cache.get(attachments_cache_key) if restored_attachments_dict: restored_attachments_dict.update(self.request.FILES) self.request._files = restored_attachments_dict # Updates the attachment cache if files are available if self.request.FILES: attachments_cache.set(attachments_cache_key, self.request.FILES)
[ "def", "init_attachment_cache", "(", "self", ")", ":", "if", "self", ".", "request", ".", "method", "==", "'GET'", ":", "# Invalidates previous attachments", "attachments_cache", ".", "delete", "(", "self", ".", "get_attachments_cache_key", "(", "self", ".", "request", ")", ")", "return", "# Try to restore previous uploaded attachments if applicable", "attachments_cache_key", "=", "self", ".", "get_attachments_cache_key", "(", "self", ".", "request", ")", "restored_attachments_dict", "=", "attachments_cache", ".", "get", "(", "attachments_cache_key", ")", "if", "restored_attachments_dict", ":", "restored_attachments_dict", ".", "update", "(", "self", ".", "request", ".", "FILES", ")", "self", ".", "request", ".", "_files", "=", "restored_attachments_dict", "# Updates the attachment cache if files are available", "if", "self", ".", "request", ".", "FILES", ":", "attachments_cache", ".", "set", "(", "attachments_cache_key", ",", "self", ".", "request", ".", "FILES", ")" ]
Initializes the attachment cache for the current view.
[ "Initializes", "the", "attachment", "cache", "for", "the", "current", "view", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L179-L195
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_post_form_kwargs
def get_post_form_kwargs(self): """ Returns the keyword arguments for instantiating the post form. """ kwargs = { 'user': self.request.user, 'forum': self.get_forum(), 'topic': self.get_topic(), } post = self.get_post() if post: kwargs.update({'instance': post}) if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs
python
def get_post_form_kwargs(self): """ Returns the keyword arguments for instantiating the post form. """ kwargs = { 'user': self.request.user, 'forum': self.get_forum(), 'topic': self.get_topic(), } post = self.get_post() if post: kwargs.update({'instance': post}) if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs
[ "def", "get_post_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'user'", ":", "self", ".", "request", ".", "user", ",", "'forum'", ":", "self", ".", "get_forum", "(", ")", ",", "'topic'", ":", "self", ".", "get_topic", "(", ")", ",", "}", "post", "=", "self", ".", "get_post", "(", ")", "if", "post", ":", "kwargs", ".", "update", "(", "{", "'instance'", ":", "post", "}", ")", "if", "self", ".", "request", ".", "method", "in", "(", "'POST'", ",", "'PUT'", ")", ":", "kwargs", ".", "update", "(", "{", "'data'", ":", "self", ".", "request", ".", "POST", ",", "'files'", ":", "self", ".", "request", ".", "FILES", ",", "}", ")", "return", "kwargs" ]
Returns the keyword arguments for instantiating the post form.
[ "Returns", "the", "keyword", "arguments", "for", "instantiating", "the", "post", "form", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L209-L226
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_attachment_formset
def get_attachment_formset(self, formset_class): """ Returns an instance of the attachment formset to be used in the view. """ if ( self.request.forum_permission_handler.can_attach_files( self.get_forum(), self.request.user, ) ): return formset_class(**self.get_attachment_formset_kwargs())
python
def get_attachment_formset(self, formset_class): """ Returns an instance of the attachment formset to be used in the view. """ if ( self.request.forum_permission_handler.can_attach_files( self.get_forum(), self.request.user, ) ): return formset_class(**self.get_attachment_formset_kwargs())
[ "def", "get_attachment_formset", "(", "self", ",", "formset_class", ")", ":", "if", "(", "self", ".", "request", ".", "forum_permission_handler", ".", "can_attach_files", "(", "self", ".", "get_forum", "(", ")", ",", "self", ".", "request", ".", "user", ",", ")", ")", ":", "return", "formset_class", "(", "*", "*", "self", ".", "get_attachment_formset_kwargs", "(", ")", ")" ]
Returns an instance of the attachment formset to be used in the view.
[ "Returns", "an", "instance", "of", "the", "attachment", "formset", "to", "be", "used", "in", "the", "view", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L228-L235
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_attachment_formset_kwargs
def get_attachment_formset_kwargs(self): """ Returns the keyword arguments for instantiating the attachment formset. """ kwargs = { 'prefix': 'attachment', } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) else: post = self.get_post() attachment_queryset = Attachment.objects.filter(post=post) kwargs.update({ 'queryset': attachment_queryset, }) return kwargs
python
def get_attachment_formset_kwargs(self): """ Returns the keyword arguments for instantiating the attachment formset. """ kwargs = { 'prefix': 'attachment', } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) else: post = self.get_post() attachment_queryset = Attachment.objects.filter(post=post) kwargs.update({ 'queryset': attachment_queryset, }) return kwargs
[ "def", "get_attachment_formset_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'prefix'", ":", "'attachment'", ",", "}", "if", "self", ".", "request", ".", "method", "in", "(", "'POST'", ",", "'PUT'", ")", ":", "kwargs", ".", "update", "(", "{", "'data'", ":", "self", ".", "request", ".", "POST", ",", "'files'", ":", "self", ".", "request", ".", "FILES", ",", "}", ")", "else", ":", "post", "=", "self", ".", "get_post", "(", ")", "attachment_queryset", "=", "Attachment", ".", "objects", ".", "filter", "(", "post", "=", "post", ")", "kwargs", ".", "update", "(", "{", "'queryset'", ":", "attachment_queryset", ",", "}", ")", "return", "kwargs" ]
Returns the keyword arguments for instantiating the attachment formset.
[ "Returns", "the", "keyword", "arguments", "for", "instantiating", "the", "attachment", "formset", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L241-L258
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_forum
def get_forum(self): """ Returns the considered forum. """ pk = self.kwargs.get(self.forum_pk_url_kwarg, None) if not pk: # pragma: no cover # This should never happen return if not hasattr(self, '_forum'): self._forum = get_object_or_404(Forum, pk=pk) return self._forum
python
def get_forum(self): """ Returns the considered forum. """ pk = self.kwargs.get(self.forum_pk_url_kwarg, None) if not pk: # pragma: no cover # This should never happen return if not hasattr(self, '_forum'): self._forum = get_object_or_404(Forum, pk=pk) return self._forum
[ "def", "get_forum", "(", "self", ")", ":", "pk", "=", "self", ".", "kwargs", ".", "get", "(", "self", ".", "forum_pk_url_kwarg", ",", "None", ")", "if", "not", "pk", ":", "# pragma: no cover", "# This should never happen", "return", "if", "not", "hasattr", "(", "self", ",", "'_forum'", ")", ":", "self", ".", "_forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "pk", ")", "return", "self", ".", "_forum" ]
Returns the considered forum.
[ "Returns", "the", "considered", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L295-L303
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_topic
def get_topic(self): """ Returns the considered topic if applicable. """ pk = self.kwargs.get(self.topic_pk_url_kwarg, None) if not pk: return if not hasattr(self, '_topic'): self._topic = get_object_or_404(Topic, pk=pk) return self._topic
python
def get_topic(self): """ Returns the considered topic if applicable. """ pk = self.kwargs.get(self.topic_pk_url_kwarg, None) if not pk: return if not hasattr(self, '_topic'): self._topic = get_object_or_404(Topic, pk=pk) return self._topic
[ "def", "get_topic", "(", "self", ")", ":", "pk", "=", "self", ".", "kwargs", ".", "get", "(", "self", ".", "topic_pk_url_kwarg", ",", "None", ")", "if", "not", "pk", ":", "return", "if", "not", "hasattr", "(", "self", ",", "'_topic'", ")", ":", "self", ".", "_topic", "=", "get_object_or_404", "(", "Topic", ",", "pk", "=", "pk", ")", "return", "self", ".", "_topic" ]
Returns the considered topic if applicable.
[ "Returns", "the", "considered", "topic", "if", "applicable", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L305-L312
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BasePostFormView.get_post
def get_post(self): """ Returns the considered post if applicable. """ pk = self.kwargs.get(self.post_pk_url_kwarg, None) if not pk: return if not hasattr(self, '_forum_post'): self._forum_post = get_object_or_404(Post, pk=pk) return self._forum_post
python
def get_post(self): """ Returns the considered post if applicable. """ pk = self.kwargs.get(self.post_pk_url_kwarg, None) if not pk: return if not hasattr(self, '_forum_post'): self._forum_post = get_object_or_404(Post, pk=pk) return self._forum_post
[ "def", "get_post", "(", "self", ")", ":", "pk", "=", "self", ".", "kwargs", ".", "get", "(", "self", ".", "post_pk_url_kwarg", ",", "None", ")", "if", "not", "pk", ":", "return", "if", "not", "hasattr", "(", "self", ",", "'_forum_post'", ")", ":", "self", ".", "_forum_post", "=", "get_object_or_404", "(", "Post", ",", "pk", "=", "pk", ")", "return", "self", ".", "_forum_post" ]
Returns the considered post if applicable.
[ "Returns", "the", "considered", "post", "if", "applicable", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L314-L321
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BaseTopicFormView.get_poll_option_formset
def get_poll_option_formset(self, formset_class): """ Returns an instance of the poll option formset to be used in the view. """ if self.request.forum_permission_handler.can_create_polls( self.get_forum(), self.request.user, ): return formset_class(**self.get_poll_option_formset_kwargs())
python
def get_poll_option_formset(self, formset_class): """ Returns an instance of the poll option formset to be used in the view. """ if self.request.forum_permission_handler.can_create_polls( self.get_forum(), self.request.user, ): return formset_class(**self.get_poll_option_formset_kwargs())
[ "def", "get_poll_option_formset", "(", "self", ",", "formset_class", ")", ":", "if", "self", ".", "request", ".", "forum_permission_handler", ".", "can_create_polls", "(", "self", ".", "get_forum", "(", ")", ",", "self", ".", "request", ".", "user", ",", ")", ":", "return", "formset_class", "(", "*", "*", "self", ".", "get_poll_option_formset_kwargs", "(", ")", ")" ]
Returns an instance of the poll option formset to be used in the view.
[ "Returns", "an", "instance", "of", "the", "poll", "option", "formset", "to", "be", "used", "in", "the", "view", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L448-L453
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
BaseTopicFormView.get_poll_option_formset_kwargs
def get_poll_option_formset_kwargs(self): """ Returns the keyword arguments for instantiating the poll option formset. """ kwargs = { 'prefix': 'poll', } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) else: topic = self.get_topic() poll_option_queryset = TopicPollOption.objects.filter(poll__topic=topic) kwargs.update({ 'queryset': poll_option_queryset, }) return kwargs
python
def get_poll_option_formset_kwargs(self): """ Returns the keyword arguments for instantiating the poll option formset. """ kwargs = { 'prefix': 'poll', } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) else: topic = self.get_topic() poll_option_queryset = TopicPollOption.objects.filter(poll__topic=topic) kwargs.update({ 'queryset': poll_option_queryset, }) return kwargs
[ "def", "get_poll_option_formset_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'prefix'", ":", "'poll'", ",", "}", "if", "self", ".", "request", ".", "method", "in", "(", "'POST'", ",", "'PUT'", ")", ":", "kwargs", ".", "update", "(", "{", "'data'", ":", "self", ".", "request", ".", "POST", ",", "'files'", ":", "self", ".", "request", ".", "FILES", ",", "}", ")", "else", ":", "topic", "=", "self", ".", "get_topic", "(", ")", "poll_option_queryset", "=", "TopicPollOption", ".", "objects", ".", "filter", "(", "poll__topic", "=", "topic", ")", "kwargs", ".", "update", "(", "{", "'queryset'", ":", "poll_option_queryset", ",", "}", ")", "return", "kwargs" ]
Returns the keyword arguments for instantiating the poll option formset.
[ "Returns", "the", "keyword", "arguments", "for", "instantiating", "the", "poll", "option", "formset", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L459-L476
train
e1ven/Robohash
robohash/robohash.py
Robohash._remove_exts
def _remove_exts(self,string): """ Sets the string, to create the Robohash """ # If the user hasn't disabled it, we will detect image extensions, such as .png, .jpg, etc. # We'll remove them from the string before hashing. # This ensures that /Bear.png and /Bear.bmp will send back the same image, in different formats. if string.lower().endswith(('.png','.gif','.jpg','.bmp','.jpeg','.ppm','.datauri')): format = string[string.rfind('.') +1 :len(string)] if format.lower() == 'jpg': format = 'jpeg' self.format = format string = string[0:string.rfind('.')] return string
python
def _remove_exts(self,string): """ Sets the string, to create the Robohash """ # If the user hasn't disabled it, we will detect image extensions, such as .png, .jpg, etc. # We'll remove them from the string before hashing. # This ensures that /Bear.png and /Bear.bmp will send back the same image, in different formats. if string.lower().endswith(('.png','.gif','.jpg','.bmp','.jpeg','.ppm','.datauri')): format = string[string.rfind('.') +1 :len(string)] if format.lower() == 'jpg': format = 'jpeg' self.format = format string = string[0:string.rfind('.')] return string
[ "def", "_remove_exts", "(", "self", ",", "string", ")", ":", "# If the user hasn't disabled it, we will detect image extensions, such as .png, .jpg, etc.", "# We'll remove them from the string before hashing.", "# This ensures that /Bear.png and /Bear.bmp will send back the same image, in different formats.", "if", "string", ".", "lower", "(", ")", ".", "endswith", "(", "(", "'.png'", ",", "'.gif'", ",", "'.jpg'", ",", "'.bmp'", ",", "'.jpeg'", ",", "'.ppm'", ",", "'.datauri'", ")", ")", ":", "format", "=", "string", "[", "string", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "len", "(", "string", ")", "]", "if", "format", ".", "lower", "(", ")", "==", "'jpg'", ":", "format", "=", "'jpeg'", "self", ".", "format", "=", "format", "string", "=", "string", "[", "0", ":", "string", ".", "rfind", "(", "'.'", ")", "]", "return", "string" ]
Sets the string, to create the Robohash
[ "Sets", "the", "string", "to", "create", "the", "Robohash" ]
8dbbf9e69948ae2abc93c27511ef04f90b56c4d3
https://github.com/e1ven/Robohash/blob/8dbbf9e69948ae2abc93c27511ef04f90b56c4d3/robohash/robohash.py#L46-L61
train
e1ven/Robohash
robohash/robohash.py
Robohash._get_list_of_files
def _get_list_of_files(self,path): """ Go through each subdirectory of `path`, and choose one file from each to use in our hash. Continue to increase self.iter, so we use a different 'slot' of randomness each time. """ chosen_files = [] # Get a list of all subdirectories directories = [] for root, dirs, files in natsort.natsorted(os.walk(path, topdown=False)): for name in dirs: if name[:1] is not '.': directories.append(os.path.join(root, name)) directories = natsort.natsorted(directories) # Go through each directory in the list, and choose one file from each. # Add this file to our master list of robotparts. for directory in directories: files_in_dir = [] for imagefile in natsort.natsorted(os.listdir(directory)): files_in_dir.append(os.path.join(directory,imagefile)) files_in_dir = natsort.natsorted(files_in_dir) # Use some of our hash bits to choose which file element_in_list = self.hasharray[self.iter] % len(files_in_dir) chosen_files.append(files_in_dir[element_in_list]) self.iter += 1 return chosen_files
python
def _get_list_of_files(self,path): """ Go through each subdirectory of `path`, and choose one file from each to use in our hash. Continue to increase self.iter, so we use a different 'slot' of randomness each time. """ chosen_files = [] # Get a list of all subdirectories directories = [] for root, dirs, files in natsort.natsorted(os.walk(path, topdown=False)): for name in dirs: if name[:1] is not '.': directories.append(os.path.join(root, name)) directories = natsort.natsorted(directories) # Go through each directory in the list, and choose one file from each. # Add this file to our master list of robotparts. for directory in directories: files_in_dir = [] for imagefile in natsort.natsorted(os.listdir(directory)): files_in_dir.append(os.path.join(directory,imagefile)) files_in_dir = natsort.natsorted(files_in_dir) # Use some of our hash bits to choose which file element_in_list = self.hasharray[self.iter] % len(files_in_dir) chosen_files.append(files_in_dir[element_in_list]) self.iter += 1 return chosen_files
[ "def", "_get_list_of_files", "(", "self", ",", "path", ")", ":", "chosen_files", "=", "[", "]", "# Get a list of all subdirectories", "directories", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "natsort", ".", "natsorted", "(", "os", ".", "walk", "(", "path", ",", "topdown", "=", "False", ")", ")", ":", "for", "name", "in", "dirs", ":", "if", "name", "[", ":", "1", "]", "is", "not", "'.'", ":", "directories", ".", "append", "(", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", ")", "directories", "=", "natsort", ".", "natsorted", "(", "directories", ")", "# Go through each directory in the list, and choose one file from each.", "# Add this file to our master list of robotparts.", "for", "directory", "in", "directories", ":", "files_in_dir", "=", "[", "]", "for", "imagefile", "in", "natsort", ".", "natsorted", "(", "os", ".", "listdir", "(", "directory", ")", ")", ":", "files_in_dir", ".", "append", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "imagefile", ")", ")", "files_in_dir", "=", "natsort", ".", "natsorted", "(", "files_in_dir", ")", "# Use some of our hash bits to choose which file", "element_in_list", "=", "self", ".", "hasharray", "[", "self", ".", "iter", "]", "%", "len", "(", "files_in_dir", ")", "chosen_files", ".", "append", "(", "files_in_dir", "[", "element_in_list", "]", ")", "self", ".", "iter", "+=", "1", "return", "chosen_files" ]
Go through each subdirectory of `path`, and choose one file from each to use in our hash. Continue to increase self.iter, so we use a different 'slot' of randomness each time.
[ "Go", "through", "each", "subdirectory", "of", "path", "and", "choose", "one", "file", "from", "each", "to", "use", "in", "our", "hash", ".", "Continue", "to", "increase", "self", ".", "iter", "so", "we", "use", "a", "different", "slot", "of", "randomness", "each", "time", "." ]
8dbbf9e69948ae2abc93c27511ef04f90b56c4d3
https://github.com/e1ven/Robohash/blob/8dbbf9e69948ae2abc93c27511ef04f90b56c4d3/robohash/robohash.py#L85-L113
train
e1ven/Robohash
robohash/robohash.py
Robohash.assemble
def assemble(self,roboset=None,color=None,format=None,bgset=None,sizex=300,sizey=300): """ Build our Robot! Returns the robot image itself. """ # Allow users to manually specify a robot 'set' that they like. # Ensure that this is one of the allowed choices, or allow all # If they don't set one, take the first entry from sets above. if roboset == 'any': roboset = self.sets[self.hasharray[1] % len(self.sets) ] elif roboset in self.sets: roboset = roboset else: roboset = self.sets[0] # Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors. # This could/should probably be expanded at some point.. # Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs ) if roboset == 'set1': if color in self.colors: roboset = 'set1/' + color else: randomcolor = self.colors[self.hasharray[0] % len(self.colors) ] roboset = 'set1/' + randomcolor # If they specified a background, ensure it's legal, then give it to them. if bgset in self.bgsets: bgset = bgset elif bgset == 'any': bgset = self.bgsets[ self.hasharray[2] % len(self.bgsets) ] # If we set a format based on extension earlier, use that. Otherwise, PNG. if format is None: format = self.format # Each directory in our set represents one piece of the Robot, such as the eyes, nose, mouth, etc. # Each directory is named with two numbers - The number before the # is the sort order. # This ensures that they always go in the same order when choosing pieces, regardless of OS. # The second number is the order in which to apply the pieces. # For instance, the head has to go down BEFORE the eyes, or the eyes would be hidden. # First, we'll get a list of parts of our robot. roboparts = self._get_list_of_files(self.resourcedir + 'sets/' + roboset) # Now that we've sorted them by the first number, we need to sort each sub-category by the second. roboparts.sort(key=lambda x: x.split("#")[1]) if bgset is not None: bglist = [] backgrounds = natsort.natsorted(os.listdir(self.resourcedir + 'backgrounds/' + bgset)) backgrounds.sort() for ls in backgrounds: if not ls.startswith("."): bglist.append(self.resourcedir + 'backgrounds/' + bgset + "/" + ls) background = bglist[self.hasharray[3] % len(bglist)] # Paste in each piece of the Robot. roboimg = Image.open(roboparts[0]) roboimg = roboimg.resize((1024,1024)) for png in roboparts: img = Image.open(png) img = img.resize((1024,1024)) roboimg.paste(img,(0,0),img) # If we're a BMP, flatten the image. if format == 'bmp': #Flatten bmps r, g, b, a = roboimg.split() roboimg = Image.merge("RGB", (r, g, b)) if bgset is not None: bg = Image.open(background) bg = bg.resize((1024,1024)) bg.paste(roboimg,(0,0),roboimg) roboimg = bg self.img = roboimg.resize((sizex,sizey),Image.ANTIALIAS) self.format = format
python
def assemble(self,roboset=None,color=None,format=None,bgset=None,sizex=300,sizey=300): """ Build our Robot! Returns the robot image itself. """ # Allow users to manually specify a robot 'set' that they like. # Ensure that this is one of the allowed choices, or allow all # If they don't set one, take the first entry from sets above. if roboset == 'any': roboset = self.sets[self.hasharray[1] % len(self.sets) ] elif roboset in self.sets: roboset = roboset else: roboset = self.sets[0] # Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors. # This could/should probably be expanded at some point.. # Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs ) if roboset == 'set1': if color in self.colors: roboset = 'set1/' + color else: randomcolor = self.colors[self.hasharray[0] % len(self.colors) ] roboset = 'set1/' + randomcolor # If they specified a background, ensure it's legal, then give it to them. if bgset in self.bgsets: bgset = bgset elif bgset == 'any': bgset = self.bgsets[ self.hasharray[2] % len(self.bgsets) ] # If we set a format based on extension earlier, use that. Otherwise, PNG. if format is None: format = self.format # Each directory in our set represents one piece of the Robot, such as the eyes, nose, mouth, etc. # Each directory is named with two numbers - The number before the # is the sort order. # This ensures that they always go in the same order when choosing pieces, regardless of OS. # The second number is the order in which to apply the pieces. # For instance, the head has to go down BEFORE the eyes, or the eyes would be hidden. # First, we'll get a list of parts of our robot. roboparts = self._get_list_of_files(self.resourcedir + 'sets/' + roboset) # Now that we've sorted them by the first number, we need to sort each sub-category by the second. roboparts.sort(key=lambda x: x.split("#")[1]) if bgset is not None: bglist = [] backgrounds = natsort.natsorted(os.listdir(self.resourcedir + 'backgrounds/' + bgset)) backgrounds.sort() for ls in backgrounds: if not ls.startswith("."): bglist.append(self.resourcedir + 'backgrounds/' + bgset + "/" + ls) background = bglist[self.hasharray[3] % len(bglist)] # Paste in each piece of the Robot. roboimg = Image.open(roboparts[0]) roboimg = roboimg.resize((1024,1024)) for png in roboparts: img = Image.open(png) img = img.resize((1024,1024)) roboimg.paste(img,(0,0),img) # If we're a BMP, flatten the image. if format == 'bmp': #Flatten bmps r, g, b, a = roboimg.split() roboimg = Image.merge("RGB", (r, g, b)) if bgset is not None: bg = Image.open(background) bg = bg.resize((1024,1024)) bg.paste(roboimg,(0,0),roboimg) roboimg = bg self.img = roboimg.resize((sizex,sizey),Image.ANTIALIAS) self.format = format
[ "def", "assemble", "(", "self", ",", "roboset", "=", "None", ",", "color", "=", "None", ",", "format", "=", "None", ",", "bgset", "=", "None", ",", "sizex", "=", "300", ",", "sizey", "=", "300", ")", ":", "# Allow users to manually specify a robot 'set' that they like.", "# Ensure that this is one of the allowed choices, or allow all", "# If they don't set one, take the first entry from sets above.", "if", "roboset", "==", "'any'", ":", "roboset", "=", "self", ".", "sets", "[", "self", ".", "hasharray", "[", "1", "]", "%", "len", "(", "self", ".", "sets", ")", "]", "elif", "roboset", "in", "self", ".", "sets", ":", "roboset", "=", "roboset", "else", ":", "roboset", "=", "self", ".", "sets", "[", "0", "]", "# Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors.", "# This could/should probably be expanded at some point..", "# Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs )", "if", "roboset", "==", "'set1'", ":", "if", "color", "in", "self", ".", "colors", ":", "roboset", "=", "'set1/'", "+", "color", "else", ":", "randomcolor", "=", "self", ".", "colors", "[", "self", ".", "hasharray", "[", "0", "]", "%", "len", "(", "self", ".", "colors", ")", "]", "roboset", "=", "'set1/'", "+", "randomcolor", "# If they specified a background, ensure it's legal, then give it to them.", "if", "bgset", "in", "self", ".", "bgsets", ":", "bgset", "=", "bgset", "elif", "bgset", "==", "'any'", ":", "bgset", "=", "self", ".", "bgsets", "[", "self", ".", "hasharray", "[", "2", "]", "%", "len", "(", "self", ".", "bgsets", ")", "]", "# If we set a format based on extension earlier, use that. Otherwise, PNG.", "if", "format", "is", "None", ":", "format", "=", "self", ".", "format", "# Each directory in our set represents one piece of the Robot, such as the eyes, nose, mouth, etc.", "# Each directory is named with two numbers - The number before the # is the sort order.", "# This ensures that they always go in the same order when choosing pieces, regardless of OS.", "# The second number is the order in which to apply the pieces.", "# For instance, the head has to go down BEFORE the eyes, or the eyes would be hidden.", "# First, we'll get a list of parts of our robot.", "roboparts", "=", "self", ".", "_get_list_of_files", "(", "self", ".", "resourcedir", "+", "'sets/'", "+", "roboset", ")", "# Now that we've sorted them by the first number, we need to sort each sub-category by the second.", "roboparts", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "split", "(", "\"#\"", ")", "[", "1", "]", ")", "if", "bgset", "is", "not", "None", ":", "bglist", "=", "[", "]", "backgrounds", "=", "natsort", ".", "natsorted", "(", "os", ".", "listdir", "(", "self", ".", "resourcedir", "+", "'backgrounds/'", "+", "bgset", ")", ")", "backgrounds", ".", "sort", "(", ")", "for", "ls", "in", "backgrounds", ":", "if", "not", "ls", ".", "startswith", "(", "\".\"", ")", ":", "bglist", ".", "append", "(", "self", ".", "resourcedir", "+", "'backgrounds/'", "+", "bgset", "+", "\"/\"", "+", "ls", ")", "background", "=", "bglist", "[", "self", ".", "hasharray", "[", "3", "]", "%", "len", "(", "bglist", ")", "]", "# Paste in each piece of the Robot.", "roboimg", "=", "Image", ".", "open", "(", "roboparts", "[", "0", "]", ")", "roboimg", "=", "roboimg", ".", "resize", "(", "(", "1024", ",", "1024", ")", ")", "for", "png", "in", "roboparts", ":", "img", "=", "Image", ".", "open", "(", "png", ")", "img", "=", "img", ".", "resize", "(", "(", "1024", ",", "1024", ")", ")", "roboimg", ".", "paste", "(", "img", ",", "(", "0", ",", "0", ")", ",", "img", ")", "# If we're a BMP, flatten the image.", "if", "format", "==", "'bmp'", ":", "#Flatten bmps", "r", ",", "g", ",", "b", ",", "a", "=", "roboimg", ".", "split", "(", ")", "roboimg", "=", "Image", ".", "merge", "(", "\"RGB\"", ",", "(", "r", ",", "g", ",", "b", ")", ")", "if", "bgset", "is", "not", "None", ":", "bg", "=", "Image", ".", "open", "(", "background", ")", "bg", "=", "bg", ".", "resize", "(", "(", "1024", ",", "1024", ")", ")", "bg", ".", "paste", "(", "roboimg", ",", "(", "0", ",", "0", ")", ",", "roboimg", ")", "roboimg", "=", "bg", "self", ".", "img", "=", "roboimg", ".", "resize", "(", "(", "sizex", ",", "sizey", ")", ",", "Image", ".", "ANTIALIAS", ")", "self", ".", "format", "=", "format" ]
Build our Robot! Returns the robot image itself.
[ "Build", "our", "Robot!", "Returns", "the", "robot", "image", "itself", "." ]
8dbbf9e69948ae2abc93c27511ef04f90b56c4d3
https://github.com/e1ven/Robohash/blob/8dbbf9e69948ae2abc93c27511ef04f90b56c4d3/robohash/robohash.py#L115-L198
train
tensorflow/skflow
scripts/docs/docs.py
collect_members
def collect_members(module_to_name): """Collect all symbols from a list of modules. Args: module_to_name: Dictionary mapping modules to short names. Returns: Dictionary mapping name to (fullname, member) pairs. """ members = {} for module, module_name in module_to_name.items(): all_names = getattr(module, "__all__", None) for name, member in inspect.getmembers(module): if ((inspect.isfunction(member) or inspect.isclass(member)) and not _always_drop_symbol_re.match(name) and (all_names is None or name in all_names)): fullname = '%s.%s' % (module_name, name) if name in members: other_fullname, other_member = members[name] if member is not other_member: raise RuntimeError("Short name collision between %s and %s" % (fullname, other_fullname)) if len(fullname) == len(other_fullname): raise RuntimeError("Can't decide whether to use %s or %s for %s: " "both full names have length %d" % (fullname, other_fullname, name, len(fullname))) if len(fullname) > len(other_fullname): continue # Use the shorter full name members[name] = fullname, member return members
python
def collect_members(module_to_name): """Collect all symbols from a list of modules. Args: module_to_name: Dictionary mapping modules to short names. Returns: Dictionary mapping name to (fullname, member) pairs. """ members = {} for module, module_name in module_to_name.items(): all_names = getattr(module, "__all__", None) for name, member in inspect.getmembers(module): if ((inspect.isfunction(member) or inspect.isclass(member)) and not _always_drop_symbol_re.match(name) and (all_names is None or name in all_names)): fullname = '%s.%s' % (module_name, name) if name in members: other_fullname, other_member = members[name] if member is not other_member: raise RuntimeError("Short name collision between %s and %s" % (fullname, other_fullname)) if len(fullname) == len(other_fullname): raise RuntimeError("Can't decide whether to use %s or %s for %s: " "both full names have length %d" % (fullname, other_fullname, name, len(fullname))) if len(fullname) > len(other_fullname): continue # Use the shorter full name members[name] = fullname, member return members
[ "def", "collect_members", "(", "module_to_name", ")", ":", "members", "=", "{", "}", "for", "module", ",", "module_name", "in", "module_to_name", ".", "items", "(", ")", ":", "all_names", "=", "getattr", "(", "module", ",", "\"__all__\"", ",", "None", ")", "for", "name", ",", "member", "in", "inspect", ".", "getmembers", "(", "module", ")", ":", "if", "(", "(", "inspect", ".", "isfunction", "(", "member", ")", "or", "inspect", ".", "isclass", "(", "member", ")", ")", "and", "not", "_always_drop_symbol_re", ".", "match", "(", "name", ")", "and", "(", "all_names", "is", "None", "or", "name", "in", "all_names", ")", ")", ":", "fullname", "=", "'%s.%s'", "%", "(", "module_name", ",", "name", ")", "if", "name", "in", "members", ":", "other_fullname", ",", "other_member", "=", "members", "[", "name", "]", "if", "member", "is", "not", "other_member", ":", "raise", "RuntimeError", "(", "\"Short name collision between %s and %s\"", "%", "(", "fullname", ",", "other_fullname", ")", ")", "if", "len", "(", "fullname", ")", "==", "len", "(", "other_fullname", ")", ":", "raise", "RuntimeError", "(", "\"Can't decide whether to use %s or %s for %s: \"", "\"both full names have length %d\"", "%", "(", "fullname", ",", "other_fullname", ",", "name", ",", "len", "(", "fullname", ")", ")", ")", "if", "len", "(", "fullname", ")", ">", "len", "(", "other_fullname", ")", ":", "continue", "# Use the shorter full name", "members", "[", "name", "]", "=", "fullname", ",", "member", "return", "members" ]
Collect all symbols from a list of modules. Args: module_to_name: Dictionary mapping modules to short names. Returns: Dictionary mapping name to (fullname, member) pairs.
[ "Collect", "all", "symbols", "from", "a", "list", "of", "modules", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L103-L132
train
tensorflow/skflow
scripts/docs/docs.py
_get_anchor
def _get_anchor(module_to_name, fullname): """Turn a full member name into an anchor. Args: module_to_name: Dictionary mapping modules to short names. fullname: Fully qualified name of symbol. Returns: HTML anchor string. The longest module name prefix of fullname is removed to make the anchor. Raises: ValueError: If fullname uses characters invalid in an anchor. """ if not _anchor_re.match(fullname): raise ValueError("'%s' is not a valid anchor" % fullname) anchor = fullname for module_name in module_to_name.values(): if fullname.startswith(module_name + "."): rest = fullname[len(module_name)+1:] # Use this prefix iff it is longer than any found before if len(anchor) > len(rest): anchor = rest return anchor
python
def _get_anchor(module_to_name, fullname): """Turn a full member name into an anchor. Args: module_to_name: Dictionary mapping modules to short names. fullname: Fully qualified name of symbol. Returns: HTML anchor string. The longest module name prefix of fullname is removed to make the anchor. Raises: ValueError: If fullname uses characters invalid in an anchor. """ if not _anchor_re.match(fullname): raise ValueError("'%s' is not a valid anchor" % fullname) anchor = fullname for module_name in module_to_name.values(): if fullname.startswith(module_name + "."): rest = fullname[len(module_name)+1:] # Use this prefix iff it is longer than any found before if len(anchor) > len(rest): anchor = rest return anchor
[ "def", "_get_anchor", "(", "module_to_name", ",", "fullname", ")", ":", "if", "not", "_anchor_re", ".", "match", "(", "fullname", ")", ":", "raise", "ValueError", "(", "\"'%s' is not a valid anchor\"", "%", "fullname", ")", "anchor", "=", "fullname", "for", "module_name", "in", "module_to_name", ".", "values", "(", ")", ":", "if", "fullname", ".", "startswith", "(", "module_name", "+", "\".\"", ")", ":", "rest", "=", "fullname", "[", "len", "(", "module_name", ")", "+", "1", ":", "]", "# Use this prefix iff it is longer than any found before", "if", "len", "(", "anchor", ")", ">", "len", "(", "rest", ")", ":", "anchor", "=", "rest", "return", "anchor" ]
Turn a full member name into an anchor. Args: module_to_name: Dictionary mapping modules to short names. fullname: Fully qualified name of symbol. Returns: HTML anchor string. The longest module name prefix of fullname is removed to make the anchor. Raises: ValueError: If fullname uses characters invalid in an anchor.
[ "Turn", "a", "full", "member", "name", "into", "an", "anchor", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L135-L158
train
tensorflow/skflow
scripts/docs/docs.py
write_libraries
def write_libraries(dir, libraries): """Write a list of libraries to disk. Args: dir: Output directory. libraries: List of (filename, library) pairs. """ files = [open(os.path.join(dir, k), "w") for k, _ in libraries] # Document mentioned symbols for all libraries for f, (_, v) in zip(files, libraries): v.write_markdown_to_file(f) # Document symbols that no library mentioned. We do this after writing # out all libraries so that earlier libraries know what later libraries # documented. for f, (_, v) in zip(files, libraries): v.write_other_members(f) f.close()
python
def write_libraries(dir, libraries): """Write a list of libraries to disk. Args: dir: Output directory. libraries: List of (filename, library) pairs. """ files = [open(os.path.join(dir, k), "w") for k, _ in libraries] # Document mentioned symbols for all libraries for f, (_, v) in zip(files, libraries): v.write_markdown_to_file(f) # Document symbols that no library mentioned. We do this after writing # out all libraries so that earlier libraries know what later libraries # documented. for f, (_, v) in zip(files, libraries): v.write_other_members(f) f.close()
[ "def", "write_libraries", "(", "dir", ",", "libraries", ")", ":", "files", "=", "[", "open", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "k", ")", ",", "\"w\"", ")", "for", "k", ",", "_", "in", "libraries", "]", "# Document mentioned symbols for all libraries", "for", "f", ",", "(", "_", ",", "v", ")", "in", "zip", "(", "files", ",", "libraries", ")", ":", "v", ".", "write_markdown_to_file", "(", "f", ")", "# Document symbols that no library mentioned. We do this after writing", "# out all libraries so that earlier libraries know what later libraries", "# documented.", "for", "f", ",", "(", "_", ",", "v", ")", "in", "zip", "(", "files", ",", "libraries", ")", ":", "v", ".", "write_other_members", "(", "f", ")", "f", ".", "close", "(", ")" ]
Write a list of libraries to disk. Args: dir: Output directory. libraries: List of (filename, library) pairs.
[ "Write", "a", "list", "of", "libraries", "to", "disk", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L514-L530
train
tensorflow/skflow
scripts/docs/docs.py
Index.write_markdown_to_file
def write_markdown_to_file(self, f): """Writes this index to file `f`. The output is formatted as an unordered list. Each list element contains the title of the library, followed by a list of symbols in that library hyperlinked to the corresponding anchor in that library. Args: f: The output file. """ print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) print("# TensorFlow Python reference documentation", file=f) print("", file=f) fullname_f = lambda name: self._members[name][0] anchor_f = lambda name: _get_anchor(self._module_to_name, fullname_f(name)) for filename, library in self._filename_to_library_map: sorted_names = sorted(library.mentioned, key=lambda x: (str.lower(x), x)) member_names = [n for n in sorted_names if n in self._members] # TODO: This is a hack that should be removed as soon as the website code # allows it. full_filename = self._path_prefix + filename links = ["[`%s`](%s#%s)" % (name, full_filename[:-3], anchor_f(name)) for name in member_names] if links: print("* **[%s](%s)**:" % (library.title, full_filename[:-3]), file=f) for link in links: print(" * %s" % link, file=f) print("", file=f)
python
def write_markdown_to_file(self, f): """Writes this index to file `f`. The output is formatted as an unordered list. Each list element contains the title of the library, followed by a list of symbols in that library hyperlinked to the corresponding anchor in that library. Args: f: The output file. """ print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) print("# TensorFlow Python reference documentation", file=f) print("", file=f) fullname_f = lambda name: self._members[name][0] anchor_f = lambda name: _get_anchor(self._module_to_name, fullname_f(name)) for filename, library in self._filename_to_library_map: sorted_names = sorted(library.mentioned, key=lambda x: (str.lower(x), x)) member_names = [n for n in sorted_names if n in self._members] # TODO: This is a hack that should be removed as soon as the website code # allows it. full_filename = self._path_prefix + filename links = ["[`%s`](%s#%s)" % (name, full_filename[:-3], anchor_f(name)) for name in member_names] if links: print("* **[%s](%s)**:" % (library.title, full_filename[:-3]), file=f) for link in links: print(" * %s" % link, file=f) print("", file=f)
[ "def", "write_markdown_to_file", "(", "self", ",", "f", ")", ":", "print", "(", "\"---\"", ",", "file", "=", "f", ")", "print", "(", "\"---\"", ",", "file", "=", "f", ")", "print", "(", "\"<!-- This file is machine generated: DO NOT EDIT! -->\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "print", "(", "\"# TensorFlow Python reference documentation\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "fullname_f", "=", "lambda", "name", ":", "self", ".", "_members", "[", "name", "]", "[", "0", "]", "anchor_f", "=", "lambda", "name", ":", "_get_anchor", "(", "self", ".", "_module_to_name", ",", "fullname_f", "(", "name", ")", ")", "for", "filename", ",", "library", "in", "self", ".", "_filename_to_library_map", ":", "sorted_names", "=", "sorted", "(", "library", ".", "mentioned", ",", "key", "=", "lambda", "x", ":", "(", "str", ".", "lower", "(", "x", ")", ",", "x", ")", ")", "member_names", "=", "[", "n", "for", "n", "in", "sorted_names", "if", "n", "in", "self", ".", "_members", "]", "# TODO: This is a hack that should be removed as soon as the website code", "# allows it.", "full_filename", "=", "self", ".", "_path_prefix", "+", "filename", "links", "=", "[", "\"[`%s`](%s#%s)\"", "%", "(", "name", ",", "full_filename", "[", ":", "-", "3", "]", ",", "anchor_f", "(", "name", ")", ")", "for", "name", "in", "member_names", "]", "if", "links", ":", "print", "(", "\"* **[%s](%s)**:\"", "%", "(", "library", ".", "title", ",", "full_filename", "[", ":", "-", "3", "]", ")", ",", "file", "=", "f", ")", "for", "link", "in", "links", ":", "print", "(", "\" * %s\"", "%", "link", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")" ]
Writes this index to file `f`. The output is formatted as an unordered list. Each list element contains the title of the library, followed by a list of symbols in that library hyperlinked to the corresponding anchor in that library. Args: f: The output file.
[ "Writes", "this", "index", "to", "file", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L68-L100
train
tensorflow/skflow
scripts/docs/docs.py
Library._should_include_member
def _should_include_member(self, name, member): """Returns True if this member should be included in the document.""" # Always exclude symbols matching _always_drop_symbol_re. if _always_drop_symbol_re.match(name): return False # Finally, exclude any specifically-excluded symbols. if name in self._exclude_symbols: return False return True
python
def _should_include_member(self, name, member): """Returns True if this member should be included in the document.""" # Always exclude symbols matching _always_drop_symbol_re. if _always_drop_symbol_re.match(name): return False # Finally, exclude any specifically-excluded symbols. if name in self._exclude_symbols: return False return True
[ "def", "_should_include_member", "(", "self", ",", "name", ",", "member", ")", ":", "# Always exclude symbols matching _always_drop_symbol_re.", "if", "_always_drop_symbol_re", ".", "match", "(", "name", ")", ":", "return", "False", "# Finally, exclude any specifically-excluded symbols.", "if", "name", "in", "self", ".", "_exclude_symbols", ":", "return", "False", "return", "True" ]
Returns True if this member should be included in the document.
[ "Returns", "True", "if", "this", "member", "should", "be", "included", "in", "the", "document", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L209-L217
train
tensorflow/skflow
scripts/docs/docs.py
Library.get_imported_modules
def get_imported_modules(self, module): """Returns the list of modules imported from `module`.""" for name, member in inspect.getmembers(module): if inspect.ismodule(member): yield name, member
python
def get_imported_modules(self, module): """Returns the list of modules imported from `module`.""" for name, member in inspect.getmembers(module): if inspect.ismodule(member): yield name, member
[ "def", "get_imported_modules", "(", "self", ",", "module", ")", ":", "for", "name", ",", "member", "in", "inspect", ".", "getmembers", "(", "module", ")", ":", "if", "inspect", ".", "ismodule", "(", "member", ")", ":", "yield", "name", ",", "member" ]
Returns the list of modules imported from `module`.
[ "Returns", "the", "list", "of", "modules", "imported", "from", "module", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L219-L223
train
tensorflow/skflow
scripts/docs/docs.py
Library.get_class_members
def get_class_members(self, cls_name, cls): """Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'class'. Yields: name, member tuples. """ for name, member in inspect.getmembers(cls): # Only show methods and properties presently. In Python 3, # methods register as isfunction. is_method = inspect.ismethod(member) or inspect.isfunction(member) if not (is_method or isinstance(member, property)): continue if ((is_method and member.__name__ == "__init__") or self._should_include_member(name, member)): yield name, ("%s.%s" % (cls_name, name), member)
python
def get_class_members(self, cls_name, cls): """Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'class'. Yields: name, member tuples. """ for name, member in inspect.getmembers(cls): # Only show methods and properties presently. In Python 3, # methods register as isfunction. is_method = inspect.ismethod(member) or inspect.isfunction(member) if not (is_method or isinstance(member, property)): continue if ((is_method and member.__name__ == "__init__") or self._should_include_member(name, member)): yield name, ("%s.%s" % (cls_name, name), member)
[ "def", "get_class_members", "(", "self", ",", "cls_name", ",", "cls", ")", ":", "for", "name", ",", "member", "in", "inspect", ".", "getmembers", "(", "cls", ")", ":", "# Only show methods and properties presently. In Python 3,", "# methods register as isfunction.", "is_method", "=", "inspect", ".", "ismethod", "(", "member", ")", "or", "inspect", ".", "isfunction", "(", "member", ")", "if", "not", "(", "is_method", "or", "isinstance", "(", "member", ",", "property", ")", ")", ":", "continue", "if", "(", "(", "is_method", "and", "member", ".", "__name__", "==", "\"__init__\"", ")", "or", "self", ".", "_should_include_member", "(", "name", ",", "member", ")", ")", ":", "yield", "name", ",", "(", "\"%s.%s\"", "%", "(", "cls_name", ",", "name", ")", ",", "member", ")" ]
Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'class'. Yields: name, member tuples.
[ "Returns", "the", "list", "of", "class", "members", "to", "document", "in", "cls", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L225-L246
train
tensorflow/skflow
scripts/docs/docs.py
Library._generate_signature_for_function
def _generate_signature_for_function(self, func): """Given a function, returns a string representing its args.""" args_list = [] argspec = inspect.getargspec(func) first_arg_with_default = ( len(argspec.args or []) - len(argspec.defaults or [])) for arg in argspec.args[:first_arg_with_default]: if arg == "self": # Python documentation typically skips `self` when printing method # signatures. continue args_list.append(arg) # TODO(mrry): This is a workaround for documenting signature of # functions that have the @contextlib.contextmanager decorator. # We should do something better. if argspec.varargs == "args" and argspec.keywords == "kwds": original_func = func.__closure__[0].cell_contents return self._generate_signature_for_function(original_func) if argspec.defaults: for arg, default in zip( argspec.args[first_arg_with_default:], argspec.defaults): if callable(default): args_list.append("%s=%s" % (arg, default.__name__)) else: args_list.append("%s=%r" % (arg, default)) if argspec.varargs: args_list.append("*" + argspec.varargs) if argspec.keywords: args_list.append("**" + argspec.keywords) return "(" + ", ".join(args_list) + ")"
python
def _generate_signature_for_function(self, func): """Given a function, returns a string representing its args.""" args_list = [] argspec = inspect.getargspec(func) first_arg_with_default = ( len(argspec.args or []) - len(argspec.defaults or [])) for arg in argspec.args[:first_arg_with_default]: if arg == "self": # Python documentation typically skips `self` when printing method # signatures. continue args_list.append(arg) # TODO(mrry): This is a workaround for documenting signature of # functions that have the @contextlib.contextmanager decorator. # We should do something better. if argspec.varargs == "args" and argspec.keywords == "kwds": original_func = func.__closure__[0].cell_contents return self._generate_signature_for_function(original_func) if argspec.defaults: for arg, default in zip( argspec.args[first_arg_with_default:], argspec.defaults): if callable(default): args_list.append("%s=%s" % (arg, default.__name__)) else: args_list.append("%s=%r" % (arg, default)) if argspec.varargs: args_list.append("*" + argspec.varargs) if argspec.keywords: args_list.append("**" + argspec.keywords) return "(" + ", ".join(args_list) + ")"
[ "def", "_generate_signature_for_function", "(", "self", ",", "func", ")", ":", "args_list", "=", "[", "]", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "first_arg_with_default", "=", "(", "len", "(", "argspec", ".", "args", "or", "[", "]", ")", "-", "len", "(", "argspec", ".", "defaults", "or", "[", "]", ")", ")", "for", "arg", "in", "argspec", ".", "args", "[", ":", "first_arg_with_default", "]", ":", "if", "arg", "==", "\"self\"", ":", "# Python documentation typically skips `self` when printing method", "# signatures.", "continue", "args_list", ".", "append", "(", "arg", ")", "# TODO(mrry): This is a workaround for documenting signature of", "# functions that have the @contextlib.contextmanager decorator.", "# We should do something better.", "if", "argspec", ".", "varargs", "==", "\"args\"", "and", "argspec", ".", "keywords", "==", "\"kwds\"", ":", "original_func", "=", "func", ".", "__closure__", "[", "0", "]", ".", "cell_contents", "return", "self", ".", "_generate_signature_for_function", "(", "original_func", ")", "if", "argspec", ".", "defaults", ":", "for", "arg", ",", "default", "in", "zip", "(", "argspec", ".", "args", "[", "first_arg_with_default", ":", "]", ",", "argspec", ".", "defaults", ")", ":", "if", "callable", "(", "default", ")", ":", "args_list", ".", "append", "(", "\"%s=%s\"", "%", "(", "arg", ",", "default", ".", "__name__", ")", ")", "else", ":", "args_list", ".", "append", "(", "\"%s=%r\"", "%", "(", "arg", ",", "default", ")", ")", "if", "argspec", ".", "varargs", ":", "args_list", ".", "append", "(", "\"*\"", "+", "argspec", ".", "varargs", ")", "if", "argspec", ".", "keywords", ":", "args_list", ".", "append", "(", "\"**\"", "+", "argspec", ".", "keywords", ")", "return", "\"(\"", "+", "\", \"", ".", "join", "(", "args_list", ")", "+", "\")\"" ]
Given a function, returns a string representing its args.
[ "Given", "a", "function", "returns", "a", "string", "representing", "its", "args", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L248-L279
train
tensorflow/skflow
scripts/docs/docs.py
Library._remove_docstring_indent
def _remove_docstring_indent(self, docstring): """Remove indenting. We follow Python's convention and remove the minimum indent of the lines after the first, see: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation preserving relative indentation. Args: docstring: A docstring. Returns: A list of strings, one per line, with the minimum indent stripped. """ docstring = docstring or "" lines = docstring.strip().split("\n") min_indent = len(docstring) for l in lines[1:]: l = l.rstrip() if l: i = 0 while i < len(l) and l[i] == " ": i += 1 if i < min_indent: min_indent = i for i in range(1, len(lines)): l = lines[i].rstrip() if len(l) >= min_indent: l = l[min_indent:] lines[i] = l return lines
python
def _remove_docstring_indent(self, docstring): """Remove indenting. We follow Python's convention and remove the minimum indent of the lines after the first, see: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation preserving relative indentation. Args: docstring: A docstring. Returns: A list of strings, one per line, with the minimum indent stripped. """ docstring = docstring or "" lines = docstring.strip().split("\n") min_indent = len(docstring) for l in lines[1:]: l = l.rstrip() if l: i = 0 while i < len(l) and l[i] == " ": i += 1 if i < min_indent: min_indent = i for i in range(1, len(lines)): l = lines[i].rstrip() if len(l) >= min_indent: l = l[min_indent:] lines[i] = l return lines
[ "def", "_remove_docstring_indent", "(", "self", ",", "docstring", ")", ":", "docstring", "=", "docstring", "or", "\"\"", "lines", "=", "docstring", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "min_indent", "=", "len", "(", "docstring", ")", "for", "l", "in", "lines", "[", "1", ":", "]", ":", "l", "=", "l", ".", "rstrip", "(", ")", "if", "l", ":", "i", "=", "0", "while", "i", "<", "len", "(", "l", ")", "and", "l", "[", "i", "]", "==", "\" \"", ":", "i", "+=", "1", "if", "i", "<", "min_indent", ":", "min_indent", "=", "i", "for", "i", "in", "range", "(", "1", ",", "len", "(", "lines", ")", ")", ":", "l", "=", "lines", "[", "i", "]", ".", "rstrip", "(", ")", "if", "len", "(", "l", ")", ">=", "min_indent", ":", "l", "=", "l", "[", "min_indent", ":", "]", "lines", "[", "i", "]", "=", "l", "return", "lines" ]
Remove indenting. We follow Python's convention and remove the minimum indent of the lines after the first, see: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation preserving relative indentation. Args: docstring: A docstring. Returns: A list of strings, one per line, with the minimum indent stripped.
[ "Remove", "indenting", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L281-L311
train
tensorflow/skflow
scripts/docs/docs.py
Library._print_formatted_docstring
def _print_formatted_docstring(self, docstring, f): """Formats the given `docstring` as Markdown and prints it to `f`.""" lines = self._remove_docstring_indent(docstring) # Output the lines, identifying "Args" and other section blocks. i = 0 def _at_start_of_section(): """Returns the header if lines[i] is at start of a docstring section.""" l = lines[i] match = _section_re.match(l) if match and i + 1 < len( lines) and lines[i + 1].startswith(" "): return match.group(1) else: return None while i < len(lines): l = lines[i] section_header = _at_start_of_section() if section_header: if i == 0 or lines[i-1]: print("", file=f) # Use at least H4 to keep these out of the TOC. print("##### " + section_header + ":", file=f) print("", file=f) i += 1 outputting_list = False while i < len(lines): l = lines[i] # A new section header terminates the section. if _at_start_of_section(): break match = _arg_re.match(l) if match: if not outputting_list: # We need to start a list. In Markdown, a blank line needs to # precede a list. print("", file=f) outputting_list = True suffix = l[len(match.group()):].lstrip() print("* <b>`" + match.group(1) + "`</b>: " + suffix, file=f) else: # For lines that don't start with _arg_re, continue the list if it # has enough indentation. outputting_list &= l.startswith(" ") print(l, file=f) i += 1 else: print(l, file=f) i += 1
python
def _print_formatted_docstring(self, docstring, f): """Formats the given `docstring` as Markdown and prints it to `f`.""" lines = self._remove_docstring_indent(docstring) # Output the lines, identifying "Args" and other section blocks. i = 0 def _at_start_of_section(): """Returns the header if lines[i] is at start of a docstring section.""" l = lines[i] match = _section_re.match(l) if match and i + 1 < len( lines) and lines[i + 1].startswith(" "): return match.group(1) else: return None while i < len(lines): l = lines[i] section_header = _at_start_of_section() if section_header: if i == 0 or lines[i-1]: print("", file=f) # Use at least H4 to keep these out of the TOC. print("##### " + section_header + ":", file=f) print("", file=f) i += 1 outputting_list = False while i < len(lines): l = lines[i] # A new section header terminates the section. if _at_start_of_section(): break match = _arg_re.match(l) if match: if not outputting_list: # We need to start a list. In Markdown, a blank line needs to # precede a list. print("", file=f) outputting_list = True suffix = l[len(match.group()):].lstrip() print("* <b>`" + match.group(1) + "`</b>: " + suffix, file=f) else: # For lines that don't start with _arg_re, continue the list if it # has enough indentation. outputting_list &= l.startswith(" ") print(l, file=f) i += 1 else: print(l, file=f) i += 1
[ "def", "_print_formatted_docstring", "(", "self", ",", "docstring", ",", "f", ")", ":", "lines", "=", "self", ".", "_remove_docstring_indent", "(", "docstring", ")", "# Output the lines, identifying \"Args\" and other section blocks.", "i", "=", "0", "def", "_at_start_of_section", "(", ")", ":", "\"\"\"Returns the header if lines[i] is at start of a docstring section.\"\"\"", "l", "=", "lines", "[", "i", "]", "match", "=", "_section_re", ".", "match", "(", "l", ")", "if", "match", "and", "i", "+", "1", "<", "len", "(", "lines", ")", "and", "lines", "[", "i", "+", "1", "]", ".", "startswith", "(", "\" \"", ")", ":", "return", "match", ".", "group", "(", "1", ")", "else", ":", "return", "None", "while", "i", "<", "len", "(", "lines", ")", ":", "l", "=", "lines", "[", "i", "]", "section_header", "=", "_at_start_of_section", "(", ")", "if", "section_header", ":", "if", "i", "==", "0", "or", "lines", "[", "i", "-", "1", "]", ":", "print", "(", "\"\"", ",", "file", "=", "f", ")", "# Use at least H4 to keep these out of the TOC.", "print", "(", "\"##### \"", "+", "section_header", "+", "\":\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "i", "+=", "1", "outputting_list", "=", "False", "while", "i", "<", "len", "(", "lines", ")", ":", "l", "=", "lines", "[", "i", "]", "# A new section header terminates the section.", "if", "_at_start_of_section", "(", ")", ":", "break", "match", "=", "_arg_re", ".", "match", "(", "l", ")", "if", "match", ":", "if", "not", "outputting_list", ":", "# We need to start a list. In Markdown, a blank line needs to", "# precede a list.", "print", "(", "\"\"", ",", "file", "=", "f", ")", "outputting_list", "=", "True", "suffix", "=", "l", "[", "len", "(", "match", ".", "group", "(", ")", ")", ":", "]", ".", "lstrip", "(", ")", "print", "(", "\"* <b>`\"", "+", "match", ".", "group", "(", "1", ")", "+", "\"`</b>: \"", "+", "suffix", ",", "file", "=", "f", ")", "else", ":", "# For lines that don't start with _arg_re, continue the list if it", "# has enough indentation.", "outputting_list", "&=", "l", ".", "startswith", "(", "\" \"", ")", "print", "(", "l", ",", "file", "=", "f", ")", "i", "+=", "1", "else", ":", "print", "(", "l", ",", "file", "=", "f", ")", "i", "+=", "1" ]
Formats the given `docstring` as Markdown and prints it to `f`.
[ "Formats", "the", "given", "docstring", "as", "Markdown", "and", "prints", "it", "to", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L313-L364
train
tensorflow/skflow
scripts/docs/docs.py
Library._print_function
def _print_function(self, f, prefix, fullname, func): """Prints the given function to `f`.""" heading = prefix + " `" + fullname if not isinstance(func, property): heading += self._generate_signature_for_function(func) heading += "` {#%s}" % _get_anchor(self._module_to_name, fullname) print(heading, file=f) print("", file=f) self._print_formatted_docstring(inspect.getdoc(func), f) print("", file=f)
python
def _print_function(self, f, prefix, fullname, func): """Prints the given function to `f`.""" heading = prefix + " `" + fullname if not isinstance(func, property): heading += self._generate_signature_for_function(func) heading += "` {#%s}" % _get_anchor(self._module_to_name, fullname) print(heading, file=f) print("", file=f) self._print_formatted_docstring(inspect.getdoc(func), f) print("", file=f)
[ "def", "_print_function", "(", "self", ",", "f", ",", "prefix", ",", "fullname", ",", "func", ")", ":", "heading", "=", "prefix", "+", "\" `\"", "+", "fullname", "if", "not", "isinstance", "(", "func", ",", "property", ")", ":", "heading", "+=", "self", ".", "_generate_signature_for_function", "(", "func", ")", "heading", "+=", "\"` {#%s}\"", "%", "_get_anchor", "(", "self", ".", "_module_to_name", ",", "fullname", ")", "print", "(", "heading", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "self", ".", "_print_formatted_docstring", "(", "inspect", ".", "getdoc", "(", "func", ")", ",", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")" ]
Prints the given function to `f`.
[ "Prints", "the", "given", "function", "to", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L366-L375
train
tensorflow/skflow
scripts/docs/docs.py
Library._write_member_markdown_to_file
def _write_member_markdown_to_file(self, f, prefix, name, member): """Print `member` to `f`.""" if (inspect.isfunction(member) or inspect.ismethod(member) or isinstance(member, property)): print("- - -", file=f) print("", file=f) self._print_function(f, prefix, name, member) print("", file=f) elif inspect.isclass(member): print("- - -", file=f) print("", file=f) print("%s `class %s` {#%s}" % (prefix, name, _get_anchor(self._module_to_name, name)), file=f) print("", file=f) self._write_class_markdown_to_file(f, name, member) print("", file=f) else: raise RuntimeError("Member %s has unknown type %s" % (name, type(member)))
python
def _write_member_markdown_to_file(self, f, prefix, name, member): """Print `member` to `f`.""" if (inspect.isfunction(member) or inspect.ismethod(member) or isinstance(member, property)): print("- - -", file=f) print("", file=f) self._print_function(f, prefix, name, member) print("", file=f) elif inspect.isclass(member): print("- - -", file=f) print("", file=f) print("%s `class %s` {#%s}" % (prefix, name, _get_anchor(self._module_to_name, name)), file=f) print("", file=f) self._write_class_markdown_to_file(f, name, member) print("", file=f) else: raise RuntimeError("Member %s has unknown type %s" % (name, type(member)))
[ "def", "_write_member_markdown_to_file", "(", "self", ",", "f", ",", "prefix", ",", "name", ",", "member", ")", ":", "if", "(", "inspect", ".", "isfunction", "(", "member", ")", "or", "inspect", ".", "ismethod", "(", "member", ")", "or", "isinstance", "(", "member", ",", "property", ")", ")", ":", "print", "(", "\"- - -\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "self", ".", "_print_function", "(", "f", ",", "prefix", ",", "name", ",", "member", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "elif", "inspect", ".", "isclass", "(", "member", ")", ":", "print", "(", "\"- - -\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "print", "(", "\"%s `class %s` {#%s}\"", "%", "(", "prefix", ",", "name", ",", "_get_anchor", "(", "self", ".", "_module_to_name", ",", "name", ")", ")", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "self", ".", "_write_class_markdown_to_file", "(", "f", ",", "name", ",", "member", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "else", ":", "raise", "RuntimeError", "(", "\"Member %s has unknown type %s\"", "%", "(", "name", ",", "type", "(", "member", ")", ")", ")" ]
Print `member` to `f`.
[ "Print", "member", "to", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L377-L395
train
tensorflow/skflow
scripts/docs/docs.py
Library._write_class_markdown_to_file
def _write_class_markdown_to_file(self, f, name, cls): """Write the class doc to `f`. Args: f: File to write to. prefix: Prefix for names. cls: class object. name: name to use. """ # Build the list of class methods to document. methods = dict(self.get_class_members(name, cls)) # Used later to check if any methods were called out in the class # docstring. num_methods = len(methods) try: self._write_docstring_markdown_to_file(f, "####", inspect.getdoc(cls), methods, {}) except ValueError as e: raise ValueError(str(e) + " in class `%s`" % cls.__name__) # If some methods were not described, describe them now if they are # defined by the class itself (not inherited). If NO methods were # described, describe all methods. # # TODO(touts): when all methods have been categorized make it an error # if some methods are not categorized. any_method_called_out = (len(methods) != num_methods) if any_method_called_out: other_methods = {n: m for n, m in methods.items() if n in cls.__dict__} if other_methods: print("\n#### Other Methods", file=f) else: other_methods = methods for name in sorted(other_methods): self._write_member_markdown_to_file(f, "####", *other_methods[name])
python
def _write_class_markdown_to_file(self, f, name, cls): """Write the class doc to `f`. Args: f: File to write to. prefix: Prefix for names. cls: class object. name: name to use. """ # Build the list of class methods to document. methods = dict(self.get_class_members(name, cls)) # Used later to check if any methods were called out in the class # docstring. num_methods = len(methods) try: self._write_docstring_markdown_to_file(f, "####", inspect.getdoc(cls), methods, {}) except ValueError as e: raise ValueError(str(e) + " in class `%s`" % cls.__name__) # If some methods were not described, describe them now if they are # defined by the class itself (not inherited). If NO methods were # described, describe all methods. # # TODO(touts): when all methods have been categorized make it an error # if some methods are not categorized. any_method_called_out = (len(methods) != num_methods) if any_method_called_out: other_methods = {n: m for n, m in methods.items() if n in cls.__dict__} if other_methods: print("\n#### Other Methods", file=f) else: other_methods = methods for name in sorted(other_methods): self._write_member_markdown_to_file(f, "####", *other_methods[name])
[ "def", "_write_class_markdown_to_file", "(", "self", ",", "f", ",", "name", ",", "cls", ")", ":", "# Build the list of class methods to document.", "methods", "=", "dict", "(", "self", ".", "get_class_members", "(", "name", ",", "cls", ")", ")", "# Used later to check if any methods were called out in the class", "# docstring.", "num_methods", "=", "len", "(", "methods", ")", "try", ":", "self", ".", "_write_docstring_markdown_to_file", "(", "f", ",", "\"####\"", ",", "inspect", ".", "getdoc", "(", "cls", ")", ",", "methods", ",", "{", "}", ")", "except", "ValueError", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", "+", "\" in class `%s`\"", "%", "cls", ".", "__name__", ")", "# If some methods were not described, describe them now if they are", "# defined by the class itself (not inherited). If NO methods were", "# described, describe all methods.", "#", "# TODO(touts): when all methods have been categorized make it an error", "# if some methods are not categorized.", "any_method_called_out", "=", "(", "len", "(", "methods", ")", "!=", "num_methods", ")", "if", "any_method_called_out", ":", "other_methods", "=", "{", "n", ":", "m", "for", "n", ",", "m", "in", "methods", ".", "items", "(", ")", "if", "n", "in", "cls", ".", "__dict__", "}", "if", "other_methods", ":", "print", "(", "\"\\n#### Other Methods\"", ",", "file", "=", "f", ")", "else", ":", "other_methods", "=", "methods", "for", "name", "in", "sorted", "(", "other_methods", ")", ":", "self", ".", "_write_member_markdown_to_file", "(", "f", ",", "\"####\"", ",", "*", "other_methods", "[", "name", "]", ")" ]
Write the class doc to `f`. Args: f: File to write to. prefix: Prefix for names. cls: class object. name: name to use.
[ "Write", "the", "class", "doc", "to", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L414-L448
train
tensorflow/skflow
scripts/docs/docs.py
Library.write_markdown_to_file
def write_markdown_to_file(self, f): """Prints this library to file `f`. Args: f: File to write to. Returns: Dictionary of documented members. """ print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) # TODO(touts): Do not insert these. Let the doc writer put them in # the module docstring explicitly. print("#", self._title, file=f) if self._prefix: print(self._prefix, file=f) print("[TOC]", file=f) print("", file=f) if self._module is not None: self._write_module_markdown_to_file(f, self._module)
python
def write_markdown_to_file(self, f): """Prints this library to file `f`. Args: f: File to write to. Returns: Dictionary of documented members. """ print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) # TODO(touts): Do not insert these. Let the doc writer put them in # the module docstring explicitly. print("#", self._title, file=f) if self._prefix: print(self._prefix, file=f) print("[TOC]", file=f) print("", file=f) if self._module is not None: self._write_module_markdown_to_file(f, self._module)
[ "def", "write_markdown_to_file", "(", "self", ",", "f", ")", ":", "print", "(", "\"---\"", ",", "file", "=", "f", ")", "print", "(", "\"---\"", ",", "file", "=", "f", ")", "print", "(", "\"<!-- This file is machine generated: DO NOT EDIT! -->\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "# TODO(touts): Do not insert these. Let the doc writer put them in", "# the module docstring explicitly.", "print", "(", "\"#\"", ",", "self", ".", "_title", ",", "file", "=", "f", ")", "if", "self", ".", "_prefix", ":", "print", "(", "self", ".", "_prefix", ",", "file", "=", "f", ")", "print", "(", "\"[TOC]\"", ",", "file", "=", "f", ")", "print", "(", "\"\"", ",", "file", "=", "f", ")", "if", "self", ".", "_module", "is", "not", "None", ":", "self", ".", "_write_module_markdown_to_file", "(", "f", ",", "self", ".", "_module", ")" ]
Prints this library to file `f`. Args: f: File to write to. Returns: Dictionary of documented members.
[ "Prints", "this", "library", "to", "file", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L455-L476
train