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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.get_draft
def get_draft(self): """ Return self if this object is a draft, otherwise return the draft copy of a published item. """ if self.is_draft: return self elif self.is_published: draft = self.publishing_draft # Previously the reverse relation could be `DraftItemBoobyTrapped` # in some cases. This should be fixed by extra monkey-patching of # the `publishing_draft` field in icekit.publishing.apps, but we # will leave this extra sanity check here just in case. if hasattr(draft, 'get_draft_payload'): draft = draft.get_draft_payload() return draft raise ValueError( # pragma: no cover "Publishable object %r is neither draft nor published" % self)
python
def get_draft(self): """ Return self if this object is a draft, otherwise return the draft copy of a published item. """ if self.is_draft: return self elif self.is_published: draft = self.publishing_draft # Previously the reverse relation could be `DraftItemBoobyTrapped` # in some cases. This should be fixed by extra monkey-patching of # the `publishing_draft` field in icekit.publishing.apps, but we # will leave this extra sanity check here just in case. if hasattr(draft, 'get_draft_payload'): draft = draft.get_draft_payload() return draft raise ValueError( # pragma: no cover "Publishable object %r is neither draft nor published" % self)
[ "def", "get_draft", "(", "self", ")", ":", "if", "self", ".", "is_draft", ":", "return", "self", "elif", "self", ".", "is_published", ":", "draft", "=", "self", ".", "publishing_draft", "# Previously the reverse relation could be `DraftItemBoobyTrapped`", "# in some c...
Return self if this object is a draft, otherwise return the draft copy of a published item.
[ "Return", "self", "if", "this", "object", "is", "a", "draft", "otherwise", "return", "the", "draft", "copy", "of", "a", "published", "item", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L143-L160
train
33,400
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.get_published
def get_published(self): """ Return self is this object is published, otherwise return the published copy of a draft item. If this object is a draft with no published copy it will return ``None``. """ if self.is_published: return self elif self.is_draft: return self.publishing_linked raise ValueError( # pragma: no cover "Publishable object %r is neither draft nor published" % self)
python
def get_published(self): """ Return self is this object is published, otherwise return the published copy of a draft item. If this object is a draft with no published copy it will return ``None``. """ if self.is_published: return self elif self.is_draft: return self.publishing_linked raise ValueError( # pragma: no cover "Publishable object %r is neither draft nor published" % self)
[ "def", "get_published", "(", "self", ")", ":", "if", "self", ".", "is_published", ":", "return", "self", "elif", "self", ".", "is_draft", ":", "return", "self", ".", "publishing_linked", "raise", "ValueError", "(", "# pragma: no cover", "\"Publishable object %r is...
Return self is this object is published, otherwise return the published copy of a draft item. If this object is a draft with no published copy it will return ``None``.
[ "Return", "self", "is", "this", "object", "is", "published", "otherwise", "return", "the", "published", "copy", "of", "a", "draft", "item", ".", "If", "this", "object", "is", "a", "draft", "with", "no", "published", "copy", "it", "will", "return", "None", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L162-L173
train
33,401
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.get_published_or_draft
def get_published_or_draft(self): """ Return the published item, if it exists, otherwise, for privileged users, return the draft version. """ if self.is_published: return self elif self.publishing_linked_id: return self.publishing_linked if is_draft_request_context(): return self.get_draft() # There is no public version, and there is no privilege to view the # draft version return None
python
def get_published_or_draft(self): """ Return the published item, if it exists, otherwise, for privileged users, return the draft version. """ if self.is_published: return self elif self.publishing_linked_id: return self.publishing_linked if is_draft_request_context(): return self.get_draft() # There is no public version, and there is no privilege to view the # draft version return None
[ "def", "get_published_or_draft", "(", "self", ")", ":", "if", "self", ".", "is_published", ":", "return", "self", "elif", "self", ".", "publishing_linked_id", ":", "return", "self", ".", "publishing_linked", "if", "is_draft_request_context", "(", ")", ":", "retu...
Return the published item, if it exists, otherwise, for privileged users, return the draft version.
[ "Return", "the", "published", "item", "if", "it", "exists", "otherwise", "for", "privileged", "users", "return", "the", "draft", "version", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L186-L199
train
33,402
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.publish
def publish(self): """ Publishes the object. The decorator `assert_draft` makes sure that you cannot publish a published object. :param self: The object to tbe published. :return: The published object. """ if self.is_draft: # If the object has previously been linked then patch the # placeholder data and remove the previously linked object. # Otherwise set the published date. if self.publishing_linked: self.patch_placeholders() # Unlink draft and published copies then delete published. # NOTE: This indirect dance is necessary to avoid # triggering unwanted MPTT tree structure updates via # `save`. type(self.publishing_linked).objects \ .filter(pk=self.publishing_linked.pk) \ .delete() # Instead of self.publishing_linked.delete() else: self.publishing_published_at = timezone.now() # Create a new object copying all fields. publish_obj = deepcopy(self) # If any fields are defined not to copy set them to None. for fld in self.publishing_publish_empty_fields + ( 'urlnode_ptr_id', 'publishing_linked_id' ): setattr(publish_obj, fld, None) # Set the state of publication to published on the object. publish_obj.publishing_is_draft = False # Update Fluent's publishing status field mechanism to correspond # to our own notion of publication, to help use work together more # easily with Fluent Pages. if isinstance(self, UrlNode): self.status = UrlNode.DRAFT publish_obj.status = UrlNode.PUBLISHED # Set the date the object should be published at. publish_obj.publishing_published_at = self.publishing_published_at # Perform per-model preparation before saving published copy publish_obj.publishing_prepare_published_copy(self) # Save the new published object as a separate instance to self. publish_obj.save() # Sanity-check that we successfully saved the published copy if not publish_obj.pk: # pragma: no cover raise PublishingException("Failed to save published copy") # As it is a new object we need to clone each of the # translatable fields, placeholders and required relations. self.clone_parler_translations(publish_obj) self.clone_fluent_placeholders_and_content_items(publish_obj) self.clone_fluent_contentitems_m2m_relationships(publish_obj) # Extra relationship-cloning smarts publish_obj.publishing_clone_relations(self) # Link the published object to the draft object. self.publishing_linked = publish_obj # Flag draft instance when it is being updated as part of a # publish action, for use in `publishing_set_update_time` self._skip_update_publishing_modified_at = True # Signal the pre-save hook for publication, save then signal # the post publish hook. publishing_signals.publishing_publish_pre_save_draft.send( sender=type(self), instance=self) # Save the draft and its new relationship with the published copy publishing_signals.publishing_publish_save_draft.send( sender=type(self), instance=self) publishing_signals.publishing_post_publish.send( sender=type(self), instance=self) return publish_obj
python
def publish(self): """ Publishes the object. The decorator `assert_draft` makes sure that you cannot publish a published object. :param self: The object to tbe published. :return: The published object. """ if self.is_draft: # If the object has previously been linked then patch the # placeholder data and remove the previously linked object. # Otherwise set the published date. if self.publishing_linked: self.patch_placeholders() # Unlink draft and published copies then delete published. # NOTE: This indirect dance is necessary to avoid # triggering unwanted MPTT tree structure updates via # `save`. type(self.publishing_linked).objects \ .filter(pk=self.publishing_linked.pk) \ .delete() # Instead of self.publishing_linked.delete() else: self.publishing_published_at = timezone.now() # Create a new object copying all fields. publish_obj = deepcopy(self) # If any fields are defined not to copy set them to None. for fld in self.publishing_publish_empty_fields + ( 'urlnode_ptr_id', 'publishing_linked_id' ): setattr(publish_obj, fld, None) # Set the state of publication to published on the object. publish_obj.publishing_is_draft = False # Update Fluent's publishing status field mechanism to correspond # to our own notion of publication, to help use work together more # easily with Fluent Pages. if isinstance(self, UrlNode): self.status = UrlNode.DRAFT publish_obj.status = UrlNode.PUBLISHED # Set the date the object should be published at. publish_obj.publishing_published_at = self.publishing_published_at # Perform per-model preparation before saving published copy publish_obj.publishing_prepare_published_copy(self) # Save the new published object as a separate instance to self. publish_obj.save() # Sanity-check that we successfully saved the published copy if not publish_obj.pk: # pragma: no cover raise PublishingException("Failed to save published copy") # As it is a new object we need to clone each of the # translatable fields, placeholders and required relations. self.clone_parler_translations(publish_obj) self.clone_fluent_placeholders_and_content_items(publish_obj) self.clone_fluent_contentitems_m2m_relationships(publish_obj) # Extra relationship-cloning smarts publish_obj.publishing_clone_relations(self) # Link the published object to the draft object. self.publishing_linked = publish_obj # Flag draft instance when it is being updated as part of a # publish action, for use in `publishing_set_update_time` self._skip_update_publishing_modified_at = True # Signal the pre-save hook for publication, save then signal # the post publish hook. publishing_signals.publishing_publish_pre_save_draft.send( sender=type(self), instance=self) # Save the draft and its new relationship with the published copy publishing_signals.publishing_publish_save_draft.send( sender=type(self), instance=self) publishing_signals.publishing_post_publish.send( sender=type(self), instance=self) return publish_obj
[ "def", "publish", "(", "self", ")", ":", "if", "self", ".", "is_draft", ":", "# If the object has previously been linked then patch the", "# placeholder data and remove the previously linked object.", "# Otherwise set the published date.", "if", "self", ".", "publishing_linked", ...
Publishes the object. The decorator `assert_draft` makes sure that you cannot publish a published object. :param self: The object to tbe published. :return: The published object.
[ "Publishes", "the", "object", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L237-L320
train
33,403
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.unpublish
def unpublish(self): """ Un-publish the current object. """ if self.is_draft and self.publishing_linked: publishing_signals.publishing_pre_unpublish.send( sender=type(self), instance=self) # Unlink draft and published copies then delete published. # NOTE: This indirect dance is necessary to avoid triggering # unwanted MPTT tree structure updates via `delete`. type(self.publishing_linked).objects \ .filter(pk=self.publishing_linked.pk) \ .delete() # Instead of self.publishing_linked.delete() # NOTE: We update and save the object *after* deleting the # published version, in case the `save()` method does some # validation that breaks when unlinked published objects exist. self.publishing_linked = None self.publishing_published_at = None # Save the draft to remove its relationship with the published copy publishing_signals.publishing_unpublish_save_draft.send( sender=type(self), instance=self) publishing_signals.publishing_post_unpublish.send( sender=type(self), instance=self)
python
def unpublish(self): """ Un-publish the current object. """ if self.is_draft and self.publishing_linked: publishing_signals.publishing_pre_unpublish.send( sender=type(self), instance=self) # Unlink draft and published copies then delete published. # NOTE: This indirect dance is necessary to avoid triggering # unwanted MPTT tree structure updates via `delete`. type(self.publishing_linked).objects \ .filter(pk=self.publishing_linked.pk) \ .delete() # Instead of self.publishing_linked.delete() # NOTE: We update and save the object *after* deleting the # published version, in case the `save()` method does some # validation that breaks when unlinked published objects exist. self.publishing_linked = None self.publishing_published_at = None # Save the draft to remove its relationship with the published copy publishing_signals.publishing_unpublish_save_draft.send( sender=type(self), instance=self) publishing_signals.publishing_post_unpublish.send( sender=type(self), instance=self)
[ "def", "unpublish", "(", "self", ")", ":", "if", "self", ".", "is_draft", "and", "self", ".", "publishing_linked", ":", "publishing_signals", ".", "publishing_pre_unpublish", ".", "send", "(", "sender", "=", "type", "(", "self", ")", ",", "instance", "=", ...
Un-publish the current object.
[ "Un", "-", "publish", "the", "current", "object", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L323-L347
train
33,404
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.publishing_prepare_published_copy
def publishing_prepare_published_copy(self, draft_obj): """ Prepare published copy of draft prior to saving it """ # We call super here, somewhat perversely, to ensure this method will # be called on publishable subclasses if implemented there. mysuper = super(PublishingModel, self) if hasattr(mysuper, 'publishing_prepare_published_copy'): mysuper.publishing_prepare_published_copy(draft_obj)
python
def publishing_prepare_published_copy(self, draft_obj): """ Prepare published copy of draft prior to saving it """ # We call super here, somewhat perversely, to ensure this method will # be called on publishable subclasses if implemented there. mysuper = super(PublishingModel, self) if hasattr(mysuper, 'publishing_prepare_published_copy'): mysuper.publishing_prepare_published_copy(draft_obj)
[ "def", "publishing_prepare_published_copy", "(", "self", ",", "draft_obj", ")", ":", "# We call super here, somewhat perversely, to ensure this method will", "# be called on publishable subclasses if implemented there.", "mysuper", "=", "super", "(", "PublishingModel", ",", "self", ...
Prepare published copy of draft prior to saving it
[ "Prepare", "published", "copy", "of", "draft", "prior", "to", "saving", "it" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L357-L363
train
33,405
ic-labs/django-icekit
icekit/publishing/models.py
PublishingModel.clone_fluent_placeholders_and_content_items
def clone_fluent_placeholders_and_content_items(self, dst_obj): """ Clone each `Placeholder` and its `ContentItem`s. :param self: The object for which the placeholders are to be cloned from. :param dst_obj: The object which the cloned placeholders are to be related. :return: None """ if not self.has_placeholder_relationships(): return for src_placeholder in Placeholder.objects.parent(self): dst_placeholder = Placeholder.objects.create_for_object( dst_obj, slot=src_placeholder.slot, role=src_placeholder.role, title=src_placeholder.title ) src_items = src_placeholder.get_content_items() src_items.copy_to_placeholder(dst_placeholder)
python
def clone_fluent_placeholders_and_content_items(self, dst_obj): """ Clone each `Placeholder` and its `ContentItem`s. :param self: The object for which the placeholders are to be cloned from. :param dst_obj: The object which the cloned placeholders are to be related. :return: None """ if not self.has_placeholder_relationships(): return for src_placeholder in Placeholder.objects.parent(self): dst_placeholder = Placeholder.objects.create_for_object( dst_obj, slot=src_placeholder.slot, role=src_placeholder.role, title=src_placeholder.title ) src_items = src_placeholder.get_content_items() src_items.copy_to_placeholder(dst_placeholder)
[ "def", "clone_fluent_placeholders_and_content_items", "(", "self", ",", "dst_obj", ")", ":", "if", "not", "self", ".", "has_placeholder_relationships", "(", ")", ":", "return", "for", "src_placeholder", "in", "Placeholder", ".", "objects", ".", "parent", "(", "sel...
Clone each `Placeholder` and its `ContentItem`s. :param self: The object for which the placeholders are to be cloned from. :param dst_obj: The object which the cloned placeholders are to be related. :return: None
[ "Clone", "each", "Placeholder", "and", "its", "ContentItem", "s", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L595-L617
train
33,406
ic-labs/django-icekit
icekit/management/commands/rebuild_page_tree.py
Command.handle_noargs
def handle_noargs(self, **options): """ By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensure the tree data structure is consistent with what was published by the user. """ is_dry_run = options.get('dry-run', False) mptt_only = options.get('mptt-only', False) slugs = {} overrides = {} # MODIFIED # This was modified to filter draft objects only. # ORIGINAL LINE -> `parents = dict(UrlNode.objects.values_list('id', 'parent_id'))` parents = dict( UrlNode.objects.filter(status=UrlNode.DRAFT).values_list('id', 'parent_id') ) # END MODIFIED self.stdout.write("Updated MPTT columns") if is_dry_run and mptt_only: # Can't really do anything return if not is_dry_run: # Fix MPTT first, that is the basis for walking through all nodes. # MODIFIED # Original line -> `UrlNode.objects.rebuild()` # The `rebuild` function works on the manager. As we need to filter the queryset first # it does not play nicely. The code for `rebuild` was brought in here and modified to # work with the current context. # Get opts from `UrlNode` rather than `self.model`. opts = UrlNode._mptt_meta # Add a queryset parameter will draft objects only. qs = UrlNode.objects._mptt_filter( qs=UrlNode.objects.filter(status=UrlNode.DRAFT), parent=None ) if opts.order_insertion_by: qs = qs.order_by(*opts.order_insertion_by) pks = qs.values_list('pk', flat=True) # Obtain the `rebuild_helper` from `UrlNode.objects` rather than `self`. rebuild_helper = UrlNode.objects._rebuild_helper idx = 0 for pk in pks: idx += 1 rebuild_helper(pk, 1, idx) # END MODIFIED self.stdout.write("Updated MPTT columns") if mptt_only: return self.stdout.write("Updating cached URLs") self.stdout.write("Page tree nodes:\n\n") col_style = u"| {0:6} | {1:6} | {2:6} | {3}" header = col_style.format("Site", "Page", "Locale", "URL") sep = '-' * (len(header) + 40) self.stdout.write(sep) self.stdout.write(header) self.stdout.write(sep) # MODIFIED # Modified to add the filter for draft objects only. for translation in UrlNode_Translation.objects.filter( master__status=UrlNode.DRAFT ).select_related('master').order_by( 'master__parent_site__id', 'master__tree_id', 'master__lft', 'language_code' ): # END MODIFIED slugs.setdefault(translation.language_code, {})[translation.master_id] = translation.slug overrides.setdefault(translation.language_code, {})[translation.master_id] = translation.override_url old_url = translation._cached_url try: new_url = self._construct_url(translation.language_code, translation.master_id, parents, slugs, overrides) except KeyError: if is_dry_run: # When the mptt tree is broken, some URLs can't be correctly generated yet. self.stderr.write("Failed to determine new URL for {0}, please run with --mptt-only first.".format(old_url)) return raise if old_url != new_url: translation._cached_url = new_url if not is_dry_run: translation.save() if old_url != new_url: self.stdout.write(smart_text(u"{0} {1} {2}\n".format( col_style.format(translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url), "WILL CHANGE from" if is_dry_run else "UPDATED from", old_url ))) else: self.stdout.write(smart_text(col_style.format( translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url )))
python
def handle_noargs(self, **options): """ By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensure the tree data structure is consistent with what was published by the user. """ is_dry_run = options.get('dry-run', False) mptt_only = options.get('mptt-only', False) slugs = {} overrides = {} # MODIFIED # This was modified to filter draft objects only. # ORIGINAL LINE -> `parents = dict(UrlNode.objects.values_list('id', 'parent_id'))` parents = dict( UrlNode.objects.filter(status=UrlNode.DRAFT).values_list('id', 'parent_id') ) # END MODIFIED self.stdout.write("Updated MPTT columns") if is_dry_run and mptt_only: # Can't really do anything return if not is_dry_run: # Fix MPTT first, that is the basis for walking through all nodes. # MODIFIED # Original line -> `UrlNode.objects.rebuild()` # The `rebuild` function works on the manager. As we need to filter the queryset first # it does not play nicely. The code for `rebuild` was brought in here and modified to # work with the current context. # Get opts from `UrlNode` rather than `self.model`. opts = UrlNode._mptt_meta # Add a queryset parameter will draft objects only. qs = UrlNode.objects._mptt_filter( qs=UrlNode.objects.filter(status=UrlNode.DRAFT), parent=None ) if opts.order_insertion_by: qs = qs.order_by(*opts.order_insertion_by) pks = qs.values_list('pk', flat=True) # Obtain the `rebuild_helper` from `UrlNode.objects` rather than `self`. rebuild_helper = UrlNode.objects._rebuild_helper idx = 0 for pk in pks: idx += 1 rebuild_helper(pk, 1, idx) # END MODIFIED self.stdout.write("Updated MPTT columns") if mptt_only: return self.stdout.write("Updating cached URLs") self.stdout.write("Page tree nodes:\n\n") col_style = u"| {0:6} | {1:6} | {2:6} | {3}" header = col_style.format("Site", "Page", "Locale", "URL") sep = '-' * (len(header) + 40) self.stdout.write(sep) self.stdout.write(header) self.stdout.write(sep) # MODIFIED # Modified to add the filter for draft objects only. for translation in UrlNode_Translation.objects.filter( master__status=UrlNode.DRAFT ).select_related('master').order_by( 'master__parent_site__id', 'master__tree_id', 'master__lft', 'language_code' ): # END MODIFIED slugs.setdefault(translation.language_code, {})[translation.master_id] = translation.slug overrides.setdefault(translation.language_code, {})[translation.master_id] = translation.override_url old_url = translation._cached_url try: new_url = self._construct_url(translation.language_code, translation.master_id, parents, slugs, overrides) except KeyError: if is_dry_run: # When the mptt tree is broken, some URLs can't be correctly generated yet. self.stderr.write("Failed to determine new URL for {0}, please run with --mptt-only first.".format(old_url)) return raise if old_url != new_url: translation._cached_url = new_url if not is_dry_run: translation.save() if old_url != new_url: self.stdout.write(smart_text(u"{0} {1} {2}\n".format( col_style.format(translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url), "WILL CHANGE from" if is_dry_run else "UPDATED from", old_url ))) else: self.stdout.write(smart_text(col_style.format( translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url )))
[ "def", "handle_noargs", "(", "self", ",", "*", "*", "options", ")", ":", "is_dry_run", "=", "options", ".", "get", "(", "'dry-run'", ",", "False", ")", "mptt_only", "=", "options", ".", "get", "(", "'mptt-only'", ",", "False", ")", "slugs", "=", "{", ...
By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensure the tree data structure is consistent with what was published by the user.
[ "By", "default", "this", "function", "runs", "on", "all", "objects", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/management/commands/rebuild_page_tree.py#L26-L133
train
33,407
ic-labs/django-icekit
icekit/utils/search/search_indexes.py
AbstractLayoutIndex.full_prepare
def full_prepare(self, obj): """ Make django_ct equal to the type of get_model, to make polymorphic children show up in results. """ prepared_data = super(AbstractLayoutIndex, self).full_prepare(obj) prepared_data['django_ct'] = get_model_ct(self.get_model()) return prepared_data
python
def full_prepare(self, obj): """ Make django_ct equal to the type of get_model, to make polymorphic children show up in results. """ prepared_data = super(AbstractLayoutIndex, self).full_prepare(obj) prepared_data['django_ct'] = get_model_ct(self.get_model()) return prepared_data
[ "def", "full_prepare", "(", "self", ",", "obj", ")", ":", "prepared_data", "=", "super", "(", "AbstractLayoutIndex", ",", "self", ")", ".", "full_prepare", "(", "obj", ")", "prepared_data", "[", "'django_ct'", "]", "=", "get_model_ct", "(", "self", ".", "g...
Make django_ct equal to the type of get_model, to make polymorphic children show up in results.
[ "Make", "django_ct", "equal", "to", "the", "type", "of", "get_model", "to", "make", "polymorphic", "children", "show", "up", "in", "results", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/search_indexes.py#L53-L60
train
33,408
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
grammatical_join
def grammatical_join(l, initial_joins=", ", final_join=" and "): """ Display a list of items nicely, with a different string before the final item. Useful for using lists in sentences. >>> grammatical_join(['apples', 'pears', 'bananas']) 'apples, pears and bananas' >>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=";", final_join="; or ") 'apples; pears; or bananas' :param l: List of strings to join :param initial_joins: the string to join the non-ultimate items with :param final_join: the string to join the final item with :return: items joined with commas except " and " before the final one. """ # http://stackoverflow.com/questions/19838976/grammatical-list-join-in-python return initial_joins.join(l[:-2] + [final_join.join(l[-2:])])
python
def grammatical_join(l, initial_joins=", ", final_join=" and "): """ Display a list of items nicely, with a different string before the final item. Useful for using lists in sentences. >>> grammatical_join(['apples', 'pears', 'bananas']) 'apples, pears and bananas' >>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=";", final_join="; or ") 'apples; pears; or bananas' :param l: List of strings to join :param initial_joins: the string to join the non-ultimate items with :param final_join: the string to join the final item with :return: items joined with commas except " and " before the final one. """ # http://stackoverflow.com/questions/19838976/grammatical-list-join-in-python return initial_joins.join(l[:-2] + [final_join.join(l[-2:])])
[ "def", "grammatical_join", "(", "l", ",", "initial_joins", "=", "\", \"", ",", "final_join", "=", "\" and \"", ")", ":", "# http://stackoverflow.com/questions/19838976/grammatical-list-join-in-python", "return", "initial_joins", ".", "join", "(", "l", "[", ":", "-", "...
Display a list of items nicely, with a different string before the final item. Useful for using lists in sentences. >>> grammatical_join(['apples', 'pears', 'bananas']) 'apples, pears and bananas' >>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=";", final_join="; or ") 'apples; pears; or bananas' :param l: List of strings to join :param initial_joins: the string to join the non-ultimate items with :param final_join: the string to join the final item with :return: items joined with commas except " and " before the final one.
[ "Display", "a", "list", "of", "items", "nicely", "with", "a", "different", "string", "before", "the", "final", "item", ".", "Useful", "for", "using", "lists", "in", "sentences", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L64-L81
train
33,409
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
update_GET
def update_GET(parser, token): """ ``update_GET`` allows you to substitute parameters into the current request's GET parameters. This is useful for updating search filters, page numbers, without losing the current set. For example, the template fragment:: <a href="?{% update_GET 'attr1' += value1 'attr2' -= value2 'attr3' = value3 %}">foo</a> - adds ``value1`` to (the list of values in) ``'attr1'``, - removes ``value2`` from (the list of values in) ``'attr2'``, - sets ``attr3`` to ``value3``. and returns a urlencoded GET string. Allowed attributes are: - strings, in quotes - vars that resolve to strings Allowed values are: - strings, in quotes - vars that resolve to strings - lists of strings - None (without quotes) Note: - If a attribute is set to ``None`` or an empty list, the GET parameter is removed. - If an attribute's value is an empty string, or ``[""]`` or ``None``, the value remains, but has a ``""`` value. - If you try to ``=-`` a value from a list that doesn't contain that value, nothing happens. - If you try to ``=-`` a value from a list where the value appears more than once, only the first value is removed. """ try: args = token.split_contents()[1:] triples = list(_chunks(args, 3)) if triples and len(triples[-1]) != 3: raise template.TemplateSyntaxError, "%r tag requires arguments in groups of three (op, attr, value)." % token.contents.split()[0] ops = set([t[1] for t in triples]) if not ops <= set(['+=', '-=', '=']): raise template.TemplateSyntaxError, "The only allowed operators are '+=', '-=' and '='. You have used %s" % ", ".join(ops) except ValueError: return UpdateGetNode() return UpdateGetNode(triples)
python
def update_GET(parser, token): """ ``update_GET`` allows you to substitute parameters into the current request's GET parameters. This is useful for updating search filters, page numbers, without losing the current set. For example, the template fragment:: <a href="?{% update_GET 'attr1' += value1 'attr2' -= value2 'attr3' = value3 %}">foo</a> - adds ``value1`` to (the list of values in) ``'attr1'``, - removes ``value2`` from (the list of values in) ``'attr2'``, - sets ``attr3`` to ``value3``. and returns a urlencoded GET string. Allowed attributes are: - strings, in quotes - vars that resolve to strings Allowed values are: - strings, in quotes - vars that resolve to strings - lists of strings - None (without quotes) Note: - If a attribute is set to ``None`` or an empty list, the GET parameter is removed. - If an attribute's value is an empty string, or ``[""]`` or ``None``, the value remains, but has a ``""`` value. - If you try to ``=-`` a value from a list that doesn't contain that value, nothing happens. - If you try to ``=-`` a value from a list where the value appears more than once, only the first value is removed. """ try: args = token.split_contents()[1:] triples = list(_chunks(args, 3)) if triples and len(triples[-1]) != 3: raise template.TemplateSyntaxError, "%r tag requires arguments in groups of three (op, attr, value)." % token.contents.split()[0] ops = set([t[1] for t in triples]) if not ops <= set(['+=', '-=', '=']): raise template.TemplateSyntaxError, "The only allowed operators are '+=', '-=' and '='. You have used %s" % ", ".join(ops) except ValueError: return UpdateGetNode() return UpdateGetNode(triples)
[ "def", "update_GET", "(", "parser", ",", "token", ")", ":", "try", ":", "args", "=", "token", ".", "split_contents", "(", ")", "[", "1", ":", "]", "triples", "=", "list", "(", "_chunks", "(", "args", ",", "3", ")", ")", "if", "triples", "and", "l...
``update_GET`` allows you to substitute parameters into the current request's GET parameters. This is useful for updating search filters, page numbers, without losing the current set. For example, the template fragment:: <a href="?{% update_GET 'attr1' += value1 'attr2' -= value2 'attr3' = value3 %}">foo</a> - adds ``value1`` to (the list of values in) ``'attr1'``, - removes ``value2`` from (the list of values in) ``'attr2'``, - sets ``attr3`` to ``value3``. and returns a urlencoded GET string. Allowed attributes are: - strings, in quotes - vars that resolve to strings Allowed values are: - strings, in quotes - vars that resolve to strings - lists of strings - None (without quotes) Note: - If a attribute is set to ``None`` or an empty list, the GET parameter is removed. - If an attribute's value is an empty string, or ``[""]`` or ``None``, the value remains, but has a ``""`` value. - If you try to ``=-`` a value from a list that doesn't contain that value, nothing happens. - If you try to ``=-`` a value from a list where the value appears more than once, only the first value is removed.
[ "update_GET", "allows", "you", "to", "substitute", "parameters", "into", "the", "current", "request", "s", "GET", "parameters", ".", "This", "is", "useful", "for", "updating", "search", "filters", "page", "numbers", "without", "losing", "the", "current", "set", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L103-L154
train
33,410
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
oembed
def oembed(url, params=""): """ Render an OEmbed-compatible link as an embedded item. :param url: A URL of an OEmbed provider. :return: The OEMbed ``<embed>`` code. """ # Note: this method isn't currently very efficient - the data isn't # cached or stored. kwargs = dict(urlparse.parse_qsl(params)) try: return mark_safe(get_oembed_data( url, **kwargs )['html']) except (KeyError, ProviderException): if settings.DEBUG: return "No OEmbed data returned" return ""
python
def oembed(url, params=""): """ Render an OEmbed-compatible link as an embedded item. :param url: A URL of an OEmbed provider. :return: The OEMbed ``<embed>`` code. """ # Note: this method isn't currently very efficient - the data isn't # cached or stored. kwargs = dict(urlparse.parse_qsl(params)) try: return mark_safe(get_oembed_data( url, **kwargs )['html']) except (KeyError, ProviderException): if settings.DEBUG: return "No OEmbed data returned" return ""
[ "def", "oembed", "(", "url", ",", "params", "=", "\"\"", ")", ":", "# Note: this method isn't currently very efficient - the data isn't", "# cached or stored.", "kwargs", "=", "dict", "(", "urlparse", ".", "parse_qsl", "(", "params", ")", ")", "try", ":", "return", ...
Render an OEmbed-compatible link as an embedded item. :param url: A URL of an OEmbed provider. :return: The OEMbed ``<embed>`` code.
[ "Render", "an", "OEmbed", "-", "compatible", "link", "as", "an", "embedded", "item", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L226-L246
train
33,411
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
admin_link
def admin_link(obj): """ Returns a link to the admin URL of an object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_link }} renders as:: <a href='/admin/foo/123'>Foo</a> :param obj: A Django model instance. :return: A safe string expressing an HTML link to the admin page for an object. """ if hasattr(obj, 'get_admin_link'): return mark_safe(obj.get_admin_link()) return mark_safe(admin_link_fn(obj))
python
def admin_link(obj): """ Returns a link to the admin URL of an object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_link }} renders as:: <a href='/admin/foo/123'>Foo</a> :param obj: A Django model instance. :return: A safe string expressing an HTML link to the admin page for an object. """ if hasattr(obj, 'get_admin_link'): return mark_safe(obj.get_admin_link()) return mark_safe(admin_link_fn(obj))
[ "def", "admin_link", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'get_admin_link'", ")", ":", "return", "mark_safe", "(", "obj", ".", "get_admin_link", "(", ")", ")", "return", "mark_safe", "(", "admin_link_fn", "(", "obj", ")", ")" ]
Returns a link to the admin URL of an object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_link }} renders as:: <a href='/admin/foo/123'>Foo</a> :param obj: A Django model instance. :return: A safe string expressing an HTML link to the admin page for an object.
[ "Returns", "a", "link", "to", "the", "admin", "URL", "of", "an", "object", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L250-L271
train
33,412
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
admin_url
def admin_url(obj): """ Returns the admin URL of the object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_url }} renders as:: /admin/foo/123 :param obj: A Django model instance. :return: the admin URL of the object """ if hasattr(obj, 'get_admin_url'): return mark_safe(obj.get_admin_url()) return mark_safe(admin_url_fn(obj))
python
def admin_url(obj): """ Returns the admin URL of the object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_url }} renders as:: /admin/foo/123 :param obj: A Django model instance. :return: the admin URL of the object """ if hasattr(obj, 'get_admin_url'): return mark_safe(obj.get_admin_url()) return mark_safe(admin_url_fn(obj))
[ "def", "admin_url", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'get_admin_url'", ")", ":", "return", "mark_safe", "(", "obj", ".", "get_admin_url", "(", ")", ")", "return", "mark_safe", "(", "admin_url_fn", "(", "obj", ")", ")" ]
Returns the admin URL of the object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_url }} renders as:: /admin/foo/123 :param obj: A Django model instance. :return: the admin URL of the object
[ "Returns", "the", "admin", "URL", "of", "the", "object", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L275-L295
train
33,413
ic-labs/django-icekit
icekit/templatetags/icekit_tags.py
sharedcontent_exists
def sharedcontent_exists(slug): """ Return `True` if shared content with the given slug name exists. This filter makes it possible to conditionally include shared content with surrounding markup only when the shared content item actually exits, and avoid outputting the surrounding markup when it doesn't. Example usage: {% load icekit_tags sharedcontent_tags %} {% if "shared-content-slug"|sharedcontent_exists %} <div class="surrounding-html"> {% sharedcontent "shared-content-slug" %} </div> {% endif %} """ from django.contrib.sites.models import Site from fluent_contents.plugins.sharedcontent.models import SharedContent site = Site.objects.get_current() return SharedContent.objects.parent_site(site).filter(slug=slug).exists()
python
def sharedcontent_exists(slug): """ Return `True` if shared content with the given slug name exists. This filter makes it possible to conditionally include shared content with surrounding markup only when the shared content item actually exits, and avoid outputting the surrounding markup when it doesn't. Example usage: {% load icekit_tags sharedcontent_tags %} {% if "shared-content-slug"|sharedcontent_exists %} <div class="surrounding-html"> {% sharedcontent "shared-content-slug" %} </div> {% endif %} """ from django.contrib.sites.models import Site from fluent_contents.plugins.sharedcontent.models import SharedContent site = Site.objects.get_current() return SharedContent.objects.parent_site(site).filter(slug=slug).exists()
[ "def", "sharedcontent_exists", "(", "slug", ")", ":", "from", "django", ".", "contrib", ".", "sites", ".", "models", "import", "Site", "from", "fluent_contents", ".", "plugins", ".", "sharedcontent", ".", "models", "import", "SharedContent", "site", "=", "Site...
Return `True` if shared content with the given slug name exists. This filter makes it possible to conditionally include shared content with surrounding markup only when the shared content item actually exits, and avoid outputting the surrounding markup when it doesn't. Example usage: {% load icekit_tags sharedcontent_tags %} {% if "shared-content-slug"|sharedcontent_exists %} <div class="surrounding-html"> {% sharedcontent "shared-content-slug" %} </div> {% endif %}
[ "Return", "True", "if", "shared", "content", "with", "the", "given", "slug", "name", "exists", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L342-L363
train
33,414
ic-labs/django-icekit
icekit/admin_tools/previews.py
RawIdPreviewAdminMixin.render_field_error
def render_field_error(self, obj_id, obj, exception, request): """ Default rendering for items in field where the the usual rendering method raised an exception. """ if obj is None: msg = 'No match for ID={0}'.format(obj_id) else: msg = unicode(exception) return u'<p class="error">{0}</p>'.format(msg)
python
def render_field_error(self, obj_id, obj, exception, request): """ Default rendering for items in field where the the usual rendering method raised an exception. """ if obj is None: msg = 'No match for ID={0}'.format(obj_id) else: msg = unicode(exception) return u'<p class="error">{0}</p>'.format(msg)
[ "def", "render_field_error", "(", "self", ",", "obj_id", ",", "obj", ",", "exception", ",", "request", ")", ":", "if", "obj", "is", "None", ":", "msg", "=", "'No match for ID={0}'", ".", "format", "(", "obj_id", ")", "else", ":", "msg", "=", "unicode", ...
Default rendering for items in field where the the usual rendering method raised an exception.
[ "Default", "rendering", "for", "items", "in", "field", "where", "the", "the", "usual", "rendering", "method", "raised", "an", "exception", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/previews.py#L65-L74
train
33,415
ic-labs/django-icekit
icekit/admin_tools/previews.py
RawIdPreviewAdminMixin.render_field_previews
def render_field_previews(self, id_and_obj_list, admin, request, field_name): """ Override this to customise the preview representation of all objects. """ obj_preview_list = [] for obj_id, obj in id_and_obj_list: try: # Handle invalid IDs if obj is None: obj_preview = self.render_field_error( obj_id, obj, None, request ) else: try: obj_preview = admin.preview(obj, request) except AttributeError: try: obj_preview = obj.preview(request) except AttributeError: try: obj_preview = getattr(self, 'preview_{0}'.format( field_name))(obj, request) except AttributeError: # Fall back to default field rendering obj_preview = self.render_field_default(obj, request) obj_link = admin_link(obj, inner_html=obj_preview) except Exception as ex: obj_link = self.render_field_error(obj_id, obj, ex, request) obj_preview_list.append(obj_link) li_html_list = [u'<li>{0}</li>'.format(preview) for preview in obj_preview_list] if li_html_list: return u'<ul>{0}</ul>'.format(u''.join(li_html_list)) else: return ''
python
def render_field_previews(self, id_and_obj_list, admin, request, field_name): """ Override this to customise the preview representation of all objects. """ obj_preview_list = [] for obj_id, obj in id_and_obj_list: try: # Handle invalid IDs if obj is None: obj_preview = self.render_field_error( obj_id, obj, None, request ) else: try: obj_preview = admin.preview(obj, request) except AttributeError: try: obj_preview = obj.preview(request) except AttributeError: try: obj_preview = getattr(self, 'preview_{0}'.format( field_name))(obj, request) except AttributeError: # Fall back to default field rendering obj_preview = self.render_field_default(obj, request) obj_link = admin_link(obj, inner_html=obj_preview) except Exception as ex: obj_link = self.render_field_error(obj_id, obj, ex, request) obj_preview_list.append(obj_link) li_html_list = [u'<li>{0}</li>'.format(preview) for preview in obj_preview_list] if li_html_list: return u'<ul>{0}</ul>'.format(u''.join(li_html_list)) else: return ''
[ "def", "render_field_previews", "(", "self", ",", "id_and_obj_list", ",", "admin", ",", "request", ",", "field_name", ")", ":", "obj_preview_list", "=", "[", "]", "for", "obj_id", ",", "obj", "in", "id_and_obj_list", ":", "try", ":", "# Handle invalid IDs", "i...
Override this to customise the preview representation of all objects.
[ "Override", "this", "to", "customise", "the", "preview", "representation", "of", "all", "objects", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/previews.py#L76-L111
train
33,416
ic-labs/django-icekit
icekit/plugins/links/abstract_models.py
AbstractLinkItem.get_item
def get_item(self): "If the item is publishable, get the visible version" if hasattr(self, 'get_draft'): draft = self.get_draft() else: draft = self if not hasattr(self, '_item_cache'): try: self._item_cache = draft.item.get_published_or_draft() except AttributeError: # not publishable self._item_cache = draft.item return self._item_cache
python
def get_item(self): "If the item is publishable, get the visible version" if hasattr(self, 'get_draft'): draft = self.get_draft() else: draft = self if not hasattr(self, '_item_cache'): try: self._item_cache = draft.item.get_published_or_draft() except AttributeError: # not publishable self._item_cache = draft.item return self._item_cache
[ "def", "get_item", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'get_draft'", ")", ":", "draft", "=", "self", ".", "get_draft", "(", ")", "else", ":", "draft", "=", "self", "if", "not", "hasattr", "(", "self", ",", "'_item_cache'", ")",...
If the item is publishable, get the visible version
[ "If", "the", "item", "is", "publishable", "get", "the", "visible", "version" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/links/abstract_models.py#L39-L53
train
33,417
ic-labs/django-icekit
icekit/plugins/links/abstract_models.py
LinkPlugin.render
def render(self, request, instance, **kwargs): """ Only render the plugin if the item can be shown to the user """ if instance.get_item(): return super(LinkPlugin, self).render(request, instance, **kwargs) return ""
python
def render(self, request, instance, **kwargs): """ Only render the plugin if the item can be shown to the user """ if instance.get_item(): return super(LinkPlugin, self).render(request, instance, **kwargs) return ""
[ "def", "render", "(", "self", ",", "request", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "get_item", "(", ")", ":", "return", "super", "(", "LinkPlugin", ",", "self", ")", ".", "render", "(", "request", ",", "instance"...
Only render the plugin if the item can be shown to the user
[ "Only", "render", "the", "plugin", "if", "the", "item", "can", "be", "shown", "to", "the", "user" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/links/abstract_models.py#L109-L115
train
33,418
ic-labs/django-icekit
icekit/api/base_serializers.py
ModelSubSerializer.get_fields
def get_fields(self): """ Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute. """ prefix = getattr(self.Meta, 'source_prefix', '') fields = super(ModelSubSerializer, self).get_fields() fields_without_prefix = OrderedDict() for field_name, field in fields.items(): if field_name.startswith(prefix): # Set real model field name as field's `source` unless the # source is already explicitly set, in which case it is # probably a method name not the direct field name if not field.source: field.source = field_name field_name = field_name[len(prefix):] fields_without_prefix[field_name] = field return fields_without_prefix
python
def get_fields(self): """ Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute. """ prefix = getattr(self.Meta, 'source_prefix', '') fields = super(ModelSubSerializer, self).get_fields() fields_without_prefix = OrderedDict() for field_name, field in fields.items(): if field_name.startswith(prefix): # Set real model field name as field's `source` unless the # source is already explicitly set, in which case it is # probably a method name not the direct field name if not field.source: field.source = field_name field_name = field_name[len(prefix):] fields_without_prefix[field_name] = field return fields_without_prefix
[ "def", "get_fields", "(", "self", ")", ":", "prefix", "=", "getattr", "(", "self", ".", "Meta", ",", "'source_prefix'", ",", "''", ")", "fields", "=", "super", "(", "ModelSubSerializer", ",", "self", ")", ".", "get_fields", "(", ")", "fields_without_prefix...
Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute.
[ "Convert", "default", "field", "names", "for", "this", "sub", "-", "serializer", "into", "versions", "where", "the", "field", "name", "has", "the", "prefix", "removed", "but", "each", "field", "object", "knows", "the", "real", "model", "field", "name", "by",...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L51-L69
train
33,419
ic-labs/django-icekit
icekit/api/base_serializers.py
WritableSerializerHelperMixin._populate_validated_data_with_sub_field_data
def _populate_validated_data_with_sub_field_data(self, validated_data): """ Move field data nested in `ModelSubSerializer` fields back into the overall validated data dict. """ for fieldname, field in self.get_fields().items(): if isinstance(field, ModelSubSerializer): field_data = validated_data.pop(fieldname, None) if field_data: validated_data.update(field_data)
python
def _populate_validated_data_with_sub_field_data(self, validated_data): """ Move field data nested in `ModelSubSerializer` fields back into the overall validated data dict. """ for fieldname, field in self.get_fields().items(): if isinstance(field, ModelSubSerializer): field_data = validated_data.pop(fieldname, None) if field_data: validated_data.update(field_data)
[ "def", "_populate_validated_data_with_sub_field_data", "(", "self", ",", "validated_data", ")", ":", "for", "fieldname", ",", "field", "in", "self", ".", "get_fields", "(", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "field", ",", "ModelSubSeria...
Move field data nested in `ModelSubSerializer` fields back into the overall validated data dict.
[ "Move", "field", "data", "nested", "in", "ModelSubSerializer", "fields", "back", "into", "the", "overall", "validated", "data", "dict", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L123-L132
train
33,420
ic-labs/django-icekit
icekit/api/base_serializers.py
WritableSerializerHelperMixin._prepare_related_single_or_m2m_relations
def _prepare_related_single_or_m2m_relations(self, validated_data): """ Handle writing to nested related model fields for both single and many-to-many relationships. For single relationships, any existing or new instance resulting from the provided data is set back into the provided `validated_data` to be applied by DjangoRestFramework's default handling. For M2M relationships, any existing or new instances resulting from the provided data are returned in a dictionary mapping M2M field names to a list of instances to be related. The actual relationship is then applied by `_write_related_m2m_relations` because DjangoRestFramework does not support assigning M2M fields. """ many_to_many_relationships = {} for fieldname, field in self.get_fields().items(): if ( # `ModelSubSerializer` is handled separately isinstance(field, ModelSubSerializer) or # Skip read-only fields, obviously field.read_only or # Only list or model serializers are supported not ( isinstance(field, serializers.ModelSerializer) or isinstance(field, serializers.ListSerializer) ) ): continue # Skip field is_list_field = isinstance(field, serializers.ListSerializer) if is_list_field: ModelClass = field.child.Meta.model field_data_list = validated_data.pop(fieldname, []) else: ModelClass = field.Meta.model field_data_list = validated_data.pop(fieldname, None) field_data_list = field_data_list and [field_data_list] or [] # Skip field if no data was provided if not field_data_list: continue related_instances = [] for field_data in field_data_list: related_instance = \ self._get_or_update_or_create_related_instance( ModelClass, fieldname, field_data) if related_instance: related_instances.append(related_instance) # Add related model instance as validated data parameter for # later create/update operation on parent instance. if not is_list_field: validated_data[fieldname] = related_instances[0] # Many-to-many relationships must be handled after super's `create` # or `update` method, not here. So we just return the list for now else: many_to_many_relationships[fieldname] = related_instances return many_to_many_relationships
python
def _prepare_related_single_or_m2m_relations(self, validated_data): """ Handle writing to nested related model fields for both single and many-to-many relationships. For single relationships, any existing or new instance resulting from the provided data is set back into the provided `validated_data` to be applied by DjangoRestFramework's default handling. For M2M relationships, any existing or new instances resulting from the provided data are returned in a dictionary mapping M2M field names to a list of instances to be related. The actual relationship is then applied by `_write_related_m2m_relations` because DjangoRestFramework does not support assigning M2M fields. """ many_to_many_relationships = {} for fieldname, field in self.get_fields().items(): if ( # `ModelSubSerializer` is handled separately isinstance(field, ModelSubSerializer) or # Skip read-only fields, obviously field.read_only or # Only list or model serializers are supported not ( isinstance(field, serializers.ModelSerializer) or isinstance(field, serializers.ListSerializer) ) ): continue # Skip field is_list_field = isinstance(field, serializers.ListSerializer) if is_list_field: ModelClass = field.child.Meta.model field_data_list = validated_data.pop(fieldname, []) else: ModelClass = field.Meta.model field_data_list = validated_data.pop(fieldname, None) field_data_list = field_data_list and [field_data_list] or [] # Skip field if no data was provided if not field_data_list: continue related_instances = [] for field_data in field_data_list: related_instance = \ self._get_or_update_or_create_related_instance( ModelClass, fieldname, field_data) if related_instance: related_instances.append(related_instance) # Add related model instance as validated data parameter for # later create/update operation on parent instance. if not is_list_field: validated_data[fieldname] = related_instances[0] # Many-to-many relationships must be handled after super's `create` # or `update` method, not here. So we just return the list for now else: many_to_many_relationships[fieldname] = related_instances return many_to_many_relationships
[ "def", "_prepare_related_single_or_m2m_relations", "(", "self", ",", "validated_data", ")", ":", "many_to_many_relationships", "=", "{", "}", "for", "fieldname", ",", "field", "in", "self", ".", "get_fields", "(", ")", ".", "items", "(", ")", ":", "if", "(", ...
Handle writing to nested related model fields for both single and many-to-many relationships. For single relationships, any existing or new instance resulting from the provided data is set back into the provided `validated_data` to be applied by DjangoRestFramework's default handling. For M2M relationships, any existing or new instances resulting from the provided data are returned in a dictionary mapping M2M field names to a list of instances to be related. The actual relationship is then applied by `_write_related_m2m_relations` because DjangoRestFramework does not support assigning M2M fields.
[ "Handle", "writing", "to", "nested", "related", "model", "fields", "for", "both", "single", "and", "many", "-", "to", "-", "many", "relationships", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L134-L194
train
33,421
ic-labs/django-icekit
icekit/api/base_serializers.py
WritableSerializerHelperMixin._get_or_update_or_create_related_instance
def _get_or_update_or_create_related_instance( self, ModelClass, fieldname, field_data ): """ Handle lookup, update, or creation of related instances based on the field data provided and the field's `writable_related_fields` settings as defined on the serializer's `Meta`. This method will: - fail immediately if the field does not have `writable_related_fields` settings defined, or if these settings are not valid `WritableRelatedFieldSettings` objects - look up an existing instance using the defined `lookup_field` if a value is provided for the lookup field: - if no lookup field value is provided, fail unless `can_create` is set on the field since we cannot find any existing instance - if no existing instance is found, fail unless `can_create` - find the matching existing instance - if there is an existing instance: - if other data is provided, fail unless `can_update` is set - update existing instance based on other data provided if `can_update is set` - return the existing instance - if there is not an existing instance and `can_create` is set: - create a new instance with provided data - return the new instance """ writable_related_fields = getattr( self.Meta, 'writable_related_fields', {}) # Get settings for writable related field if fieldname not in writable_related_fields: raise TypeError( "Cannot write related model field '%s' for %s on %s" " without corresponding 'writable_related_fields' settings" " in the Meta class" % (fieldname, ModelClass.__name__, self.Meta.model.__name__) ) field_settings = writable_related_fields[fieldname] if not isinstance(field_settings, WritableRelatedFieldSettings): raise TypeError( "Settings for related model field '%s' in" " '%s.Meta.writable_related_fields' must be of type" " 'WritableRelatedFieldSettings': %s" % (fieldname, ModelClass.__name__, type(field_settings)) ) # Get settings for lookup field; may be a string or a strings list lookup_fields = field_settings.lookup_field if not isinstance(lookup_fields, (list, tuple)): lookup_fields = [lookup_fields] # We use the first of potentially multiple lookup field values for # which we have been given field data. lookup_value = None for lookup_field in lookup_fields: if lookup_field in field_data: lookup_value = field_data.pop(lookup_field) break # Fail if we have no lookup value and we cannot create an instance if lookup_value is None and not field_settings.can_create: raise TypeError( "Cannot look up related model field '%s' for %s on %s" " using the lookup field(s) %r because no value" " was provided for the lookup field(s) in %s" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, lookup_fields, field_data) ) related_instance = None # Fetch existing instance using lookup field try: related_instance = ModelClass.objects.get( **{lookup_field: lookup_value}) # Update existing related instance with values provided in # parent's create/update operation, if such updates are # permitted. If updates are not permitted, raise an exception # only if submitted values differ from existing ones. is_updated = False for name, value in field_data.items(): original_value = getattr(related_instance, name) if value != original_value: if not field_settings.can_update: raise TypeError( u"Cannot update instance for related model" u" field '%s' for %s on %s because" u" 'can_update' is not set for this field in" u" 'writable_related_fields' but submitted" u" value `%s=%s` does not match existing" u" instance value `%s`" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, name, value, original_value) ) setattr(related_instance, name, value) is_updated = True if is_updated: related_instance.save() except ModelClass.MultipleObjectsReturned, ex: raise TypeError( "Cannot look up related model field '%s' for %s on %s" " using '%s' as the lookup field because it returns" " multiple results for value '%s': %s" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, lookup_field, lookup_value, ex) ) # If a related instance does not yet exist, optionally create one except ModelClass.DoesNotExist: if not field_settings.can_create: raise TypeError( "Cannot create instance for related model field '%s'" " for %s on %s because 'can_create' is not set for" " this field in 'writable_related_fields'" % (fieldname, ModelClass.__name__, self.Meta.model.__name__) ) field_data.update({lookup_field: lookup_value}) related_instance = ModelClass.objects.create(**field_data) return related_instance
python
def _get_or_update_or_create_related_instance( self, ModelClass, fieldname, field_data ): """ Handle lookup, update, or creation of related instances based on the field data provided and the field's `writable_related_fields` settings as defined on the serializer's `Meta`. This method will: - fail immediately if the field does not have `writable_related_fields` settings defined, or if these settings are not valid `WritableRelatedFieldSettings` objects - look up an existing instance using the defined `lookup_field` if a value is provided for the lookup field: - if no lookup field value is provided, fail unless `can_create` is set on the field since we cannot find any existing instance - if no existing instance is found, fail unless `can_create` - find the matching existing instance - if there is an existing instance: - if other data is provided, fail unless `can_update` is set - update existing instance based on other data provided if `can_update is set` - return the existing instance - if there is not an existing instance and `can_create` is set: - create a new instance with provided data - return the new instance """ writable_related_fields = getattr( self.Meta, 'writable_related_fields', {}) # Get settings for writable related field if fieldname not in writable_related_fields: raise TypeError( "Cannot write related model field '%s' for %s on %s" " without corresponding 'writable_related_fields' settings" " in the Meta class" % (fieldname, ModelClass.__name__, self.Meta.model.__name__) ) field_settings = writable_related_fields[fieldname] if not isinstance(field_settings, WritableRelatedFieldSettings): raise TypeError( "Settings for related model field '%s' in" " '%s.Meta.writable_related_fields' must be of type" " 'WritableRelatedFieldSettings': %s" % (fieldname, ModelClass.__name__, type(field_settings)) ) # Get settings for lookup field; may be a string or a strings list lookup_fields = field_settings.lookup_field if not isinstance(lookup_fields, (list, tuple)): lookup_fields = [lookup_fields] # We use the first of potentially multiple lookup field values for # which we have been given field data. lookup_value = None for lookup_field in lookup_fields: if lookup_field in field_data: lookup_value = field_data.pop(lookup_field) break # Fail if we have no lookup value and we cannot create an instance if lookup_value is None and not field_settings.can_create: raise TypeError( "Cannot look up related model field '%s' for %s on %s" " using the lookup field(s) %r because no value" " was provided for the lookup field(s) in %s" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, lookup_fields, field_data) ) related_instance = None # Fetch existing instance using lookup field try: related_instance = ModelClass.objects.get( **{lookup_field: lookup_value}) # Update existing related instance with values provided in # parent's create/update operation, if such updates are # permitted. If updates are not permitted, raise an exception # only if submitted values differ from existing ones. is_updated = False for name, value in field_data.items(): original_value = getattr(related_instance, name) if value != original_value: if not field_settings.can_update: raise TypeError( u"Cannot update instance for related model" u" field '%s' for %s on %s because" u" 'can_update' is not set for this field in" u" 'writable_related_fields' but submitted" u" value `%s=%s` does not match existing" u" instance value `%s`" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, name, value, original_value) ) setattr(related_instance, name, value) is_updated = True if is_updated: related_instance.save() except ModelClass.MultipleObjectsReturned, ex: raise TypeError( "Cannot look up related model field '%s' for %s on %s" " using '%s' as the lookup field because it returns" " multiple results for value '%s': %s" % (fieldname, ModelClass.__name__, self.Meta.model.__name__, lookup_field, lookup_value, ex) ) # If a related instance does not yet exist, optionally create one except ModelClass.DoesNotExist: if not field_settings.can_create: raise TypeError( "Cannot create instance for related model field '%s'" " for %s on %s because 'can_create' is not set for" " this field in 'writable_related_fields'" % (fieldname, ModelClass.__name__, self.Meta.model.__name__) ) field_data.update({lookup_field: lookup_value}) related_instance = ModelClass.objects.create(**field_data) return related_instance
[ "def", "_get_or_update_or_create_related_instance", "(", "self", ",", "ModelClass", ",", "fieldname", ",", "field_data", ")", ":", "writable_related_fields", "=", "getattr", "(", "self", ".", "Meta", ",", "'writable_related_fields'", ",", "{", "}", ")", "# Get setti...
Handle lookup, update, or creation of related instances based on the field data provided and the field's `writable_related_fields` settings as defined on the serializer's `Meta`. This method will: - fail immediately if the field does not have `writable_related_fields` settings defined, or if these settings are not valid `WritableRelatedFieldSettings` objects - look up an existing instance using the defined `lookup_field` if a value is provided for the lookup field: - if no lookup field value is provided, fail unless `can_create` is set on the field since we cannot find any existing instance - if no existing instance is found, fail unless `can_create` - find the matching existing instance - if there is an existing instance: - if other data is provided, fail unless `can_update` is set - update existing instance based on other data provided if `can_update is set` - return the existing instance - if there is not an existing instance and `can_create` is set: - create a new instance with provided data - return the new instance
[ "Handle", "lookup", "update", "or", "creation", "of", "related", "instances", "based", "on", "the", "field", "data", "provided", "and", "the", "field", "s", "writable_related_fields", "settings", "as", "defined", "on", "the", "serializer", "s", "Meta", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L196-L327
train
33,422
ic-labs/django-icekit
icekit/api/base_serializers.py
WritableSerializerHelperMixin._write_related_m2m_relations
def _write_related_m2m_relations(self, obj, many_to_many_relationships): """ For the given `many_to_many_relationships` dict mapping field names to a list of object instances, apply the instance listing to the `obj`s named many-to-many relationship field. """ for fieldname, related_objs in many_to_many_relationships.items(): # TODO On PATCH avoid clearing existing relationships not provided? setattr(obj, fieldname, related_objs)
python
def _write_related_m2m_relations(self, obj, many_to_many_relationships): """ For the given `many_to_many_relationships` dict mapping field names to a list of object instances, apply the instance listing to the `obj`s named many-to-many relationship field. """ for fieldname, related_objs in many_to_many_relationships.items(): # TODO On PATCH avoid clearing existing relationships not provided? setattr(obj, fieldname, related_objs)
[ "def", "_write_related_m2m_relations", "(", "self", ",", "obj", ",", "many_to_many_relationships", ")", ":", "for", "fieldname", ",", "related_objs", "in", "many_to_many_relationships", ".", "items", "(", ")", ":", "# TODO On PATCH avoid clearing existing relationships not ...
For the given `many_to_many_relationships` dict mapping field names to a list of object instances, apply the instance listing to the `obj`s named many-to-many relationship field.
[ "For", "the", "given", "many_to_many_relationships", "dict", "mapping", "field", "names", "to", "a", "list", "of", "object", "instances", "apply", "the", "instance", "listing", "to", "the", "obj", "s", "named", "many", "-", "to", "-", "many", "relationship", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L329-L337
train
33,423
ic-labs/django-icekit
icekit/plugins/__init__.py
FileSystemLayoutsPlugin.get_choices
def get_choices(self): """ Return a list of choices for source files found in configured layout template directories. """ choices = [] for label_prefix, templates_dir, template_name_prefix in \ appsettings.LAYOUT_TEMPLATES: source_dir = os.path.join(templates_dir, template_name_prefix) # Walk directories, appending a choice for each source file. for local, dirs, files in os.walk(source_dir, followlinks=True): for source_file in files: template_name = os.path.join( template_name_prefix, source_file) label = '%s: %s' % (label_prefix, source_file) choices.append((template_name, label)) return choices
python
def get_choices(self): """ Return a list of choices for source files found in configured layout template directories. """ choices = [] for label_prefix, templates_dir, template_name_prefix in \ appsettings.LAYOUT_TEMPLATES: source_dir = os.path.join(templates_dir, template_name_prefix) # Walk directories, appending a choice for each source file. for local, dirs, files in os.walk(source_dir, followlinks=True): for source_file in files: template_name = os.path.join( template_name_prefix, source_file) label = '%s: %s' % (label_prefix, source_file) choices.append((template_name, label)) return choices
[ "def", "get_choices", "(", "self", ")", ":", "choices", "=", "[", "]", "for", "label_prefix", ",", "templates_dir", ",", "template_name_prefix", "in", "appsettings", ".", "LAYOUT_TEMPLATES", ":", "source_dir", "=", "os", ".", "path", ".", "join", "(", "templ...
Return a list of choices for source files found in configured layout template directories.
[ "Return", "a", "list", "of", "choices", "for", "source", "files", "found", "in", "configured", "layout", "template", "directories", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/__init__.py#L116-L132
train
33,424
ic-labs/django-icekit
icekit/project/jinja2.py
environment
def environment(**options): """ Add ``static`` and ``url`` functions to the ``environment`` context processor and return as a Jinja2 ``Environment`` object. """ env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) env.globals.update(context_processors.environment()) return env
python
def environment(**options): """ Add ``static`` and ``url`` functions to the ``environment`` context processor and return as a Jinja2 ``Environment`` object. """ env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) env.globals.update(context_processors.environment()) return env
[ "def", "environment", "(", "*", "*", "options", ")", ":", "env", "=", "Environment", "(", "*", "*", "options", ")", "env", ".", "globals", ".", "update", "(", "{", "'static'", ":", "staticfiles_storage", ".", "url", ",", "'url'", ":", "reverse", ",", ...
Add ``static`` and ``url`` functions to the ``environment`` context processor and return as a Jinja2 ``Environment`` object.
[ "Add", "static", "and", "url", "functions", "to", "the", "environment", "context", "processor", "and", "return", "as", "a", "Jinja2", "Environment", "object", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/project/jinja2.py#L9-L20
train
33,425
ic-labs/django-icekit
icekit/apps.py
update_site
def update_site(sender, **kwargs): """ Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and `SITE_PORT` settings. """ Site = apps.get_model('sites', 'Site') domain = settings.SITE_DOMAIN if settings.SITE_PORT: domain += ':%s' % settings.SITE_PORT Site.objects.update_or_create( pk=settings.SITE_ID, defaults=dict( domain=domain, name=settings.SITE_NAME)) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. sequence_sql = connection.ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: cursor = connection.cursor() for command in sequence_sql: cursor.execute(command)
python
def update_site(sender, **kwargs): """ Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and `SITE_PORT` settings. """ Site = apps.get_model('sites', 'Site') domain = settings.SITE_DOMAIN if settings.SITE_PORT: domain += ':%s' % settings.SITE_PORT Site.objects.update_or_create( pk=settings.SITE_ID, defaults=dict( domain=domain, name=settings.SITE_NAME)) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. sequence_sql = connection.ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: cursor = connection.cursor() for command in sequence_sql: cursor.execute(command)
[ "def", "update_site", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "Site", "=", "apps", ".", "get_model", "(", "'sites'", ",", "'Site'", ")", "domain", "=", "settings", ".", "SITE_DOMAIN", "if", "settings", ".", "SITE_PORT", ":", "domain", "+=", "...
Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and `SITE_PORT` settings.
[ "Update", "Site", "object", "matching", "SITE_ID", "setting", "with", "SITE_DOMAIN", "and", "SITE_PORT", "settings", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/apps.py#L16-L37
train
33,426
ic-labs/django-icekit
icekit_events/templatetags/events_tags.py
_format_with_same_year
def _format_with_same_year(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same year as another date. Usually this means ommitting the year. This can be overridden by specifying a format that has `_SAME_YEAR` appended to the name in the project's `formats` spec. """ # gotta use a janky way of resolving the format test_format_specifier = format_specifier + "_SAME_YEAR" test_format = get_format(test_format_specifier, use_l10n=True) if test_format == test_format_specifier: # this format string didn't resolve to anything and may be a raw format. # Use a regex to remove year markers instead. return re.sub(YEAR_RE, '', get_format(format_specifier)) else: return test_format
python
def _format_with_same_year(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same year as another date. Usually this means ommitting the year. This can be overridden by specifying a format that has `_SAME_YEAR` appended to the name in the project's `formats` spec. """ # gotta use a janky way of resolving the format test_format_specifier = format_specifier + "_SAME_YEAR" test_format = get_format(test_format_specifier, use_l10n=True) if test_format == test_format_specifier: # this format string didn't resolve to anything and may be a raw format. # Use a regex to remove year markers instead. return re.sub(YEAR_RE, '', get_format(format_specifier)) else: return test_format
[ "def", "_format_with_same_year", "(", "format_specifier", ")", ":", "# gotta use a janky way of resolving the format", "test_format_specifier", "=", "format_specifier", "+", "\"_SAME_YEAR\"", "test_format", "=", "get_format", "(", "test_format_specifier", ",", "use_l10n", "=", ...
Return a version of `format_specifier` that renders a date assuming it has the same year as another date. Usually this means ommitting the year. This can be overridden by specifying a format that has `_SAME_YEAR` appended to the name in the project's `formats` spec.
[ "Return", "a", "version", "of", "format_specifier", "that", "renders", "a", "date", "assuming", "it", "has", "the", "same", "year", "as", "another", "date", ".", "Usually", "this", "means", "ommitting", "the", "year", ".", "This", "can", "be", "overridden", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/templatetags/events_tags.py#L46-L63
train
33,427
ic-labs/django-icekit
icekit_events/templatetags/events_tags.py
_format_with_same_year_and_month
def _format_with_same_year_and_month(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` spec. """ test_format_specifier = format_specifier + "_SAME_YEAR_SAME_MONTH" test_format = get_format(test_format_specifier, use_l10n=True) if test_format == test_format_specifier: # this format string didn't resolve to anything and may be a raw format. # Use a regex to remove year and month markers instead. no_year = re.sub(YEAR_RE, '', get_format(format_specifier)) return re.sub(MONTH_RE, '', no_year) else: return test_format
python
def _format_with_same_year_and_month(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` spec. """ test_format_specifier = format_specifier + "_SAME_YEAR_SAME_MONTH" test_format = get_format(test_format_specifier, use_l10n=True) if test_format == test_format_specifier: # this format string didn't resolve to anything and may be a raw format. # Use a regex to remove year and month markers instead. no_year = re.sub(YEAR_RE, '', get_format(format_specifier)) return re.sub(MONTH_RE, '', no_year) else: return test_format
[ "def", "_format_with_same_year_and_month", "(", "format_specifier", ")", ":", "test_format_specifier", "=", "format_specifier", "+", "\"_SAME_YEAR_SAME_MONTH\"", "test_format", "=", "get_format", "(", "test_format_specifier", ",", "use_l10n", "=", "True", ")", "if", "test...
Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` spec.
[ "Return", "a", "version", "of", "format_specifier", "that", "renders", "a", "date", "assuming", "it", "has", "the", "same", "year", "and", "month", "as", "another", "date", ".", "Usually", "this", "means", "ommitting", "the", "year", "and", "month", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/templatetags/events_tags.py#L65-L83
train
33,428
ic-labs/django-icekit
icekit/admin.py
LayoutAdmin._get_ctypes
def _get_ctypes(self): """ Returns all related objects for this model. """ ctypes = [] for related_object in self.model._meta.get_all_related_objects(): model = getattr(related_object, 'related_model', related_object.model) ctypes.append(ContentType.objects.get_for_model(model).pk) if model.__subclasses__(): for child in model.__subclasses__(): ctypes.append(ContentType.objects.get_for_model(child).pk) return ctypes
python
def _get_ctypes(self): """ Returns all related objects for this model. """ ctypes = [] for related_object in self.model._meta.get_all_related_objects(): model = getattr(related_object, 'related_model', related_object.model) ctypes.append(ContentType.objects.get_for_model(model).pk) if model.__subclasses__(): for child in model.__subclasses__(): ctypes.append(ContentType.objects.get_for_model(child).pk) return ctypes
[ "def", "_get_ctypes", "(", "self", ")", ":", "ctypes", "=", "[", "]", "for", "related_object", "in", "self", ".", "model", ".", "_meta", ".", "get_all_related_objects", "(", ")", ":", "model", "=", "getattr", "(", "related_object", ",", "'related_model'", ...
Returns all related objects for this model.
[ "Returns", "all", "related", "objects", "for", "this", "model", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L18-L29
train
33,429
ic-labs/django-icekit
icekit/admin.py
LayoutAdmin.placeholder_data_view
def placeholder_data_view(self, request, id): """ Return placeholder data for the given layout's template. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. try: layout = models.Layout.objects.get(pk=id) except models.Layout.DoesNotExist: json = {'success': False, 'error': 'Layout not found'} status = 404 else: placeholders = layout.get_placeholder_data() status = 200 placeholders = [p.as_dict() for p in placeholders] # inject placeholder help text, if any is set for p in placeholders: try: p['help_text'] = settings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(p['slot']).get('help_text') except AttributeError: p['help_text'] = None json = { 'id': layout.id, 'title': layout.title, 'placeholders': placeholders, } return JsonResponse(json, status=status)
python
def placeholder_data_view(self, request, id): """ Return placeholder data for the given layout's template. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. try: layout = models.Layout.objects.get(pk=id) except models.Layout.DoesNotExist: json = {'success': False, 'error': 'Layout not found'} status = 404 else: placeholders = layout.get_placeholder_data() status = 200 placeholders = [p.as_dict() for p in placeholders] # inject placeholder help text, if any is set for p in placeholders: try: p['help_text'] = settings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(p['slot']).get('help_text') except AttributeError: p['help_text'] = None json = { 'id': layout.id, 'title': layout.title, 'placeholders': placeholders, } return JsonResponse(json, status=status)
[ "def", "placeholder_data_view", "(", "self", ",", "request", ",", "id", ")", ":", "# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.", "try", ":", "layout", "=", "models", ".", "Layout", ".", "objects", ".", "get", "(", "pk", "=", "id", ")", "exc...
Return placeholder data for the given layout's template.
[ "Return", "placeholder", "data", "for", "the", "given", "layout", "s", "template", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L37-L66
train
33,430
ic-labs/django-icekit
icekit/admin.py
LayoutAdmin.get_urls
def get_urls(self): """ Add ``layout_placeholder_data`` URL. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. urls = super(LayoutAdmin, self).get_urls() my_urls = patterns( '', url( r'^placeholder_data/(?P<id>\d+)/$', self.admin_site.admin_view(self.placeholder_data_view), name='layout_placeholder_data', ) ) return my_urls + urls
python
def get_urls(self): """ Add ``layout_placeholder_data`` URL. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. urls = super(LayoutAdmin, self).get_urls() my_urls = patterns( '', url( r'^placeholder_data/(?P<id>\d+)/$', self.admin_site.admin_view(self.placeholder_data_view), name='layout_placeholder_data', ) ) return my_urls + urls
[ "def", "get_urls", "(", "self", ")", ":", "# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.", "urls", "=", "super", "(", "LayoutAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "my_urls", "=", "patterns", "(", "''", ",", "url", "(", "r'^plac...
Add ``layout_placeholder_data`` URL.
[ "Add", "layout_placeholder_data", "URL", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L68-L82
train
33,431
ic-labs/django-icekit
icekit_events/forms.py
RecurrenceRuleWidget.decompress
def decompress(self, value): """ Return the primary key value for the ``Select`` widget if the given recurrence rule exists in the queryset. """ if value: try: pk = self.queryset.get(recurrence_rule=value).pk except self.queryset.model.DoesNotExist: pk = None return [pk, None, value] return [None, None, None]
python
def decompress(self, value): """ Return the primary key value for the ``Select`` widget if the given recurrence rule exists in the queryset. """ if value: try: pk = self.queryset.get(recurrence_rule=value).pk except self.queryset.model.DoesNotExist: pk = None return [pk, None, value] return [None, None, None]
[ "def", "decompress", "(", "self", ",", "value", ")", ":", "if", "value", ":", "try", ":", "pk", "=", "self", ".", "queryset", ".", "get", "(", "recurrence_rule", "=", "value", ")", ".", "pk", "except", "self", ".", "queryset", ".", "model", ".", "D...
Return the primary key value for the ``Select`` widget if the given recurrence rule exists in the queryset.
[ "Return", "the", "primary", "key", "value", "for", "the", "Select", "widget", "if", "the", "given", "recurrence", "rule", "exists", "in", "the", "queryset", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/forms.py#L61-L72
train
33,432
ic-labs/django-icekit
icekit_events/forms.py
RecurrenceRuleField._set_queryset
def _set_queryset(self, queryset): """ Set the queryset on the ``ModelChoiceField`` and choices on the widget. """ self.fields[0].queryset = self.widget.queryset = queryset self.widget.choices = self.fields[0].choices
python
def _set_queryset(self, queryset): """ Set the queryset on the ``ModelChoiceField`` and choices on the widget. """ self.fields[0].queryset = self.widget.queryset = queryset self.widget.choices = self.fields[0].choices
[ "def", "_set_queryset", "(", "self", ",", "queryset", ")", ":", "self", ".", "fields", "[", "0", "]", ".", "queryset", "=", "self", ".", "widget", ".", "queryset", "=", "queryset", "self", ".", "widget", ".", "choices", "=", "self", ".", "fields", "[...
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
[ "Set", "the", "queryset", "on", "the", "ModelChoiceField", "and", "choices", "on", "the", "widget", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/forms.py#L171-L176
train
33,433
ic-labs/django-icekit
icekit_events/plugins/event_content_listing/forms.py
EventContentListingAdminForm.filter_content_types
def filter_content_types(self, content_type_qs): """ Filter the content types selectable to only event subclasses """ valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, EventBase): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
python
def filter_content_types(self, content_type_qs): """ Filter the content types selectable to only event subclasses """ valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, EventBase): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
[ "def", "filter_content_types", "(", "self", ",", "content_type_qs", ")", ":", "valid_ct_ids", "=", "[", "]", "for", "ct", "in", "content_type_qs", ":", "model", "=", "ct", ".", "model_class", "(", ")", "if", "model", "and", "issubclass", "(", "model", ",",...
Filter the content types selectable to only event subclasses
[ "Filter", "the", "content", "types", "selectable", "to", "only", "event", "subclasses" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/plugins/event_content_listing/forms.py#L18-L25
train
33,434
ic-labs/django-icekit
icekit/utils/pagination.py
describe_page_numbers
def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3): """ Produces a description of how to display a paginated list's page numbers. Rather than just spitting out a list of every page available, the page numbers returned will be trimmed to display only the immediate numbers around the start, end, and the current page. :param current_page: the current page number (page numbers should start at 1) :param total_count: the total number of items that are being paginated :param per_page: the number of items that are displayed per page :param page_numbers_at_ends: the amount of page numbers to display at the beginning and end of the list :param pages_numbers_around_current: the amount of page numbers to display around the currently selected page :return: a dictionary describing the page numbers, relative to the current page """ if total_count: page_count = int(math.ceil(1.0 * total_count / per_page)) if page_count < current_page: raise PageNumberOutOfBounds page_numbers = get_page_numbers( current_page=current_page, num_pages=page_count, extremes=page_numbers_at_ends, arounds=pages_numbers_around_current, ) current_items_start = (current_page * per_page) - per_page + 1 current_items_end = (current_items_start + per_page) - 1 if current_items_end > total_count: current_items_end = total_count else: page_count = 0 page_numbers = [] current_items_start = 0 current_items_end = 0 return { 'numbers': [num for num in page_numbers if not isinstance(num, six.string_types)], 'has_previous': 'previous' in page_numbers, 'has_next': 'next' in page_numbers, 'current_page': current_page, 'previous_page': current_page - 1, 'next_page': current_page + 1, 'total_count': total_count, 'page_count': page_count, 'per_page': per_page, 'current_items_start': current_items_start, 'current_items_end': current_items_end, }
python
def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3): """ Produces a description of how to display a paginated list's page numbers. Rather than just spitting out a list of every page available, the page numbers returned will be trimmed to display only the immediate numbers around the start, end, and the current page. :param current_page: the current page number (page numbers should start at 1) :param total_count: the total number of items that are being paginated :param per_page: the number of items that are displayed per page :param page_numbers_at_ends: the amount of page numbers to display at the beginning and end of the list :param pages_numbers_around_current: the amount of page numbers to display around the currently selected page :return: a dictionary describing the page numbers, relative to the current page """ if total_count: page_count = int(math.ceil(1.0 * total_count / per_page)) if page_count < current_page: raise PageNumberOutOfBounds page_numbers = get_page_numbers( current_page=current_page, num_pages=page_count, extremes=page_numbers_at_ends, arounds=pages_numbers_around_current, ) current_items_start = (current_page * per_page) - per_page + 1 current_items_end = (current_items_start + per_page) - 1 if current_items_end > total_count: current_items_end = total_count else: page_count = 0 page_numbers = [] current_items_start = 0 current_items_end = 0 return { 'numbers': [num for num in page_numbers if not isinstance(num, six.string_types)], 'has_previous': 'previous' in page_numbers, 'has_next': 'next' in page_numbers, 'current_page': current_page, 'previous_page': current_page - 1, 'next_page': current_page + 1, 'total_count': total_count, 'page_count': page_count, 'per_page': per_page, 'current_items_start': current_items_start, 'current_items_end': current_items_end, }
[ "def", "describe_page_numbers", "(", "current_page", ",", "total_count", ",", "per_page", ",", "page_numbers_at_ends", "=", "3", ",", "pages_numbers_around_current", "=", "3", ")", ":", "if", "total_count", ":", "page_count", "=", "int", "(", "math", ".", "ceil"...
Produces a description of how to display a paginated list's page numbers. Rather than just spitting out a list of every page available, the page numbers returned will be trimmed to display only the immediate numbers around the start, end, and the current page. :param current_page: the current page number (page numbers should start at 1) :param total_count: the total number of items that are being paginated :param per_page: the number of items that are displayed per page :param page_numbers_at_ends: the amount of page numbers to display at the beginning and end of the list :param pages_numbers_around_current: the amount of page numbers to display around the currently selected page :return: a dictionary describing the page numbers, relative to the current page
[ "Produces", "a", "description", "of", "how", "to", "display", "a", "paginated", "list", "s", "page", "numbers", ".", "Rather", "than", "just", "spitting", "out", "a", "list", "of", "every", "page", "available", "the", "page", "numbers", "returned", "will", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/pagination.py#L16-L62
train
33,435
ic-labs/django-icekit
icekit/middleware.py
render_stats
def render_stats(stats, sort, format): """ Returns a StringIO containing the formatted statistics from _statsfile_. _sort_ is a list of fields to sort by. _format_ is the name of the method that pstats uses to format the data. """ output = StdoutWrapper() if hasattr(stats, "stream"): stats.stream = output.stream stats.sort_stats(*sort) getattr(stats, format)() return output.stream
python
def render_stats(stats, sort, format): """ Returns a StringIO containing the formatted statistics from _statsfile_. _sort_ is a list of fields to sort by. _format_ is the name of the method that pstats uses to format the data. """ output = StdoutWrapper() if hasattr(stats, "stream"): stats.stream = output.stream stats.sort_stats(*sort) getattr(stats, format)() return output.stream
[ "def", "render_stats", "(", "stats", ",", "sort", ",", "format", ")", ":", "output", "=", "StdoutWrapper", "(", ")", "if", "hasattr", "(", "stats", ",", "\"stream\"", ")", ":", "stats", ".", "stream", "=", "output", ".", "stream", "stats", ".", "sort_s...
Returns a StringIO containing the formatted statistics from _statsfile_. _sort_ is a list of fields to sort by. _format_ is the name of the method that pstats uses to format the data.
[ "Returns", "a", "StringIO", "containing", "the", "formatted", "statistics", "from", "_statsfile_", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L42-L54
train
33,436
ic-labs/django-icekit
icekit/middleware.py
render_queries
def render_queries(queries, sort): """ Returns a StringIO containing the formatted SQL queries. _sort_ is a field to sort by. """ output = StringIO() if sort == 'order': print >>output, " time query" for query in queries: print >>output, " %8s %s" % (query["time"], query["sql"]) return output if sort == 'time': def sorter(x, y): return cmp(x[1][1], y[1][1]) elif sort == 'queries': def sorter(x, y): return cmp(x[1][0], y[1][0]) else: raise RuntimeError("Unknown sort: %s" % sort) print >>output, " queries time query" results = {} for query in queries: try: result = results[query["sql"]] result[0] += 1 result[1] += Decimal(query["time"]) except KeyError: results[query["sql"]] = [1, Decimal(query["time"])] results = sorted(results.iteritems(), cmp=sorter, reverse=True) for result in results: print >>output, " %8d %8.3f %s" % ( result[1][0], result[1][1], result[0] ) return output
python
def render_queries(queries, sort): """ Returns a StringIO containing the formatted SQL queries. _sort_ is a field to sort by. """ output = StringIO() if sort == 'order': print >>output, " time query" for query in queries: print >>output, " %8s %s" % (query["time"], query["sql"]) return output if sort == 'time': def sorter(x, y): return cmp(x[1][1], y[1][1]) elif sort == 'queries': def sorter(x, y): return cmp(x[1][0], y[1][0]) else: raise RuntimeError("Unknown sort: %s" % sort) print >>output, " queries time query" results = {} for query in queries: try: result = results[query["sql"]] result[0] += 1 result[1] += Decimal(query["time"]) except KeyError: results[query["sql"]] = [1, Decimal(query["time"])] results = sorted(results.iteritems(), cmp=sorter, reverse=True) for result in results: print >>output, " %8d %8.3f %s" % ( result[1][0], result[1][1], result[0] ) return output
[ "def", "render_queries", "(", "queries", ",", "sort", ")", ":", "output", "=", "StringIO", "(", ")", "if", "sort", "==", "'order'", ":", "print", ">>", "output", ",", "\" time query\"", "for", "query", "in", "queries", ":", "print", ">>", "output", "...
Returns a StringIO containing the formatted SQL queries. _sort_ is a field to sort by.
[ "Returns", "a", "StringIO", "containing", "the", "formatted", "SQL", "queries", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L57-L91
train
33,437
ic-labs/django-icekit
icekit/middleware.py
unpickle_stats
def unpickle_stats(stats): """Unpickle a pstats.Stats object""" stats = cPickle.loads(stats) stats.stream = True return stats
python
def unpickle_stats(stats): """Unpickle a pstats.Stats object""" stats = cPickle.loads(stats) stats.stream = True return stats
[ "def", "unpickle_stats", "(", "stats", ")", ":", "stats", "=", "cPickle", ".", "loads", "(", "stats", ")", "stats", ".", "stream", "=", "True", "return", "stats" ]
Unpickle a pstats.Stats object
[ "Unpickle", "a", "pstats", ".", "Stats", "object" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L101-L105
train
33,438
ic-labs/django-icekit
icekit/middleware.py
display_stats
def display_stats(request, stats, queries): """ Generate a HttpResponse of functions for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries. """ sort = [ request.REQUEST.get('sort_first', 'time'), request.REQUEST.get('sort_second', 'calls') ] fmt = request.REQUEST.get('format', 'print_stats') sort_first_buttons = RadioButtons('sort_first', sort[0], sort_categories) sort_second_buttons = RadioButtons('sort_second', sort[1], sort_categories) format_buttons = RadioButtons('format', fmt, ( ('print_stats', 'by function'), ('print_callers', 'by callers'), ('print_callees', 'by callees') )) output = render_stats(stats, sort, fmt) output.reset() output = [html.escape(unicode(line)) for line in output.readlines()] response = HttpResponse(content_type='text/html; charset=utf-8') response.content = (stats_template % { 'format_buttons': format_buttons, 'sort_first_buttons': sort_first_buttons, 'sort_second_buttons': sort_second_buttons, 'rawqueries' : b64encode(cPickle.dumps(queries)), 'rawstats': b64encode(pickle_stats(stats)), 'stats': "".join(output), 'url': request.path }) return response
python
def display_stats(request, stats, queries): """ Generate a HttpResponse of functions for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries. """ sort = [ request.REQUEST.get('sort_first', 'time'), request.REQUEST.get('sort_second', 'calls') ] fmt = request.REQUEST.get('format', 'print_stats') sort_first_buttons = RadioButtons('sort_first', sort[0], sort_categories) sort_second_buttons = RadioButtons('sort_second', sort[1], sort_categories) format_buttons = RadioButtons('format', fmt, ( ('print_stats', 'by function'), ('print_callers', 'by callers'), ('print_callees', 'by callees') )) output = render_stats(stats, sort, fmt) output.reset() output = [html.escape(unicode(line)) for line in output.readlines()] response = HttpResponse(content_type='text/html; charset=utf-8') response.content = (stats_template % { 'format_buttons': format_buttons, 'sort_first_buttons': sort_first_buttons, 'sort_second_buttons': sort_second_buttons, 'rawqueries' : b64encode(cPickle.dumps(queries)), 'rawstats': b64encode(pickle_stats(stats)), 'stats': "".join(output), 'url': request.path }) return response
[ "def", "display_stats", "(", "request", ",", "stats", ",", "queries", ")", ":", "sort", "=", "[", "request", ".", "REQUEST", ".", "get", "(", "'sort_first'", ",", "'time'", ")", ",", "request", ".", "REQUEST", ".", "get", "(", "'sort_second'", ",", "'c...
Generate a HttpResponse of functions for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries.
[ "Generate", "a", "HttpResponse", "of", "functions", "for", "a", "profiling", "run", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L201-L233
train
33,439
ic-labs/django-icekit
icekit/middleware.py
display_queries
def display_queries(request, stats, queries): """ Generate a HttpResponse of SQL queries for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries. """ sort = request.REQUEST.get('sort_by', 'time') sort_buttons = RadioButtons('sort_by', sort, ( ('order', 'by order'), ('time', 'time'), ('queries', 'query count') )) output = render_queries(queries, sort) output.reset() output = [html.escape(unicode(line)) for line in output.readlines()] response = HttpResponse(mimetype='text/html; charset=utf-8') response.content = (queries_template % { 'sort_buttons': sort_buttons, 'num_queries': len(queries), 'queries': "".join(output), 'rawqueries' : b64encode(cPickle.dumps(queries)), 'rawstats': b64encode(pickle_stats(stats)), 'url': request.path }) return response
python
def display_queries(request, stats, queries): """ Generate a HttpResponse of SQL queries for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries. """ sort = request.REQUEST.get('sort_by', 'time') sort_buttons = RadioButtons('sort_by', sort, ( ('order', 'by order'), ('time', 'time'), ('queries', 'query count') )) output = render_queries(queries, sort) output.reset() output = [html.escape(unicode(line)) for line in output.readlines()] response = HttpResponse(mimetype='text/html; charset=utf-8') response.content = (queries_template % { 'sort_buttons': sort_buttons, 'num_queries': len(queries), 'queries': "".join(output), 'rawqueries' : b64encode(cPickle.dumps(queries)), 'rawstats': b64encode(pickle_stats(stats)), 'url': request.path }) return response
[ "def", "display_queries", "(", "request", ",", "stats", ",", "queries", ")", ":", "sort", "=", "request", ".", "REQUEST", ".", "get", "(", "'sort_by'", ",", "'time'", ")", "sort_buttons", "=", "RadioButtons", "(", "'sort_by'", ",", "sort", ",", "(", "(",...
Generate a HttpResponse of SQL queries for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries.
[ "Generate", "a", "HttpResponse", "of", "SQL", "queries", "for", "a", "profiling", "run", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L260-L283
train
33,440
ic-labs/django-icekit
icekit/middleware.py
ProfileMiddleware.process_request
def process_request(self, request): """ Setup the profiler for a profiling run and clear the SQL query log. If this is a resort of an existing profiling run, just return the resorted list. """ def unpickle(params): stats = unpickle_stats(b64decode(params.get('stats', ''))) queries = cPickle.loads(b64decode(params.get('queries', ''))) return stats, queries if request.method != 'GET' and \ not (request.META.get( 'HTTP_CONTENT_TYPE', request.META.get('CONTENT_TYPE', '') ) in ['multipart/form-data', 'application/x-www-form-urlencoded']): return if (request.REQUEST.get('profile', False) and (settings.DEBUG == True or request.user.is_staff)): request.statsfile = tempfile.NamedTemporaryFile() params = request.REQUEST if (params.get('show_stats', False) and params.get('show_queries', '1') == '1'): # Instantly re-sort the existing stats data stats, queries = unpickle(params) return display_stats(request, stats, queries) elif (params.get('show_queries', False) and params.get('show_stats', '1') == '1'): stats, queries = unpickle(params) return display_queries(request, stats, queries) else: # We don't have previous data, so initialize the profiler request.profiler = hotshot.Profile(request.statsfile.name) reset_queries()
python
def process_request(self, request): """ Setup the profiler for a profiling run and clear the SQL query log. If this is a resort of an existing profiling run, just return the resorted list. """ def unpickle(params): stats = unpickle_stats(b64decode(params.get('stats', ''))) queries = cPickle.loads(b64decode(params.get('queries', ''))) return stats, queries if request.method != 'GET' and \ not (request.META.get( 'HTTP_CONTENT_TYPE', request.META.get('CONTENT_TYPE', '') ) in ['multipart/form-data', 'application/x-www-form-urlencoded']): return if (request.REQUEST.get('profile', False) and (settings.DEBUG == True or request.user.is_staff)): request.statsfile = tempfile.NamedTemporaryFile() params = request.REQUEST if (params.get('show_stats', False) and params.get('show_queries', '1') == '1'): # Instantly re-sort the existing stats data stats, queries = unpickle(params) return display_stats(request, stats, queries) elif (params.get('show_queries', False) and params.get('show_stats', '1') == '1'): stats, queries = unpickle(params) return display_queries(request, stats, queries) else: # We don't have previous data, so initialize the profiler request.profiler = hotshot.Profile(request.statsfile.name) reset_queries()
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "def", "unpickle", "(", "params", ")", ":", "stats", "=", "unpickle_stats", "(", "b64decode", "(", "params", ".", "get", "(", "'stats'", ",", "''", ")", ")", ")", "queries", "=", "cPickle...
Setup the profiler for a profiling run and clear the SQL query log. If this is a resort of an existing profiling run, just return the resorted list.
[ "Setup", "the", "profiler", "for", "a", "profiling", "run", "and", "clear", "the", "SQL", "query", "log", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L293-L326
train
33,441
ic-labs/django-icekit
icekit/middleware.py
ProfileMiddleware.process_view
def process_view(self, request, view_func, view_args, view_kwargs): """Run the profiler on _view_func_.""" profiler = getattr(request, 'profiler', None) if profiler: # Make sure profiler variables don't get passed into view_func original_get = request.GET request.GET = original_get.copy() request.GET.pop('profile', None) request.GET.pop('show_queries', None) request.GET.pop('show_stats', None) try: return profiler.runcall( view_func, request, *view_args, **view_kwargs ) finally: request.GET = original_get
python
def process_view(self, request, view_func, view_args, view_kwargs): """Run the profiler on _view_func_.""" profiler = getattr(request, 'profiler', None) if profiler: # Make sure profiler variables don't get passed into view_func original_get = request.GET request.GET = original_get.copy() request.GET.pop('profile', None) request.GET.pop('show_queries', None) request.GET.pop('show_stats', None) try: return profiler.runcall( view_func, request, *view_args, **view_kwargs ) finally: request.GET = original_get
[ "def", "process_view", "(", "self", ",", "request", ",", "view_func", ",", "view_args", ",", "view_kwargs", ")", ":", "profiler", "=", "getattr", "(", "request", ",", "'profiler'", ",", "None", ")", "if", "profiler", ":", "# Make sure profiler variables don't ge...
Run the profiler on _view_func_.
[ "Run", "the", "profiler", "on", "_view_func_", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L328-L343
train
33,442
ic-labs/django-icekit
icekit/middleware.py
ProfileMiddleware.process_response
def process_response(self, request, response): """Finish profiling and render the results.""" profiler = getattr(request, 'profiler', None) if profiler: profiler.close() params = request.REQUEST stats = hotshot.stats.load(request.statsfile.name) queries = connection.queries if (params.get('show_queries', False) and params.get('show_stats', '1') == '1'): response = display_queries(request, stats, queries) else: response = display_stats(request, stats, queries) return response
python
def process_response(self, request, response): """Finish profiling and render the results.""" profiler = getattr(request, 'profiler', None) if profiler: profiler.close() params = request.REQUEST stats = hotshot.stats.load(request.statsfile.name) queries = connection.queries if (params.get('show_queries', False) and params.get('show_stats', '1') == '1'): response = display_queries(request, stats, queries) else: response = display_stats(request, stats, queries) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "profiler", "=", "getattr", "(", "request", ",", "'profiler'", ",", "None", ")", "if", "profiler", ":", "profiler", ".", "close", "(", ")", "params", "=", "request", ".", ...
Finish profiling and render the results.
[ "Finish", "profiling", "and", "render", "the", "results", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L345-L358
train
33,443
ic-labs/django-icekit
glamkit_collections/etl/base.py
ETL.items_to_extract
def items_to_extract(self, offset=0, length=None): """ Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific """ endoffset = length and offset + length qs = self.origin_data()[offset:endoffset] self.items_to_extract_length = qs.count() return qs
python
def items_to_extract(self, offset=0, length=None): """ Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific """ endoffset = length and offset + length qs = self.origin_data()[offset:endoffset] self.items_to_extract_length = qs.count() return qs
[ "def", "items_to_extract", "(", "self", ",", "offset", "=", "0", ",", "length", "=", "None", ")", ":", "endoffset", "=", "length", "and", "offset", "+", "length", "qs", "=", "self", ".", "origin_data", "(", ")", "[", "offset", ":", "endoffset", "]", ...
Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific
[ "Return", "an", "iterable", "of", "specific", "items", "to", "extract", ".", "As", "a", "side", "-", "effect", "set", "self", ".", "items_to_extract_length", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/glamkit_collections/etl/base.py#L17-L29
train
33,444
ic-labs/django-icekit
icekit/utils/sequences.py
dedupe_and_sort
def dedupe_and_sort(sequence, first=None, last=None): """ De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will be placed at the end of the sequence. For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings. Items from `first` will only be included if they also appear in `sequence`. Items from `sequence` that don't appear in `first` will come after any that do, and retain their existing order. Returns a sequence of the same type as given. """ first = first or [] last = last or [] # Add items that should be sorted first. new_sequence = [i for i in first if i in sequence] # Add remaining items in their current order, ignoring duplicates and items # that should be sorted last. for item in sequence: if item not in new_sequence and item not in last: new_sequence.append(item) # Add items that should be sorted last. new_sequence.extend([i for i in last if i in sequence]) # Return a sequence of the same type as given. return type(sequence)(new_sequence)
python
def dedupe_and_sort(sequence, first=None, last=None): """ De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will be placed at the end of the sequence. For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings. Items from `first` will only be included if they also appear in `sequence`. Items from `sequence` that don't appear in `first` will come after any that do, and retain their existing order. Returns a sequence of the same type as given. """ first = first or [] last = last or [] # Add items that should be sorted first. new_sequence = [i for i in first if i in sequence] # Add remaining items in their current order, ignoring duplicates and items # that should be sorted last. for item in sequence: if item not in new_sequence and item not in last: new_sequence.append(item) # Add items that should be sorted last. new_sequence.extend([i for i in last if i in sequence]) # Return a sequence of the same type as given. return type(sequence)(new_sequence)
[ "def", "dedupe_and_sort", "(", "sequence", ",", "first", "=", "None", ",", "last", "=", "None", ")", ":", "first", "=", "first", "or", "[", "]", "last", "=", "last", "or", "[", "]", "# Add items that should be sorted first.", "new_sequence", "=", "[", "i",...
De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will be placed at the end of the sequence. For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings. Items from `first` will only be included if they also appear in `sequence`. Items from `sequence` that don't appear in `first` will come after any that do, and retain their existing order. Returns a sequence of the same type as given.
[ "De", "-", "dupe", "and", "partially", "sort", "a", "sequence", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/sequences.py#L1-L32
train
33,445
ic-labs/django-icekit
icekit/utils/sequences.py
slice_sequences
def slice_sequences(sequences, start, end, apply_slice=None): """ Performs a slice across multiple sequences. Useful when paginating across chained collections. :param sequences: an iterable of iterables, each nested iterable should contain a sequence and its size :param start: starting index to apply the slice from :param end: index that the slice should end at :param apply_slice: function that takes the sequence and start/end offsets, and returns the sliced sequence :return: a list of the items sliced from the sequences """ if start < 0 or end < 0 or end <= start: raise ValueError('Start and/or End out of range. Start: %s. End: %s' % (start, end)) items_to_take = end - start items_passed = 0 collected_items = [] if apply_slice is None: apply_slice = _apply_slice for sequence, count in sequences: offset_start = start - items_passed offset_end = end - items_passed if items_passed == start: items = apply_slice(sequence, 0, items_to_take) elif 0 < offset_start < count: items = apply_slice(sequence, offset_start, offset_end) elif offset_start < 0: items = apply_slice(sequence, 0, offset_end) else: items = [] items = list(items) collected_items += items items_to_take -= len(items) items_passed += count if items_passed > end or items_to_take == 0: break return collected_items
python
def slice_sequences(sequences, start, end, apply_slice=None): """ Performs a slice across multiple sequences. Useful when paginating across chained collections. :param sequences: an iterable of iterables, each nested iterable should contain a sequence and its size :param start: starting index to apply the slice from :param end: index that the slice should end at :param apply_slice: function that takes the sequence and start/end offsets, and returns the sliced sequence :return: a list of the items sliced from the sequences """ if start < 0 or end < 0 or end <= start: raise ValueError('Start and/or End out of range. Start: %s. End: %s' % (start, end)) items_to_take = end - start items_passed = 0 collected_items = [] if apply_slice is None: apply_slice = _apply_slice for sequence, count in sequences: offset_start = start - items_passed offset_end = end - items_passed if items_passed == start: items = apply_slice(sequence, 0, items_to_take) elif 0 < offset_start < count: items = apply_slice(sequence, offset_start, offset_end) elif offset_start < 0: items = apply_slice(sequence, 0, offset_end) else: items = [] items = list(items) collected_items += items items_to_take -= len(items) items_passed += count if items_passed > end or items_to_take == 0: break return collected_items
[ "def", "slice_sequences", "(", "sequences", ",", "start", ",", "end", ",", "apply_slice", "=", "None", ")", ":", "if", "start", "<", "0", "or", "end", "<", "0", "or", "end", "<=", "start", ":", "raise", "ValueError", "(", "'Start and/or End out of range. S...
Performs a slice across multiple sequences. Useful when paginating across chained collections. :param sequences: an iterable of iterables, each nested iterable should contain a sequence and its size :param start: starting index to apply the slice from :param end: index that the slice should end at :param apply_slice: function that takes the sequence and start/end offsets, and returns the sliced sequence :return: a list of the items sliced from the sequences
[ "Performs", "a", "slice", "across", "multiple", "sequences", ".", "Useful", "when", "paginating", "across", "chained", "collections", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/sequences.py#L39-L85
train
33,446
ic-labs/django-icekit
icekit/admin_tools/widgets.py
quote
def quote(key, value): """Certain options support string values. We want clients to be able to pass Python strings in but we need them to be quoted in the output. Unfortunately some of those options also allow numbers so we type check the value before wrapping it in quotes. """ if key in quoted_options and isinstance(value, string_types): return "'%s'" % value if key in quoted_bool_options and isinstance(value, bool): return {True:'true',False:'false'}[value] return value
python
def quote(key, value): """Certain options support string values. We want clients to be able to pass Python strings in but we need them to be quoted in the output. Unfortunately some of those options also allow numbers so we type check the value before wrapping it in quotes. """ if key in quoted_options and isinstance(value, string_types): return "'%s'" % value if key in quoted_bool_options and isinstance(value, bool): return {True:'true',False:'false'}[value] return value
[ "def", "quote", "(", "key", ",", "value", ")", ":", "if", "key", "in", "quoted_options", "and", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "\"'%s'\"", "%", "value", "if", "key", "in", "quoted_bool_options", "and", "isinstance", "(...
Certain options support string values. We want clients to be able to pass Python strings in but we need them to be quoted in the output. Unfortunately some of those options also allow numbers so we type check the value before wrapping it in quotes.
[ "Certain", "options", "support", "string", "values", ".", "We", "want", "clients", "to", "be", "able", "to", "pass", "Python", "strings", "in", "but", "we", "need", "them", "to", "be", "quoted", "in", "the", "output", ".", "Unfortunately", "some", "of", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/widgets.py#L146-L158
train
33,447
ic-labs/django-icekit
icekit/utils/images.py
scale_and_crop_with_ranges
def scale_and_crop_with_ranges( im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs): """ An easy_thumbnails processor that accepts a `size_range` tuple, which indicates that one or both dimensions can give by a number of pixels in order to minimize cropping. """ min_width, min_height = size # if there's no restriction on range, or range isn't given, just act as # normal if min_width == 0 or min_height == 0 or not size_range: return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs) max_width = min_width + size_range[0] max_height = min_height + size_range[1] # figure out the minimum and maximum aspect ratios min_ar = min_width * 1.0 / max_height max_ar = max_width * 1.0 / min_height img_width, img_height = [float(v) for v in im.size] img_ar = img_width/img_height # clamp image aspect ratio to given range if img_ar <= min_ar: size = (min_width, max_height) elif img_ar >= max_ar: size = (max_width, min_height) else: # the aspect ratio of the image is within the allowed parameters. size = (max_width, max_height) return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)
python
def scale_and_crop_with_ranges( im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs): """ An easy_thumbnails processor that accepts a `size_range` tuple, which indicates that one or both dimensions can give by a number of pixels in order to minimize cropping. """ min_width, min_height = size # if there's no restriction on range, or range isn't given, just act as # normal if min_width == 0 or min_height == 0 or not size_range: return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs) max_width = min_width + size_range[0] max_height = min_height + size_range[1] # figure out the minimum and maximum aspect ratios min_ar = min_width * 1.0 / max_height max_ar = max_width * 1.0 / min_height img_width, img_height = [float(v) for v in im.size] img_ar = img_width/img_height # clamp image aspect ratio to given range if img_ar <= min_ar: size = (min_width, max_height) elif img_ar >= max_ar: size = (max_width, min_height) else: # the aspect ratio of the image is within the allowed parameters. size = (max_width, max_height) return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)
[ "def", "scale_and_crop_with_ranges", "(", "im", ",", "size", ",", "size_range", "=", "None", ",", "crop", "=", "False", ",", "upscale", "=", "False", ",", "zoom", "=", "None", ",", "target", "=", "None", ",", "*", "*", "kwargs", ")", ":", "min_width", ...
An easy_thumbnails processor that accepts a `size_range` tuple, which indicates that one or both dimensions can give by a number of pixels in order to minimize cropping.
[ "An", "easy_thumbnails", "processor", "that", "accepts", "a", "size_range", "tuple", "which", "indicates", "that", "one", "or", "both", "dimensions", "can", "give", "by", "a", "number", "of", "pixels", "in", "order", "to", "minimize", "cropping", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/images.py#L4-L39
train
33,448
ic-labs/django-icekit
icekit/utils/implementation.py
check_settings
def check_settings(required_settings): """ Checks all settings required by a module have been set. If a setting is required and it could not be found a NotImplementedError will be raised informing which settings are missing. :param required_settings: List of settings names (as strings) that are anticipated to be in the settings module. :return: None. """ defined_settings = [ setting if hasattr(settings, setting) else None for setting in required_settings ] if not all(defined_settings): raise NotImplementedError( 'The following settings have not been set: %s' % ', '.join( set(required_settings) - set(defined_settings) ) )
python
def check_settings(required_settings): """ Checks all settings required by a module have been set. If a setting is required and it could not be found a NotImplementedError will be raised informing which settings are missing. :param required_settings: List of settings names (as strings) that are anticipated to be in the settings module. :return: None. """ defined_settings = [ setting if hasattr(settings, setting) else None for setting in required_settings ] if not all(defined_settings): raise NotImplementedError( 'The following settings have not been set: %s' % ', '.join( set(required_settings) - set(defined_settings) ) )
[ "def", "check_settings", "(", "required_settings", ")", ":", "defined_settings", "=", "[", "setting", "if", "hasattr", "(", "settings", ",", "setting", ")", "else", "None", "for", "setting", "in", "required_settings", "]", "if", "not", "all", "(", "defined_set...
Checks all settings required by a module have been set. If a setting is required and it could not be found a NotImplementedError will be raised informing which settings are missing. :param required_settings: List of settings names (as strings) that are anticipated to be in the settings module. :return: None.
[ "Checks", "all", "settings", "required", "by", "a", "module", "have", "been", "set", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/implementation.py#L4-L25
train
33,449
ic-labs/django-icekit
icekit_events/managers.py
OccurrenceQueryset.available_on_day
def available_on_day(self, day): """ Return events that are available on a given day. """ if isinstance(day, datetime): d = day.date() else: d = day return self.starts_within(d, d)
python
def available_on_day(self, day): """ Return events that are available on a given day. """ if isinstance(day, datetime): d = day.date() else: d = day return self.starts_within(d, d)
[ "def", "available_on_day", "(", "self", ",", "day", ")", ":", "if", "isinstance", "(", "day", ",", "datetime", ")", ":", "d", "=", "day", ".", "date", "(", ")", "else", ":", "d", "=", "day", "return", "self", ".", "starts_within", "(", "d", ",", ...
Return events that are available on a given day.
[ "Return", "events", "that", "are", "available", "on", "a", "given", "day", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/managers.py#L204-L212
train
33,450
ic-labs/django-icekit
icekit/utils/management/base.py
CronBaseCommand.cleanup
def cleanup(self): """ Performs clean-up after task is completed before it is executed again in the next internal. """ # Closes connections to all databases to avoid the long running process # from holding connections indefinitely. for alias in db.connections.databases: logger.info('Closing database connection: %s', alias) db.connections[alias].close()
python
def cleanup(self): """ Performs clean-up after task is completed before it is executed again in the next internal. """ # Closes connections to all databases to avoid the long running process # from holding connections indefinitely. for alias in db.connections.databases: logger.info('Closing database connection: %s', alias) db.connections[alias].close()
[ "def", "cleanup", "(", "self", ")", ":", "# Closes connections to all databases to avoid the long running process", "# from holding connections indefinitely.", "for", "alias", "in", "db", ".", "connections", ".", "databases", ":", "logger", ".", "info", "(", "'Closing datab...
Performs clean-up after task is completed before it is executed again in the next internal.
[ "Performs", "clean", "-", "up", "after", "task", "is", "completed", "before", "it", "is", "executed", "again", "in", "the", "next", "internal", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/management/base.py#L34-L43
train
33,451
ic-labs/django-icekit
icekit/plugins/base.py
PluginMount.get_plugins
def get_plugins(cls, *args, **kwargs): """ Return a list of plugin instances and pass through arguments. """ return [plugin(*args, **kwargs) for plugin in cls.plugins]
python
def get_plugins(cls, *args, **kwargs): """ Return a list of plugin instances and pass through arguments. """ return [plugin(*args, **kwargs) for plugin in cls.plugins]
[ "def", "get_plugins", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "plugin", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "plugin", "in", "cls", ".", "plugins", "]" ]
Return a list of plugin instances and pass through arguments.
[ "Return", "a", "list", "of", "plugin", "instances", "and", "pass", "through", "arguments", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/base.py#L41-L45
train
33,452
ic-labs/django-icekit
icekit/utils/search/views.py
ICEkitSearchView.pre_facet_sqs
def pre_facet_sqs(self): """ Return the queryset used for generating facets, before any facets are applied """ sqs = SearchQuerySet() if self.query: sqs = sqs.filter( SQ(content=AutoQuery(self.query)) | # Search `text` document SQ(get_title=AutoQuery(self.query)) | # boosted field SQ(boosted_search_terms=AutoQuery(self.query)) # boosted field ) return sqs
python
def pre_facet_sqs(self): """ Return the queryset used for generating facets, before any facets are applied """ sqs = SearchQuerySet() if self.query: sqs = sqs.filter( SQ(content=AutoQuery(self.query)) | # Search `text` document SQ(get_title=AutoQuery(self.query)) | # boosted field SQ(boosted_search_terms=AutoQuery(self.query)) # boosted field ) return sqs
[ "def", "pre_facet_sqs", "(", "self", ")", ":", "sqs", "=", "SearchQuerySet", "(", ")", "if", "self", ".", "query", ":", "sqs", "=", "sqs", ".", "filter", "(", "SQ", "(", "content", "=", "AutoQuery", "(", "self", ".", "query", ")", ")", "|", "# Sear...
Return the queryset used for generating facets, before any facets are applied
[ "Return", "the", "queryset", "used", "for", "generating", "facets", "before", "any", "facets", "are", "applied" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/views.py#L40-L54
train
33,453
ic-labs/django-icekit
icekit/utils/search/views.py
ICEkitSearchView.get
def get(self, request, *args, **kwargs): """User has conducted a search, or default state""" form_class = self.get_form_class() form = self.get_form(form_class) top_value = self.get_top_level_facet_value() subfacets = SEARCH_SUBFACETS.get(top_value, []) self.active_facets = [self.top_facet] + subfacets if form.is_valid(): self.query = form.cleaned_data.get(self.search_field) else: self.query = "" sqs = self.pre_facet_sqs() for facet in self.active_facets: sqs = facet.set_on_sqs(sqs) facet_counts = sqs.facet_counts() for facet in self.active_facets: facet.set_values_from_sqs_facet_counts(facet_counts) facet.apply_request_and_page_to_values(self.request, self.fluent_page) for facet in self.active_facets: sqs = facet.narrow_sqs(sqs) context = self.get_context_data(**{ self.form_name: form, 'facets': self.active_facets, 'top_facet': self.top_facet, 'query': self.query, 'object_list': sqs, 'page': self.fluent_page, 'show_placeholders': self.show_placeholders() }) return self.render_to_response(context)
python
def get(self, request, *args, **kwargs): """User has conducted a search, or default state""" form_class = self.get_form_class() form = self.get_form(form_class) top_value = self.get_top_level_facet_value() subfacets = SEARCH_SUBFACETS.get(top_value, []) self.active_facets = [self.top_facet] + subfacets if form.is_valid(): self.query = form.cleaned_data.get(self.search_field) else: self.query = "" sqs = self.pre_facet_sqs() for facet in self.active_facets: sqs = facet.set_on_sqs(sqs) facet_counts = sqs.facet_counts() for facet in self.active_facets: facet.set_values_from_sqs_facet_counts(facet_counts) facet.apply_request_and_page_to_values(self.request, self.fluent_page) for facet in self.active_facets: sqs = facet.narrow_sqs(sqs) context = self.get_context_data(**{ self.form_name: form, 'facets': self.active_facets, 'top_facet': self.top_facet, 'query': self.query, 'object_list': sqs, 'page': self.fluent_page, 'show_placeholders': self.show_placeholders() }) return self.render_to_response(context)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", "get_form", "(", "form_class", ")", "top_value", "=", "self", ".", ...
User has conducted a search, or default state
[ "User", "has", "conducted", "a", "search", "or", "default", "state" ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/views.py#L56-L94
train
33,454
ic-labs/django-icekit
icekit_events/views.py
index
def index(request): """ Listing page for event `Occurrence`s. :param request: Django request object. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse """ warnings.warn( "icekit_events.views.index is deprecated and will disappear in a " "future version. If you need this code, copy it into your project." , DeprecationWarning ) occurrences = models.Occurrence.objects.visible() context = { 'occurrences': occurrences, } return TemplateResponse(request, 'icekit_events/index.html', context)
python
def index(request): """ Listing page for event `Occurrence`s. :param request: Django request object. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse """ warnings.warn( "icekit_events.views.index is deprecated and will disappear in a " "future version. If you need this code, copy it into your project." , DeprecationWarning ) occurrences = models.Occurrence.objects.visible() context = { 'occurrences': occurrences, } return TemplateResponse(request, 'icekit_events/index.html', context)
[ "def", "index", "(", "request", ")", ":", "warnings", ".", "warn", "(", "\"icekit_events.views.index is deprecated and will disappear in a \"", "\"future version. If you need this code, copy it into your project.\"", ",", "DeprecationWarning", ")", "occurrences", "=", "models", "...
Listing page for event `Occurrence`s. :param request: Django request object. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse
[ "Listing", "page", "for", "event", "Occurrence", "s", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/views.py#L20-L41
train
33,455
ic-labs/django-icekit
icekit/workflow/templatetags/workflow_tags.py
get_assigned_to_user
def get_assigned_to_user(parser, token): """ Populates a template variable with the content with WorkflowState assignd for the given criteria. Usage:: {% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_assigned_to_user 10 as content_list for_user 23 %} {% get_assigned_to_user 10 as content_list for_user user %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want. """ tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError( "'get_assigned_to_user' statements require two arguments") if not tokens[1].isdigit(): raise template.TemplateSyntaxError( "First argument to 'get_assigned_to_user' must be an integer") if tokens[2] != 'as': raise template.TemplateSyntaxError( "Second argument to 'get_assigned_to_user' must be 'as'") if len(tokens) > 4: if tokens[4] != 'for_user': raise template.TemplateSyntaxError( "Fourth argument to 'get_assigned_to_user' must be 'for_user'") return AssigedToUserNode(limit=tokens[1], varname=tokens[3], user=(tokens[5] if len(tokens) > 5 else None))
python
def get_assigned_to_user(parser, token): """ Populates a template variable with the content with WorkflowState assignd for the given criteria. Usage:: {% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_assigned_to_user 10 as content_list for_user 23 %} {% get_assigned_to_user 10 as content_list for_user user %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want. """ tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError( "'get_assigned_to_user' statements require two arguments") if not tokens[1].isdigit(): raise template.TemplateSyntaxError( "First argument to 'get_assigned_to_user' must be an integer") if tokens[2] != 'as': raise template.TemplateSyntaxError( "Second argument to 'get_assigned_to_user' must be 'as'") if len(tokens) > 4: if tokens[4] != 'for_user': raise template.TemplateSyntaxError( "Fourth argument to 'get_assigned_to_user' must be 'for_user'") return AssigedToUserNode(limit=tokens[1], varname=tokens[3], user=(tokens[5] if len(tokens) > 5 else None))
[ "def", "get_assigned_to_user", "(", "parser", ",", "token", ")", ":", "tokens", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "<", "4", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"'get_assigned_to...
Populates a template variable with the content with WorkflowState assignd for the given criteria. Usage:: {% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_assigned_to_user 10 as content_list for_user 23 %} {% get_assigned_to_user 10 as content_list for_user user %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want.
[ "Populates", "a", "template", "variable", "with", "the", "content", "with", "WorkflowState", "assignd", "for", "the", "given", "criteria", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/workflow/templatetags/workflow_tags.py#L28-L60
train
33,456
ic-labs/django-icekit
icekit_events/migrations/0002_recurrence_rules.py
forwards
def forwards(apps, schema_editor): """ Create initial recurrence rules. """ RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule') for description, recurrence_rule in RULES: RecurrenceRule.objects.get_or_create( description=description, defaults=dict(recurrence_rule=recurrence_rule), )
python
def forwards(apps, schema_editor): """ Create initial recurrence rules. """ RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule') for description, recurrence_rule in RULES: RecurrenceRule.objects.get_or_create( description=description, defaults=dict(recurrence_rule=recurrence_rule), )
[ "def", "forwards", "(", "apps", ",", "schema_editor", ")", ":", "RecurrenceRule", "=", "apps", ".", "get_model", "(", "'icekit_events'", ",", "'RecurrenceRule'", ")", "for", "description", ",", "recurrence_rule", "in", "RULES", ":", "RecurrenceRule", ".", "objec...
Create initial recurrence rules.
[ "Create", "initial", "recurrence", "rules", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/migrations/0002_recurrence_rules.py#L18-L27
train
33,457
ic-labs/django-icekit
icekit_events/migrations/0002_recurrence_rules.py
backwards
def backwards(apps, schema_editor): """ Delete initial recurrence rules. """ RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule') descriptions = [d for d, rr in RULES] RecurrenceRule.objects.filter(description__in=descriptions).delete()
python
def backwards(apps, schema_editor): """ Delete initial recurrence rules. """ RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule') descriptions = [d for d, rr in RULES] RecurrenceRule.objects.filter(description__in=descriptions).delete()
[ "def", "backwards", "(", "apps", ",", "schema_editor", ")", ":", "RecurrenceRule", "=", "apps", ".", "get_model", "(", "'icekit_events'", ",", "'RecurrenceRule'", ")", "descriptions", "=", "[", "d", "for", "d", ",", "rr", "in", "RULES", "]", "RecurrenceRule"...
Delete initial recurrence rules.
[ "Delete", "initial", "recurrence", "rules", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/migrations/0002_recurrence_rules.py#L30-L36
train
33,458
ic-labs/django-icekit
icekit/project/context_processors.py
environment
def environment(request=None): """ Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context. """ context = { 'COMPRESS_ENABLED': settings.COMPRESS_ENABLED, 'SITE_NAME': settings.SITE_NAME, } for key in settings.ICEKIT_CONTEXT_PROCESSOR_SETTINGS: context[key] = getattr(settings, key, None) return context
python
def environment(request=None): """ Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context. """ context = { 'COMPRESS_ENABLED': settings.COMPRESS_ENABLED, 'SITE_NAME': settings.SITE_NAME, } for key in settings.ICEKIT_CONTEXT_PROCESSOR_SETTINGS: context[key] = getattr(settings, key, None) return context
[ "def", "environment", "(", "request", "=", "None", ")", ":", "context", "=", "{", "'COMPRESS_ENABLED'", ":", "settings", ".", "COMPRESS_ENABLED", ",", "'SITE_NAME'", ":", "settings", ".", "SITE_NAME", ",", "}", "for", "key", "in", "settings", ".", "ICEKIT_CO...
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
[ "Return", "COMPRESS_ENABLED", "SITE_NAME", "and", "any", "settings", "listed", "in", "ICEKIT_CONTEXT_PROCESSOR_SETTINGS", "as", "context", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/project/context_processors.py#L4-L15
train
33,459
ic-labs/django-icekit
icekit/publishing/monkey_patches.py
get_proxy_ancestor_classes
def get_proxy_ancestor_classes(klass): """ Return a set containing all the proxy model classes that are ancestors of the given class. NOTE: This implementation is for Django 1.7, it might need to work differently for other versions especially 1.8+. """ proxy_ancestor_classes = set() for superclass in klass.__bases__: if hasattr(superclass, '_meta') and superclass._meta.proxy: proxy_ancestor_classes.add(superclass) proxy_ancestor_classes.update( get_proxy_ancestor_classes(superclass)) return proxy_ancestor_classes
python
def get_proxy_ancestor_classes(klass): """ Return a set containing all the proxy model classes that are ancestors of the given class. NOTE: This implementation is for Django 1.7, it might need to work differently for other versions especially 1.8+. """ proxy_ancestor_classes = set() for superclass in klass.__bases__: if hasattr(superclass, '_meta') and superclass._meta.proxy: proxy_ancestor_classes.add(superclass) proxy_ancestor_classes.update( get_proxy_ancestor_classes(superclass)) return proxy_ancestor_classes
[ "def", "get_proxy_ancestor_classes", "(", "klass", ")", ":", "proxy_ancestor_classes", "=", "set", "(", ")", "for", "superclass", "in", "klass", ".", "__bases__", ":", "if", "hasattr", "(", "superclass", ",", "'_meta'", ")", "and", "superclass", ".", "_meta", ...
Return a set containing all the proxy model classes that are ancestors of the given class. NOTE: This implementation is for Django 1.7, it might need to work differently for other versions especially 1.8+.
[ "Return", "a", "set", "containing", "all", "the", "proxy", "model", "classes", "that", "are", "ancestors", "of", "the", "given", "class", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/monkey_patches.py#L186-L200
train
33,460
ic-labs/django-icekit
glamkit_collections/contrib/work_creator/plugins/person/models.py
PersonCreator.derive_and_set_name_fields_and_slug
def derive_and_set_name_fields_and_slug( self, set_name_sort=True, set_slug=True ): """ Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()` """ super(PersonCreator, self).derive_and_set_name_fields_and_slug( set_name_sort=False, set_slug=False) # Collect person name fields, but only if they are not empty person_names = [ name for name in [self.name_family, self.name_given] if not is_empty(name) ] # if empty, set `name_sort` = '{name_family}, {name_given}' if these # person name values are available otherwise `name_full` if set_name_sort and is_empty(self.name_sort): if person_names: self.name_sort = ', '.join(person_names) else: self.name_sort = self.name_full # if empty, set `slug` to slugified '{name_family} {name_given}' if # these person name values are available otherwise slugified # `name_full` if set_slug and is_empty(self.slug): if person_names: self.slug = slugify(' '.join(person_names)) else: self.slug = slugify(self.name_full)
python
def derive_and_set_name_fields_and_slug( self, set_name_sort=True, set_slug=True ): """ Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()` """ super(PersonCreator, self).derive_and_set_name_fields_and_slug( set_name_sort=False, set_slug=False) # Collect person name fields, but only if they are not empty person_names = [ name for name in [self.name_family, self.name_given] if not is_empty(name) ] # if empty, set `name_sort` = '{name_family}, {name_given}' if these # person name values are available otherwise `name_full` if set_name_sort and is_empty(self.name_sort): if person_names: self.name_sort = ', '.join(person_names) else: self.name_sort = self.name_full # if empty, set `slug` to slugified '{name_family} {name_given}' if # these person name values are available otherwise slugified # `name_full` if set_slug and is_empty(self.slug): if person_names: self.slug = slugify(' '.join(person_names)) else: self.slug = slugify(self.name_full)
[ "def", "derive_and_set_name_fields_and_slug", "(", "self", ",", "set_name_sort", "=", "True", ",", "set_slug", "=", "True", ")", ":", "super", "(", "PersonCreator", ",", "self", ")", ".", "derive_and_set_name_fields_and_slug", "(", "set_name_sort", "=", "False", "...
Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()`
[ "Override", "this", "method", "from", "CreatorBase", "to", "handle", "additional", "name", "fields", "for", "Person", "creators", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/glamkit_collections/contrib/work_creator/plugins/person/models.py#L93-L123
train
33,461
ic-labs/django-icekit
icekit/managers.py
LayoutQuerySet.for_model
def for_model(self, model, **kwargs): """ Return layouts that are allowed for the given model. """ queryset = self.filter( content_types=ContentType.objects.get_for_model(model), **kwargs ) return queryset
python
def for_model(self, model, **kwargs): """ Return layouts that are allowed for the given model. """ queryset = self.filter( content_types=ContentType.objects.get_for_model(model), **kwargs ) return queryset
[ "def", "for_model", "(", "self", ",", "model", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "self", ".", "filter", "(", "content_types", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "model", ")", ",", "*", "*", "kwargs", ")", ...
Return layouts that are allowed for the given model.
[ "Return", "layouts", "that", "are", "allowed", "for", "the", "given", "model", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/managers.py#L7-L15
train
33,462
ic-labs/django-icekit
icekit/publishing/managers.py
_order_by_pks
def _order_by_pks(qs, pks): """ Adjust the given queryset to order items according to the explicit ordering of PKs provided. This is a PostgreSQL-specific DB hack, based on: blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html """ pk_colname = '%s.%s' % ( qs.model._meta.db_table, qs.model._meta.pk.column) clauses = ' '.join( ['WHEN %s=%s THEN %s' % (pk_colname, pk, i) for i, pk in enumerate(pks)] ) ordering = 'CASE %s END' % clauses return qs.extra( select={'pk_ordering': ordering}, order_by=('pk_ordering',))
python
def _order_by_pks(qs, pks): """ Adjust the given queryset to order items according to the explicit ordering of PKs provided. This is a PostgreSQL-specific DB hack, based on: blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html """ pk_colname = '%s.%s' % ( qs.model._meta.db_table, qs.model._meta.pk.column) clauses = ' '.join( ['WHEN %s=%s THEN %s' % (pk_colname, pk, i) for i, pk in enumerate(pks)] ) ordering = 'CASE %s END' % clauses return qs.extra( select={'pk_ordering': ordering}, order_by=('pk_ordering',))
[ "def", "_order_by_pks", "(", "qs", ",", "pks", ")", ":", "pk_colname", "=", "'%s.%s'", "%", "(", "qs", ".", "model", ".", "_meta", ".", "db_table", ",", "qs", ".", "model", ".", "_meta", ".", "pk", ".", "column", ")", "clauses", "=", "' '", ".", ...
Adjust the given queryset to order items according to the explicit ordering of PKs provided. This is a PostgreSQL-specific DB hack, based on: blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
[ "Adjust", "the", "given", "queryset", "to", "order", "items", "according", "to", "the", "explicit", "ordering", "of", "PKs", "provided", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L169-L185
train
33,463
ic-labs/django-icekit
icekit/publishing/managers.py
_queryset_iterator
def _queryset_iterator(qs): """ Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added when all of: - the publishing middleware is active, and therefore able to report accurately whether the request is in a drafts-permitted context - the publishing middleware tells us we are not in a drafts-permitted context, which means only published items should be used. """ # Avoid double-processing draft items in our custom iterator when we # are in a `PublishingQuerySet` that is also a subclass of the # monkey-patched `UrlNodeQuerySet` if issubclass(type(qs), UrlNodeQuerySet): super_without_boobytrap_iterator = super(UrlNodeQuerySet, qs) else: super_without_boobytrap_iterator = super(PublishingQuerySet, qs) if is_publishing_middleware_active() \ and not is_draft_request_context(): for item in super_without_boobytrap_iterator.iterator(): if getattr(item, 'publishing_is_draft', False): yield DraftItemBoobyTrap(item) else: yield item else: for item in super_without_boobytrap_iterator.iterator(): yield item
python
def _queryset_iterator(qs): """ Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added when all of: - the publishing middleware is active, and therefore able to report accurately whether the request is in a drafts-permitted context - the publishing middleware tells us we are not in a drafts-permitted context, which means only published items should be used. """ # Avoid double-processing draft items in our custom iterator when we # are in a `PublishingQuerySet` that is also a subclass of the # monkey-patched `UrlNodeQuerySet` if issubclass(type(qs), UrlNodeQuerySet): super_without_boobytrap_iterator = super(UrlNodeQuerySet, qs) else: super_without_boobytrap_iterator = super(PublishingQuerySet, qs) if is_publishing_middleware_active() \ and not is_draft_request_context(): for item in super_without_boobytrap_iterator.iterator(): if getattr(item, 'publishing_is_draft', False): yield DraftItemBoobyTrap(item) else: yield item else: for item in super_without_boobytrap_iterator.iterator(): yield item
[ "def", "_queryset_iterator", "(", "qs", ")", ":", "# Avoid double-processing draft items in our custom iterator when we", "# are in a `PublishingQuerySet` that is also a subclass of the", "# monkey-patched `UrlNodeQuerySet`", "if", "issubclass", "(", "type", "(", "qs", ")", ",", "U...
Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added when all of: - the publishing middleware is active, and therefore able to report accurately whether the request is in a drafts-permitted context - the publishing middleware tells us we are not in a drafts-permitted context, which means only published items should be used.
[ "Override", "default", "iterator", "to", "wrap", "returned", "items", "in", "a", "publishing", "sanity", "-", "checker", "booby", "trap", "to", "lazily", "raise", "an", "exception", "if", "DRAFT", "items", "are", "mistakenly", "returned", "and", "mis", "-", ...
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L201-L233
train
33,464
ic-labs/django-icekit
icekit/publishing/managers.py
PublishingUrlNodeQuerySet.published
def published(self, for_user=UNSET, force_exchange=False): """ Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent. """ if for_user is not UNSET: return self.visible() queryset = super(PublishingUrlNodeQuerySet, self).published( for_user=for_user, force_exchange=force_exchange) # Exclude by publication date on the published version of items, *not* # the draft vesion, or we could get the wrong result. # Exclude fields of published copy of draft items, not draft itself... queryset = queryset.exclude( Q(publishing_is_draft=True) & Q( Q(publishing_linked__publication_date__gt=now()) | Q(publishing_linked__publication_end_date__lte=now()))) # ...and exclude fields directly on published items queryset = queryset.exclude( Q(publishing_is_draft=False) & Q( Q(publication_date__gt=now()) | Q(publication_end_date__lte=now()))) return queryset
python
def published(self, for_user=UNSET, force_exchange=False): """ Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent. """ if for_user is not UNSET: return self.visible() queryset = super(PublishingUrlNodeQuerySet, self).published( for_user=for_user, force_exchange=force_exchange) # Exclude by publication date on the published version of items, *not* # the draft vesion, or we could get the wrong result. # Exclude fields of published copy of draft items, not draft itself... queryset = queryset.exclude( Q(publishing_is_draft=True) & Q( Q(publishing_linked__publication_date__gt=now()) | Q(publishing_linked__publication_end_date__lte=now()))) # ...and exclude fields directly on published items queryset = queryset.exclude( Q(publishing_is_draft=False) & Q( Q(publication_date__gt=now()) | Q(publication_end_date__lte=now()))) return queryset
[ "def", "published", "(", "self", ",", "for_user", "=", "UNSET", ",", "force_exchange", "=", "False", ")", ":", "if", "for_user", "is", "not", "UNSET", ":", "return", "self", ".", "visible", "(", ")", "queryset", "=", "super", "(", "PublishingUrlNodeQuerySe...
Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent.
[ "Apply", "additional", "filtering", "of", "published", "items", "over", "that", "done", "in", "PublishingQuerySet", ".", "published", "to", "filter", "based", "on", "additional", "publising", "date", "fields", "used", "by", "Fluent", "." ]
c507ea5b1864303732c53ad7c5800571fca5fa94
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L342-L367
train
33,465
wikimedia/ores
ores/scoring_systems/celery_queue.py
redis_from_url
def redis_from_url(url): """ Converts a redis URL used by celery into a `redis.Redis` object. """ # Makes sure that we only try to import redis when we need # to use it import redis url = url or "" parsed_url = urlparse(url) if parsed_url.scheme != "redis": return None kwargs = {} match = PASS_HOST_PORT.match(parsed_url.netloc) if match.group('password') is not None: kwargs['password'] = match.group('password') if match.group('host') is not None: kwargs['host'] = match.group('host') if match.group('port') is not None: kwargs['port'] = int(match.group('port')) if len(parsed_url.path) > 1: # Removes "/" from the beginning kwargs['db'] = int(parsed_url.path[1:]) return redis.StrictRedis(**kwargs)
python
def redis_from_url(url): """ Converts a redis URL used by celery into a `redis.Redis` object. """ # Makes sure that we only try to import redis when we need # to use it import redis url = url or "" parsed_url = urlparse(url) if parsed_url.scheme != "redis": return None kwargs = {} match = PASS_HOST_PORT.match(parsed_url.netloc) if match.group('password') is not None: kwargs['password'] = match.group('password') if match.group('host') is not None: kwargs['host'] = match.group('host') if match.group('port') is not None: kwargs['port'] = int(match.group('port')) if len(parsed_url.path) > 1: # Removes "/" from the beginning kwargs['db'] = int(parsed_url.path[1:]) return redis.StrictRedis(**kwargs)
[ "def", "redis_from_url", "(", "url", ")", ":", "# Makes sure that we only try to import redis when we need", "# to use it", "import", "redis", "url", "=", "url", "or", "\"\"", "parsed_url", "=", "urlparse", "(", "url", ")", "if", "parsed_url", ".", "scheme", "!=", ...
Converts a redis URL used by celery into a `redis.Redis` object.
[ "Converts", "a", "redis", "URL", "used", "by", "celery", "into", "a", "redis", ".", "Redis", "object", "." ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_systems/celery_queue.py#L263-L289
train
33,466
wikimedia/ores
ores/scoring_context.py
ScoringContext.process_model_scores
def process_model_scores(self, model_names, root_cache, include_features=False): """ Generates a score map for a set of models based on a `root_cache`. This method performs no substantial IO, but may incur substantial CPU usage. :Parameters: model_names : `set` ( `str` ) A set of models to score root_cache : `dict` ( `str` --> `mixed` ) A cache of pre-computed root_dependencies for a specific revision. See `extract_root_dependency_caches()` include_features : `bool` If True, include a map of basic features used in scoring along with the model score. If False, just generate the scores. """ model_scores = {} for model_name in model_names: model_scores[model_name] = {} # Mostly CPU model_scores[model_name]['score'] = \ self._process_score(model_name, dependency_cache=root_cache) # Essentially free if include_features: base_feature_map = self._solve_base_feature_map( model_name, dependency_cache=root_cache) model_scores[model_name]['features'] = base_feature_map return model_scores
python
def process_model_scores(self, model_names, root_cache, include_features=False): """ Generates a score map for a set of models based on a `root_cache`. This method performs no substantial IO, but may incur substantial CPU usage. :Parameters: model_names : `set` ( `str` ) A set of models to score root_cache : `dict` ( `str` --> `mixed` ) A cache of pre-computed root_dependencies for a specific revision. See `extract_root_dependency_caches()` include_features : `bool` If True, include a map of basic features used in scoring along with the model score. If False, just generate the scores. """ model_scores = {} for model_name in model_names: model_scores[model_name] = {} # Mostly CPU model_scores[model_name]['score'] = \ self._process_score(model_name, dependency_cache=root_cache) # Essentially free if include_features: base_feature_map = self._solve_base_feature_map( model_name, dependency_cache=root_cache) model_scores[model_name]['features'] = base_feature_map return model_scores
[ "def", "process_model_scores", "(", "self", ",", "model_names", ",", "root_cache", ",", "include_features", "=", "False", ")", ":", "model_scores", "=", "{", "}", "for", "model_name", "in", "model_names", ":", "model_scores", "[", "model_name", "]", "=", "{", ...
Generates a score map for a set of models based on a `root_cache`. This method performs no substantial IO, but may incur substantial CPU usage. :Parameters: model_names : `set` ( `str` ) A set of models to score root_cache : `dict` ( `str` --> `mixed` ) A cache of pre-computed root_dependencies for a specific revision. See `extract_root_dependency_caches()` include_features : `bool` If True, include a map of basic features used in scoring along with the model score. If False, just generate the scores.
[ "Generates", "a", "score", "map", "for", "a", "set", "of", "models", "based", "on", "a", "root_cache", ".", "This", "method", "performs", "no", "substantial", "IO", "but", "may", "incur", "substantial", "CPU", "usage", "." ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L61-L93
train
33,467
wikimedia/ores
ores/scoring_context.py
ScoringContext._process_score
def _process_score(self, model_name, dependency_cache=None): """ Generates a score for a given model using the `dependency_cache`. """ version = self[model_name].version start = time.time() feature_values = self._solve_features(model_name, dependency_cache) logger.debug("Extracted features for {0}:{1}:{2} in {3} secs" .format(self.name, model_name, version, round(time.time() - start, 3))) start = time.time() score = self[model_name].score(feature_values) logger.debug("Scored features for {0}:{1}:{2} in {3} secs" .format(self.name, model_name, version, round(time.time() - start, 3))) return score
python
def _process_score(self, model_name, dependency_cache=None): """ Generates a score for a given model using the `dependency_cache`. """ version = self[model_name].version start = time.time() feature_values = self._solve_features(model_name, dependency_cache) logger.debug("Extracted features for {0}:{1}:{2} in {3} secs" .format(self.name, model_name, version, round(time.time() - start, 3))) start = time.time() score = self[model_name].score(feature_values) logger.debug("Scored features for {0}:{1}:{2} in {3} secs" .format(self.name, model_name, version, round(time.time() - start, 3))) return score
[ "def", "_process_score", "(", "self", ",", "model_name", ",", "dependency_cache", "=", "None", ")", ":", "version", "=", "self", "[", "model_name", "]", ".", "version", "start", "=", "time", ".", "time", "(", ")", "feature_values", "=", "self", ".", "_so...
Generates a score for a given model using the `dependency_cache`.
[ "Generates", "a", "score", "for", "a", "given", "model", "using", "the", "dependency_cache", "." ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L114-L132
train
33,468
wikimedia/ores
ores/scoring_context.py
ScoringContext.map_from_config
def map_from_config(cls, config, context_names, section_key="scoring_contexts"): """ Loads a whole set of ScoringContext's from a configuration file while maintaining a cache of model names. This aids in better memory management and allows model aliases to be implemented at the configuration level. :Returns: A map of context_names and ScoringContext's where models are loaded once and reused cross contexts. """ model_key_map = {} context_map = {} for context_name in context_names: section = config[section_key][context_name] model_map = {} for model_name, key in section['scorer_models'].items(): if key in model_key_map: scorer_model = model_key_map[key] else: scorer_model = Model.from_config(config, key) model_key_map[key] = scorer_model model_map[model_name] = scorer_model extractor = Extractor.from_config(config, section['extractor']) context_map[context_name] = cls( context_name, model_map=model_map, extractor=extractor) return context_map
python
def map_from_config(cls, config, context_names, section_key="scoring_contexts"): """ Loads a whole set of ScoringContext's from a configuration file while maintaining a cache of model names. This aids in better memory management and allows model aliases to be implemented at the configuration level. :Returns: A map of context_names and ScoringContext's where models are loaded once and reused cross contexts. """ model_key_map = {} context_map = {} for context_name in context_names: section = config[section_key][context_name] model_map = {} for model_name, key in section['scorer_models'].items(): if key in model_key_map: scorer_model = model_key_map[key] else: scorer_model = Model.from_config(config, key) model_key_map[key] = scorer_model model_map[model_name] = scorer_model extractor = Extractor.from_config(config, section['extractor']) context_map[context_name] = cls( context_name, model_map=model_map, extractor=extractor) return context_map
[ "def", "map_from_config", "(", "cls", ",", "config", ",", "context_names", ",", "section_key", "=", "\"scoring_contexts\"", ")", ":", "model_key_map", "=", "{", "}", "context_map", "=", "{", "}", "for", "context_name", "in", "context_names", ":", "section", "=...
Loads a whole set of ScoringContext's from a configuration file while maintaining a cache of model names. This aids in better memory management and allows model aliases to be implemented at the configuration level. :Returns: A map of context_names and ScoringContext's where models are loaded once and reused cross contexts.
[ "Loads", "a", "whole", "set", "of", "ScoringContext", "s", "from", "a", "configuration", "file", "while", "maintaining", "a", "cache", "of", "model", "names", ".", "This", "aids", "in", "better", "memory", "management", "and", "allows", "model", "aliases", "...
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L186-L216
train
33,469
wikimedia/ores
ores/wsgi/util.py
build_event_set
def build_event_set(event): """ Turn an EventStream event into a set of event types that ORES uses internally. """ event_set = set() if re.match(r"([^\.]+.)?mediawiki\.revision-create$", event['meta']['topic']): event_set.add('edit') user_groups = event.get('performer', {}).get('user_groups', []) if 'bot' in user_groups: event_set.add('bot_edit') else: event_set.add('nonbot_edit') if not event.get('rev_parent_id'): event_set.add('page_creation') if 'bot' in user_groups: event_set.add('bot_page_creation') else: event_set.add('nonbot_page_creation') return event_set
python
def build_event_set(event): """ Turn an EventStream event into a set of event types that ORES uses internally. """ event_set = set() if re.match(r"([^\.]+.)?mediawiki\.revision-create$", event['meta']['topic']): event_set.add('edit') user_groups = event.get('performer', {}).get('user_groups', []) if 'bot' in user_groups: event_set.add('bot_edit') else: event_set.add('nonbot_edit') if not event.get('rev_parent_id'): event_set.add('page_creation') if 'bot' in user_groups: event_set.add('bot_page_creation') else: event_set.add('nonbot_page_creation') return event_set
[ "def", "build_event_set", "(", "event", ")", ":", "event_set", "=", "set", "(", ")", "if", "re", ".", "match", "(", "r\"([^\\.]+.)?mediawiki\\.revision-create$\"", ",", "event", "[", "'meta'", "]", "[", "'topic'", "]", ")", ":", "event_set", ".", "add", "(...
Turn an EventStream event into a set of event types that ORES uses internally.
[ "Turn", "an", "EventStream", "event", "into", "a", "set", "of", "event", "types", "that", "ORES", "uses", "internally", "." ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/wsgi/util.py#L179-L202
train
33,470
wikimedia/ores
ores/wsgi/util.py
build_precache_map
def build_precache_map(config): """ Build a mapping of contexts and models from the configuration """ precache_map = {} ss_name = config['ores']['scoring_system'] for context in config['scoring_systems'][ss_name]['scoring_contexts']: precache_map[context] = {} for model in config['scoring_contexts'][context].get('precache', []): precached_config = \ config['scoring_contexts'][context]['precache'][model] events = precached_config['on'] if len(set(events) - AVAILABLE_EVENTS) > 0: logger.warning("{0} events are not available" .format(set(events) - AVAILABLE_EVENTS)) for event in precached_config['on']: if event in precache_map[context]: precache_map[context][event].add(model) else: precache_map[context][event] = {model} logger.debug("Setting up precaching for {0} in {1} on {2}" .format(model, context, event)) return precache_map
python
def build_precache_map(config): """ Build a mapping of contexts and models from the configuration """ precache_map = {} ss_name = config['ores']['scoring_system'] for context in config['scoring_systems'][ss_name]['scoring_contexts']: precache_map[context] = {} for model in config['scoring_contexts'][context].get('precache', []): precached_config = \ config['scoring_contexts'][context]['precache'][model] events = precached_config['on'] if len(set(events) - AVAILABLE_EVENTS) > 0: logger.warning("{0} events are not available" .format(set(events) - AVAILABLE_EVENTS)) for event in precached_config['on']: if event in precache_map[context]: precache_map[context][event].add(model) else: precache_map[context][event] = {model} logger.debug("Setting up precaching for {0} in {1} on {2}" .format(model, context, event)) return precache_map
[ "def", "build_precache_map", "(", "config", ")", ":", "precache_map", "=", "{", "}", "ss_name", "=", "config", "[", "'ores'", "]", "[", "'scoring_system'", "]", "for", "context", "in", "config", "[", "'scoring_systems'", "]", "[", "ss_name", "]", "[", "'sc...
Build a mapping of contexts and models from the configuration
[ "Build", "a", "mapping", "of", "contexts", "and", "models", "from", "the", "configuration" ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/wsgi/util.py#L209-L233
train
33,471
wikimedia/ores
ores/scoring/models/rev_id_scorer.py
RevIdScorer.calculate_statistics
def calculate_statistics(self): "Jam some data through to generate statistics" rev_ids = range(0, 100, 1) feature_values = zip(rev_ids, [0] * 100) scores = [self.score(f) for f in feature_values] labels = [s['prediction'] for s in scores] statistics = Classification(labels, threshold_ndigits=1, decision_key='probability') score_labels = list(zip(scores, labels)) statistics.fit(score_labels) return statistics
python
def calculate_statistics(self): "Jam some data through to generate statistics" rev_ids = range(0, 100, 1) feature_values = zip(rev_ids, [0] * 100) scores = [self.score(f) for f in feature_values] labels = [s['prediction'] for s in scores] statistics = Classification(labels, threshold_ndigits=1, decision_key='probability') score_labels = list(zip(scores, labels)) statistics.fit(score_labels) return statistics
[ "def", "calculate_statistics", "(", "self", ")", ":", "rev_ids", "=", "range", "(", "0", ",", "100", ",", "1", ")", "feature_values", "=", "zip", "(", "rev_ids", ",", "[", "0", "]", "*", "100", ")", "scores", "=", "[", "self", ".", "score", "(", ...
Jam some data through to generate statistics
[ "Jam", "some", "data", "through", "to", "generate", "statistics" ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring/models/rev_id_scorer.py#L67-L76
train
33,472
openclimatedata/pyhector
pyhector/__init__.py
read_hector_input
def read_hector_input(csv_file): """ Reads a Hector CSV file and returns it as a Pandas DataFrame. """ df = pd.read_csv(csv_file, skiprows=3, index_col=0) df.name = os.path.splitext(os.path.basename(csv_file))[0] return df
python
def read_hector_input(csv_file): """ Reads a Hector CSV file and returns it as a Pandas DataFrame. """ df = pd.read_csv(csv_file, skiprows=3, index_col=0) df.name = os.path.splitext(os.path.basename(csv_file))[0] return df
[ "def", "read_hector_input", "(", "csv_file", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "csv_file", ",", "skiprows", "=", "3", ",", "index_col", "=", "0", ")", "df", ".", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path"...
Reads a Hector CSV file and returns it as a Pandas DataFrame.
[ "Reads", "a", "Hector", "CSV", "file", "and", "returns", "it", "as", "a", "Pandas", "DataFrame", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L97-L103
train
33,473
openclimatedata/pyhector
pyhector/__init__.py
write_hector_input
def write_hector_input(scenario, path=None): """ Writes a scenario DataFrame to a CSV emissions file as used in Hector. Parameters ---------- scenario : DataFrame DataFrame with emissions. path: file-like object or path Returns ------- out : str If no path is given a String of the output is returned. """ # Output header format: # ; Scenario name # ; Generated with pyhector # ;UNITS: GtC/yr GtC/yr [...] # Date ffi_emissions luc_emissions [...] out = "" try: name = "; " + scenario.name + "\n" except AttributeError: name = "; Hector Scenario\n" out += name out += "; Written with pyhector\n" unit_names = [units[source] for source in scenario.columns] out += ";UNITS:," + ",".join(unit_names) + "\n" out += scenario.to_csv() if isinstance(path, str): f = open(path, "w") elif path is None: return out else: f = path f.write(out) if hasattr(f, "close"): f.close() return None
python
def write_hector_input(scenario, path=None): """ Writes a scenario DataFrame to a CSV emissions file as used in Hector. Parameters ---------- scenario : DataFrame DataFrame with emissions. path: file-like object or path Returns ------- out : str If no path is given a String of the output is returned. """ # Output header format: # ; Scenario name # ; Generated with pyhector # ;UNITS: GtC/yr GtC/yr [...] # Date ffi_emissions luc_emissions [...] out = "" try: name = "; " + scenario.name + "\n" except AttributeError: name = "; Hector Scenario\n" out += name out += "; Written with pyhector\n" unit_names = [units[source] for source in scenario.columns] out += ";UNITS:," + ",".join(unit_names) + "\n" out += scenario.to_csv() if isinstance(path, str): f = open(path, "w") elif path is None: return out else: f = path f.write(out) if hasattr(f, "close"): f.close() return None
[ "def", "write_hector_input", "(", "scenario", ",", "path", "=", "None", ")", ":", "# Output header format:", "# ; Scenario name", "# ; Generated with pyhector", "# ;UNITS: GtC/yr GtC/yr [...]", "# Date ffi_emissions luc_emissions [...]", "out", "=", "\"\"", "try", ":"...
Writes a scenario DataFrame to a CSV emissions file as used in Hector. Parameters ---------- scenario : DataFrame DataFrame with emissions. path: file-like object or path Returns ------- out : str If no path is given a String of the output is returned.
[ "Writes", "a", "scenario", "DataFrame", "to", "a", "CSV", "emissions", "file", "as", "used", "in", "Hector", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L106-L149
train
33,474
openclimatedata/pyhector
pyhector/__init__.py
read_hector_constraint
def read_hector_constraint(constraint_file): """ Reads a Hector contraint CSV file and returns it as a Pandas Series """ df = pd.read_csv(constraint_file, index_col=0, comment=";") df = df[df.applymap(lambda x: isinstance(x, (int, float)))] df.index = df.index.astype(int) return df.iloc[:, 0]
python
def read_hector_constraint(constraint_file): """ Reads a Hector contraint CSV file and returns it as a Pandas Series """ df = pd.read_csv(constraint_file, index_col=0, comment=";") df = df[df.applymap(lambda x: isinstance(x, (int, float)))] df.index = df.index.astype(int) return df.iloc[:, 0]
[ "def", "read_hector_constraint", "(", "constraint_file", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "constraint_file", ",", "index_col", "=", "0", ",", "comment", "=", "\";\"", ")", "df", "=", "df", "[", "df", ".", "applymap", "(", "lambda", "x", ...
Reads a Hector contraint CSV file and returns it as a Pandas Series
[ "Reads", "a", "Hector", "contraint", "CSV", "file", "and", "returns", "it", "as", "a", "Pandas", "Series" ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L152-L159
train
33,475
openclimatedata/pyhector
pyhector/__init__.py
read_hector_output
def read_hector_output(csv_file): """ Reads a Hector output stream CSV file and returns a wide DataFrame with Hector output data. """ # Filter out spin-up values. In Hector 1.x RCP output streams years are # given as end of simulation year. # See https://github.com/JGCRI/hector/issues/177 start_year = 1746 output_stream = pd.read_csv(csv_file, skiprows=1) wide = output_stream[output_stream.year >= start_year].pivot_table( index="year", columns="variable", values="value" ) return wide
python
def read_hector_output(csv_file): """ Reads a Hector output stream CSV file and returns a wide DataFrame with Hector output data. """ # Filter out spin-up values. In Hector 1.x RCP output streams years are # given as end of simulation year. # See https://github.com/JGCRI/hector/issues/177 start_year = 1746 output_stream = pd.read_csv(csv_file, skiprows=1) wide = output_stream[output_stream.year >= start_year].pivot_table( index="year", columns="variable", values="value" ) return wide
[ "def", "read_hector_output", "(", "csv_file", ")", ":", "# Filter out spin-up values. In Hector 1.x RCP output streams years are", "# given as end of simulation year.", "# See https://github.com/JGCRI/hector/issues/177", "start_year", "=", "1746", "output_stream", "=", "pd", ".", "re...
Reads a Hector output stream CSV file and returns a wide DataFrame with Hector output data.
[ "Reads", "a", "Hector", "output", "stream", "CSV", "file", "and", "returns", "a", "wide", "DataFrame", "with", "Hector", "output", "data", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L162-L177
train
33,476
openclimatedata/pyhector
pyhector/__init__.py
run
def run(scenario, config=None, base_config=None, outputs=None, return_config=False): """ Runs a scenario through the Hector climate model. Parameters ---------- scenario : DataFrame DataFrame with emissions. See ``pyhector.rcp26`` for an example and :mod:`pyhector.units` for units of emissions values. config : dictionary, default ``None`` Additional config options that overwrite the base config. base_config : dictionary Base config to use. If None uses Hector's default config. Values in config override values in base_config. default None outputs : array_like List of requested output variables as strings. if set to "all" returns all available variables. Defaults to global temperature, CO2 concentration and forcing. A full list is in :py:data:`variables`. return_config : boolean Additionaly return the full config used from adding ``config`` values to ``base_config``. default False Returns ------- DataFrame Pandas DataFrame with results in the columns requested in ``outputs``. dictionary, optional When ``return_config`` is set to True results and parameters are returned as a tuple. """ if outputs is None: outputs = ["temperature.Tgav", "simpleNbox.Ca", "forcing.Ftot"] if base_config is None: parameters = deepcopy(_default_config) else: parameters = deepcopy(base_config) if config: for key, data in config.items(): for option, value in data.items(): parameters[key][option] = value with Hector() as h: h.config(parameters) h.set_emissions(scenario) if outputs == "all": outputs = output.keys() for name in outputs: h.add_observable( output[name]["component"], output[name]["variable"], output[name].get("needs_date", False), ) h.run() results = {} for name in outputs: results[name] = h.get_observable( output[name]["component"], output[name]["variable"] ) # In Hector 1.x output value years are given as end of simulation # year, e.g. 1745-12-31 = 1746.0. # See https://github.com/JGCRI/hector/issues/177 start = int(parameters["core"]["startDate"]) + 1 # End of range is non-inclusive in Python ranges. end = int(parameters["core"]["endDate"]) + 1 index = np.arange(start, end) results = pd.DataFrame(results, index=index) if return_config: return results, parameters return results
python
def run(scenario, config=None, base_config=None, outputs=None, return_config=False): """ Runs a scenario through the Hector climate model. Parameters ---------- scenario : DataFrame DataFrame with emissions. See ``pyhector.rcp26`` for an example and :mod:`pyhector.units` for units of emissions values. config : dictionary, default ``None`` Additional config options that overwrite the base config. base_config : dictionary Base config to use. If None uses Hector's default config. Values in config override values in base_config. default None outputs : array_like List of requested output variables as strings. if set to "all" returns all available variables. Defaults to global temperature, CO2 concentration and forcing. A full list is in :py:data:`variables`. return_config : boolean Additionaly return the full config used from adding ``config`` values to ``base_config``. default False Returns ------- DataFrame Pandas DataFrame with results in the columns requested in ``outputs``. dictionary, optional When ``return_config`` is set to True results and parameters are returned as a tuple. """ if outputs is None: outputs = ["temperature.Tgav", "simpleNbox.Ca", "forcing.Ftot"] if base_config is None: parameters = deepcopy(_default_config) else: parameters = deepcopy(base_config) if config: for key, data in config.items(): for option, value in data.items(): parameters[key][option] = value with Hector() as h: h.config(parameters) h.set_emissions(scenario) if outputs == "all": outputs = output.keys() for name in outputs: h.add_observable( output[name]["component"], output[name]["variable"], output[name].get("needs_date", False), ) h.run() results = {} for name in outputs: results[name] = h.get_observable( output[name]["component"], output[name]["variable"] ) # In Hector 1.x output value years are given as end of simulation # year, e.g. 1745-12-31 = 1746.0. # See https://github.com/JGCRI/hector/issues/177 start = int(parameters["core"]["startDate"]) + 1 # End of range is non-inclusive in Python ranges. end = int(parameters["core"]["endDate"]) + 1 index = np.arange(start, end) results = pd.DataFrame(results, index=index) if return_config: return results, parameters return results
[ "def", "run", "(", "scenario", ",", "config", "=", "None", ",", "base_config", "=", "None", ",", "outputs", "=", "None", ",", "return_config", "=", "False", ")", ":", "if", "outputs", "is", "None", ":", "outputs", "=", "[", "\"temperature.Tgav\"", ",", ...
Runs a scenario through the Hector climate model. Parameters ---------- scenario : DataFrame DataFrame with emissions. See ``pyhector.rcp26`` for an example and :mod:`pyhector.units` for units of emissions values. config : dictionary, default ``None`` Additional config options that overwrite the base config. base_config : dictionary Base config to use. If None uses Hector's default config. Values in config override values in base_config. default None outputs : array_like List of requested output variables as strings. if set to "all" returns all available variables. Defaults to global temperature, CO2 concentration and forcing. A full list is in :py:data:`variables`. return_config : boolean Additionaly return the full config used from adding ``config`` values to ``base_config``. default False Returns ------- DataFrame Pandas DataFrame with results in the columns requested in ``outputs``. dictionary, optional When ``return_config`` is set to True results and parameters are returned as a tuple.
[ "Runs", "a", "scenario", "through", "the", "Hector", "climate", "model", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L195-L265
train
33,477
openclimatedata/pyhector
pyhector/__init__.py
Hector.config
def config(self, config): """Set config values from config dictionary.""" for section, data in config.items(): for variable, value in data.items(): self.set_value(section, variable, value)
python
def config(self, config): """Set config values from config dictionary.""" for section, data in config.items(): for variable, value in data.items(): self.set_value(section, variable, value)
[ "def", "config", "(", "self", ",", "config", ")", ":", "for", "section", ",", "data", "in", "config", ".", "items", "(", ")", ":", "for", "variable", ",", "value", "in", "data", ".", "items", "(", ")", ":", "self", ".", "set_value", "(", "section",...
Set config values from config dictionary.
[ "Set", "config", "values", "from", "config", "dictionary", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L80-L84
train
33,478
openclimatedata/pyhector
pyhector/__init__.py
Hector.set_emissions
def set_emissions(self, scenario): """Set emissions from Pandas DataFrame.""" for section in emissions: for source in emissions[section]: if source not in scenario.columns: continue self._set_timed_array( section, source, list(scenario.index), list(scenario[source]) )
python
def set_emissions(self, scenario): """Set emissions from Pandas DataFrame.""" for section in emissions: for source in emissions[section]: if source not in scenario.columns: continue self._set_timed_array( section, source, list(scenario.index), list(scenario[source]) )
[ "def", "set_emissions", "(", "self", ",", "scenario", ")", ":", "for", "section", "in", "emissions", ":", "for", "source", "in", "emissions", "[", "section", "]", ":", "if", "source", "not", "in", "scenario", ".", "columns", ":", "continue", "self", ".",...
Set emissions from Pandas DataFrame.
[ "Set", "emissions", "from", "Pandas", "DataFrame", "." ]
1649efcc0ed19dc66d8de8dec7a5105fa08df01a
https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L86-L94
train
33,479
wikimedia/ores
setup.py
requirements
def requirements(fname): """ Generator to parse requirements.txt file Supports bits of extended pip format (git urls) """ with open(fname) as f: for line in f: match = re.search('#egg=(.*)$', line) if match: yield match.groups()[0] else: yield line.strip()
python
def requirements(fname): """ Generator to parse requirements.txt file Supports bits of extended pip format (git urls) """ with open(fname) as f: for line in f: match = re.search('#egg=(.*)$', line) if match: yield match.groups()[0] else: yield line.strip()
[ "def", "requirements", "(", "fname", ")", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "for", "line", "in", "f", ":", "match", "=", "re", ".", "search", "(", "'#egg=(.*)$'", ",", "line", ")", "if", "match", ":", "yield", "match", ".", ...
Generator to parse requirements.txt file Supports bits of extended pip format (git urls)
[ "Generator", "to", "parse", "requirements", ".", "txt", "file" ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/setup.py#L20-L32
train
33,480
wikimedia/ores
ores/api.py
Session.score
def score(self, context, models, revids): """ Genetate scores for model applied to a sequence of revisions. :Parameters: context : str The name of the context -- usually the database name of a wiki models : `iterable` The names of a models to apply revids : `iterable` A sequence of revision IDs to score. """ if isinstance(revids, int): rev_ids = [revids] else: rev_ids = [int(rid) for rid in revids] return self._score(context, models, rev_ids)
python
def score(self, context, models, revids): """ Genetate scores for model applied to a sequence of revisions. :Parameters: context : str The name of the context -- usually the database name of a wiki models : `iterable` The names of a models to apply revids : `iterable` A sequence of revision IDs to score. """ if isinstance(revids, int): rev_ids = [revids] else: rev_ids = [int(rid) for rid in revids] return self._score(context, models, rev_ids)
[ "def", "score", "(", "self", ",", "context", ",", "models", ",", "revids", ")", ":", "if", "isinstance", "(", "revids", ",", "int", ")", ":", "rev_ids", "=", "[", "revids", "]", "else", ":", "rev_ids", "=", "[", "int", "(", "rid", ")", "for", "ri...
Genetate scores for model applied to a sequence of revisions. :Parameters: context : str The name of the context -- usually the database name of a wiki models : `iterable` The names of a models to apply revids : `iterable` A sequence of revision IDs to score.
[ "Genetate", "scores", "for", "model", "applied", "to", "a", "sequence", "of", "revisions", "." ]
75599b6ba0172c86d94f7f7e1e05a3c282333a18
https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/api.py#L68-L85
train
33,481
mattjj/pybasicbayes
examples/factor_analysis.py
principal_angle
def principal_angle(A,B): """ Find the principal angle between two subspaces spanned by columns of A and B """ from numpy.linalg import qr, svd qA, _ = qr(A) qB, _ = qr(B) U,S,V = svd(qA.T.dot(qB)) return np.arccos(min(S.min(), 1.0))
python
def principal_angle(A,B): """ Find the principal angle between two subspaces spanned by columns of A and B """ from numpy.linalg import qr, svd qA, _ = qr(A) qB, _ = qr(B) U,S,V = svd(qA.T.dot(qB)) return np.arccos(min(S.min(), 1.0))
[ "def", "principal_angle", "(", "A", ",", "B", ")", ":", "from", "numpy", ".", "linalg", "import", "qr", ",", "svd", "qA", ",", "_", "=", "qr", "(", "A", ")", "qB", ",", "_", "=", "qr", "(", "B", ")", "U", ",", "S", ",", "V", "=", "svd", "...
Find the principal angle between two subspaces spanned by columns of A and B
[ "Find", "the", "principal", "angle", "between", "two", "subspaces", "spanned", "by", "columns", "of", "A", "and", "B" ]
76aef00f011415cc5c858cd1a101f3aab971a62d
https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/examples/factor_analysis.py#L15-L24
train
33,482
mattjj/pybasicbayes
pybasicbayes/distributions/regression.py
DiagonalRegression.resample
def resample(self, data, stats=None, mask=None, niter=None): """ Introduce a mask that allows for missing data """ stats = self._get_statistics(data, mask=mask) if stats is None else stats stats = self._stats_ensure_array(stats) niter = niter if niter else self.niter for itr in range(niter): self._resample_A(stats) self._resample_sigma(stats)
python
def resample(self, data, stats=None, mask=None, niter=None): """ Introduce a mask that allows for missing data """ stats = self._get_statistics(data, mask=mask) if stats is None else stats stats = self._stats_ensure_array(stats) niter = niter if niter else self.niter for itr in range(niter): self._resample_A(stats) self._resample_sigma(stats)
[ "def", "resample", "(", "self", ",", "data", ",", "stats", "=", "None", ",", "mask", "=", "None", ",", "niter", "=", "None", ")", ":", "stats", "=", "self", ".", "_get_statistics", "(", "data", ",", "mask", "=", "mask", ")", "if", "stats", "is", ...
Introduce a mask that allows for missing data
[ "Introduce", "a", "mask", "that", "allows", "for", "missing", "data" ]
76aef00f011415cc5c858cd1a101f3aab971a62d
https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/distributions/regression.py#L734-L744
train
33,483
mattjj/pybasicbayes
pybasicbayes/util/stats.py
sample_truncated_gaussian
def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf): """ Sample a truncated normal with the specified params. This is not the most stable way but it works as long as the truncation region is not too far from the mean. """ # Broadcast arrays to be of the same shape mu, sigma, lb, ub = np.broadcast_arrays(mu, sigma, lb, ub) shp = mu.shape if np.allclose(sigma, 0.0): return mu cdflb = normal_cdf(lb, mu, sigma) cdfub = normal_cdf(ub, mu, sigma) # Sample uniformly from the CDF cdfsamples = cdflb + np.random.rand(*shp) * (cdfub-cdflb) # Clip the CDF samples so that we can invert them cdfsamples = np.clip(cdfsamples, 1e-15, 1-1e-15) zs = -np.sqrt(2) * special.erfcinv(2 * cdfsamples) # Transform the standard normal samples xs = sigma * zs + mu xs = np.clip(xs, lb, ub) return xs
python
def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf): """ Sample a truncated normal with the specified params. This is not the most stable way but it works as long as the truncation region is not too far from the mean. """ # Broadcast arrays to be of the same shape mu, sigma, lb, ub = np.broadcast_arrays(mu, sigma, lb, ub) shp = mu.shape if np.allclose(sigma, 0.0): return mu cdflb = normal_cdf(lb, mu, sigma) cdfub = normal_cdf(ub, mu, sigma) # Sample uniformly from the CDF cdfsamples = cdflb + np.random.rand(*shp) * (cdfub-cdflb) # Clip the CDF samples so that we can invert them cdfsamples = np.clip(cdfsamples, 1e-15, 1-1e-15) zs = -np.sqrt(2) * special.erfcinv(2 * cdfsamples) # Transform the standard normal samples xs = sigma * zs + mu xs = np.clip(xs, lb, ub) return xs
[ "def", "sample_truncated_gaussian", "(", "mu", "=", "0", ",", "sigma", "=", "1", ",", "lb", "=", "-", "np", ".", "Inf", ",", "ub", "=", "np", ".", "Inf", ")", ":", "# Broadcast arrays to be of the same shape", "mu", ",", "sigma", ",", "lb", ",", "ub", ...
Sample a truncated normal with the specified params. This is not the most stable way but it works as long as the truncation region is not too far from the mean.
[ "Sample", "a", "truncated", "normal", "with", "the", "specified", "params", ".", "This", "is", "not", "the", "most", "stable", "way", "but", "it", "works", "as", "long", "as", "the", "truncation", "region", "is", "not", "too", "far", "from", "the", "mean...
76aef00f011415cc5c858cd1a101f3aab971a62d
https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/util/stats.py#L124-L150
train
33,484
mattjj/pybasicbayes
pybasicbayes/models/mixture.py
CRPMixture.log_likelihood
def log_likelihood(self,x, K_extra=1): """ Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model. """ x = np.asarray(x) ks = self._get_occupied() K = len(ks) K_total = K + K_extra # Sample observation distributions given current labels obs_distns = [] for k in range(K): o = copy.deepcopy(self.obs_distn) o.resample(data=self._get_data_withlabel(k)) obs_distns.append(o) # Sample extra observation distributions from prior for k in range(K_extra): o = copy.deepcopy(self.obs_distn) o.resample() obs_distns.append(o) # Sample a set of weights weights = Categorical(alpha_0=self.alpha_0, K=K_total, weights=None) assert len(self.labels_list) == 1 weights.resample(data=self.labels_list[0].z) # Now compute the log likelihood vals = np.empty((x.shape[0],K_total)) for k in range(K_total): vals[:,k] = obs_distns[k].log_likelihood(x) vals += weights.log_likelihood(np.arange(K_total)) assert not np.isnan(vals).any() return logsumexp(vals,axis=1).sum()
python
def log_likelihood(self,x, K_extra=1): """ Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model. """ x = np.asarray(x) ks = self._get_occupied() K = len(ks) K_total = K + K_extra # Sample observation distributions given current labels obs_distns = [] for k in range(K): o = copy.deepcopy(self.obs_distn) o.resample(data=self._get_data_withlabel(k)) obs_distns.append(o) # Sample extra observation distributions from prior for k in range(K_extra): o = copy.deepcopy(self.obs_distn) o.resample() obs_distns.append(o) # Sample a set of weights weights = Categorical(alpha_0=self.alpha_0, K=K_total, weights=None) assert len(self.labels_list) == 1 weights.resample(data=self.labels_list[0].z) # Now compute the log likelihood vals = np.empty((x.shape[0],K_total)) for k in range(K_total): vals[:,k] = obs_distns[k].log_likelihood(x) vals += weights.log_likelihood(np.arange(K_total)) assert not np.isnan(vals).any() return logsumexp(vals,axis=1).sum()
[ "def", "log_likelihood", "(", "self", ",", "x", ",", "K_extra", "=", "1", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "ks", "=", "self", ".", "_get_occupied", "(", ")", "K", "=", "len", "(", "ks", ")", "K_total", "=", "K", "+", "...
Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model.
[ "Estimate", "the", "log", "likelihood", "with", "samples", "from", "the", "model", ".", "Draw", "k_extra", "components", "which", "were", "not", "populated", "by", "the", "current", "model", "in", "order", "to", "create", "a", "truncated", "approximate", "mixt...
76aef00f011415cc5c858cd1a101f3aab971a62d
https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/models/mixture.py#L801-L841
train
33,485
closeio/redis-hashring
redis_hashring/__init__.py
RingNode.debug_print
def debug_print(self): """ Prints the ring for debugging purposes. """ ring = self._fetch_all() print('Hash ring "{key}" replicas:'.format(key=self.key)) now = time.time() n_replicas = len(ring) if ring: print('{:10} {:6} {:7} {}'.format('Start', 'Range', 'Delay', 'Node')) else: print('(no replicas)') nodes = collections.defaultdict(list) for n, (start, replica, heartbeat, expired) in enumerate(ring): hostname, pid, rnd = replica.split(':') node = ':'.join([hostname, pid]) abs_size = (ring[(n+1) % n_replicas][0] - ring[n][0]) % RING_SIZE size = 100. / RING_SIZE * abs_size delay = int(now - heartbeat) nodes[node].append((hostname, pid, abs_size, delay, expired)) print('{start:10} {size:5.2f}% {delay:6}s {replica}{extra}'.format( start=start, replica=replica, delay=delay, size=size, extra=' (EXPIRED)' if expired else '' )) print() print('Hash ring "{key}" nodes:'.format(key=self.key)) if nodes: print('{:8} {:8} {:7} {:20} {:5}'.format('Range', 'Replicas', 'Delay', 'Hostname', 'PID')) else: print('(no nodes)') for k, v in nodes.items(): hostname, pid = v[0][0], v[0][1] abs_size = sum(replica[2] for replica in v) size = 100. / RING_SIZE * abs_size delay = max(replica[3] for replica in v) expired = any(replica[4] for replica in v) count = len(v) print('{size:5.2f}% {count:8} {delay:6}s {hostname:20} {pid:5}{extra}'.format( start=start, count=count, hostname=hostname, pid=pid, delay=delay, size=size, extra=' (EXPIRED)' if expired else '' ))
python
def debug_print(self): """ Prints the ring for debugging purposes. """ ring = self._fetch_all() print('Hash ring "{key}" replicas:'.format(key=self.key)) now = time.time() n_replicas = len(ring) if ring: print('{:10} {:6} {:7} {}'.format('Start', 'Range', 'Delay', 'Node')) else: print('(no replicas)') nodes = collections.defaultdict(list) for n, (start, replica, heartbeat, expired) in enumerate(ring): hostname, pid, rnd = replica.split(':') node = ':'.join([hostname, pid]) abs_size = (ring[(n+1) % n_replicas][0] - ring[n][0]) % RING_SIZE size = 100. / RING_SIZE * abs_size delay = int(now - heartbeat) nodes[node].append((hostname, pid, abs_size, delay, expired)) print('{start:10} {size:5.2f}% {delay:6}s {replica}{extra}'.format( start=start, replica=replica, delay=delay, size=size, extra=' (EXPIRED)' if expired else '' )) print() print('Hash ring "{key}" nodes:'.format(key=self.key)) if nodes: print('{:8} {:8} {:7} {:20} {:5}'.format('Range', 'Replicas', 'Delay', 'Hostname', 'PID')) else: print('(no nodes)') for k, v in nodes.items(): hostname, pid = v[0][0], v[0][1] abs_size = sum(replica[2] for replica in v) size = 100. / RING_SIZE * abs_size delay = max(replica[3] for replica in v) expired = any(replica[4] for replica in v) count = len(v) print('{size:5.2f}% {count:8} {delay:6}s {hostname:20} {pid:5}{extra}'.format( start=start, count=count, hostname=hostname, pid=pid, delay=delay, size=size, extra=' (EXPIRED)' if expired else '' ))
[ "def", "debug_print", "(", "self", ")", ":", "ring", "=", "self", ".", "_fetch_all", "(", ")", "print", "(", "'Hash ring \"{key}\" replicas:'", ".", "format", "(", "key", "=", "self", ".", "key", ")", ")", "now", "=", "time", ".", "time", "(", ")", "...
Prints the ring for debugging purposes.
[ "Prints", "the", "ring", "for", "debugging", "purposes", "." ]
d767018571fbfb5705b6115d81619b2e84b6e50e
https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L135-L194
train
33,486
closeio/redis-hashring
redis_hashring/__init__.py
RingNode.update
def update(self): """ Fetches the updated ring from Redis and updates the current ranges. """ ring = self._fetch() n_replicas = len(ring) replica_set = set([r[1] for r in self.replicas]) self.ranges = [] for n, (start, replica) in enumerate(ring): if replica in replica_set: end = ring[(n+1) % n_replicas][0] % RING_SIZE if start < end: self.ranges.append((start, end)) elif end < start: self.ranges.append((start, RING_SIZE)) self.ranges.append((0, end)) else: self.ranges.append((0, RING_SIZE))
python
def update(self): """ Fetches the updated ring from Redis and updates the current ranges. """ ring = self._fetch() n_replicas = len(ring) replica_set = set([r[1] for r in self.replicas]) self.ranges = [] for n, (start, replica) in enumerate(ring): if replica in replica_set: end = ring[(n+1) % n_replicas][0] % RING_SIZE if start < end: self.ranges.append((start, end)) elif end < start: self.ranges.append((start, RING_SIZE)) self.ranges.append((0, end)) else: self.ranges.append((0, RING_SIZE))
[ "def", "update", "(", "self", ")", ":", "ring", "=", "self", ".", "_fetch", "(", ")", "n_replicas", "=", "len", "(", "ring", ")", "replica_set", "=", "set", "(", "[", "r", "[", "1", "]", "for", "r", "in", "self", ".", "replicas", "]", ")", "sel...
Fetches the updated ring from Redis and updates the current ranges.
[ "Fetches", "the", "updated", "ring", "from", "Redis", "and", "updates", "the", "current", "ranges", "." ]
d767018571fbfb5705b6115d81619b2e84b6e50e
https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L244-L261
train
33,487
closeio/redis-hashring
redis_hashring/__init__.py
RingNode.contains
def contains(self, key): """ Returns a boolean indicating if this node is responsible for handling the given key. """ n = binascii.crc32(key.encode()) % RING_SIZE for start, end in self.ranges: if start <= n < end: return True return False
python
def contains(self, key): """ Returns a boolean indicating if this node is responsible for handling the given key. """ n = binascii.crc32(key.encode()) % RING_SIZE for start, end in self.ranges: if start <= n < end: return True return False
[ "def", "contains", "(", "self", ",", "key", ")", ":", "n", "=", "binascii", ".", "crc32", "(", "key", ".", "encode", "(", ")", ")", "%", "RING_SIZE", "for", "start", ",", "end", "in", "self", ".", "ranges", ":", "if", "start", "<=", "n", "<", "...
Returns a boolean indicating if this node is responsible for handling the given key.
[ "Returns", "a", "boolean", "indicating", "if", "this", "node", "is", "responsible", "for", "handling", "the", "given", "key", "." ]
d767018571fbfb5705b6115d81619b2e84b6e50e
https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L263-L272
train
33,488
closeio/redis-hashring
redis_hashring/__init__.py
RingNode.gevent_start
def gevent_start(self): """ Helper method to start the node for gevent-based applications. """ import gevent import gevent.select self._poller_greenlet = gevent.spawn(self.poll) self._select = gevent.select.select self.heartbeat() self.update()
python
def gevent_start(self): """ Helper method to start the node for gevent-based applications. """ import gevent import gevent.select self._poller_greenlet = gevent.spawn(self.poll) self._select = gevent.select.select self.heartbeat() self.update()
[ "def", "gevent_start", "(", "self", ")", ":", "import", "gevent", "import", "gevent", ".", "select", "self", ".", "_poller_greenlet", "=", "gevent", ".", "spawn", "(", "self", ".", "poll", ")", "self", ".", "_select", "=", "gevent", ".", "select", ".", ...
Helper method to start the node for gevent-based applications.
[ "Helper", "method", "to", "start", "the", "node", "for", "gevent", "-", "based", "applications", "." ]
d767018571fbfb5705b6115d81619b2e84b6e50e
https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L317-L326
train
33,489
closeio/redis-hashring
redis_hashring/__init__.py
RingNode.gevent_stop
def gevent_stop(self): """ Helper method to stop the node for gevent-based applications. """ import gevent gevent.kill(self._poller_greenlet) self.remove() self._select = select.select
python
def gevent_stop(self): """ Helper method to stop the node for gevent-based applications. """ import gevent gevent.kill(self._poller_greenlet) self.remove() self._select = select.select
[ "def", "gevent_stop", "(", "self", ")", ":", "import", "gevent", "gevent", ".", "kill", "(", "self", ".", "_poller_greenlet", ")", "self", ".", "remove", "(", ")", "self", ".", "_select", "=", "select", ".", "select" ]
Helper method to stop the node for gevent-based applications.
[ "Helper", "method", "to", "stop", "the", "node", "for", "gevent", "-", "based", "applications", "." ]
d767018571fbfb5705b6115d81619b2e84b6e50e
https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L328-L335
train
33,490
pepkit/peppy
peppy/project.py
suggest_implied_attributes
def suggest_implied_attributes(prj): """ If given project contains what could be implied attributes, suggest that. :param Iterable prj: Intent is a Project, but this could be any iterable of strings to check for suitability of declaration as implied attr :return list[str]: (likely empty) list of warning messages about project config keys that could be implied attributes """ def suggest(key): return "To declare {}, consider using {}".format( key, IMPLICATIONS_DECLARATION) return [suggest(k) for k in prj if k in IDEALLY_IMPLIED]
python
def suggest_implied_attributes(prj): """ If given project contains what could be implied attributes, suggest that. :param Iterable prj: Intent is a Project, but this could be any iterable of strings to check for suitability of declaration as implied attr :return list[str]: (likely empty) list of warning messages about project config keys that could be implied attributes """ def suggest(key): return "To declare {}, consider using {}".format( key, IMPLICATIONS_DECLARATION) return [suggest(k) for k in prj if k in IDEALLY_IMPLIED]
[ "def", "suggest_implied_attributes", "(", "prj", ")", ":", "def", "suggest", "(", "key", ")", ":", "return", "\"To declare {}, consider using {}\"", ".", "format", "(", "key", ",", "IMPLICATIONS_DECLARATION", ")", "return", "[", "suggest", "(", "k", ")", "for", ...
If given project contains what could be implied attributes, suggest that. :param Iterable prj: Intent is a Project, but this could be any iterable of strings to check for suitability of declaration as implied attr :return list[str]: (likely empty) list of warning messages about project config keys that could be implied attributes
[ "If", "given", "project", "contains", "what", "could", "be", "implied", "attributes", "suggest", "that", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/project.py#L1068-L1080
train
33,491
pepkit/peppy
peppy/utils.py
check_bam
def check_bam(bam, o): """ Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation. """ try: p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE) # Count paired alignments paired = 0 read_lengths = defaultdict(int) while o > 0: # Count down number of lines line = p.stdout.readline().decode().split("\t") flag = int(line[1]) read_lengths[len(line[9])] += 1 if 1 & flag: # check decimal flag contains 1 (paired) paired += 1 o -= 1 p.kill() except OSError: reason = "Note (samtools not in path): For NGS inputs, " \ "pep needs samtools to auto-populate " \ "'read_length' and 'read_type' attributes; " \ "these attributes were not populated." raise OSError(reason) _LOGGER.debug("Read lengths: {}".format(read_lengths)) _LOGGER.debug("paired: {}".format(paired)) return read_lengths, paired
python
def check_bam(bam, o): """ Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation. """ try: p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE) # Count paired alignments paired = 0 read_lengths = defaultdict(int) while o > 0: # Count down number of lines line = p.stdout.readline().decode().split("\t") flag = int(line[1]) read_lengths[len(line[9])] += 1 if 1 & flag: # check decimal flag contains 1 (paired) paired += 1 o -= 1 p.kill() except OSError: reason = "Note (samtools not in path): For NGS inputs, " \ "pep needs samtools to auto-populate " \ "'read_length' and 'read_type' attributes; " \ "these attributes were not populated." raise OSError(reason) _LOGGER.debug("Read lengths: {}".format(read_lengths)) _LOGGER.debug("paired: {}".format(paired)) return read_lengths, paired
[ "def", "check_bam", "(", "bam", ",", "o", ")", ":", "try", ":", "p", "=", "sp", ".", "Popen", "(", "[", "'samtools'", ",", "'view'", ",", "bam", "]", ",", "stdout", "=", "sp", ".", "PIPE", ")", "# Count paired alignments", "paired", "=", "0", "read...
Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation.
[ "Check", "reads", "in", "BAM", "file", "for", "read", "type", "and", "lengths", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L62-L91
train
33,492
pepkit/peppy
peppy/utils.py
grab_project_data
def grab_project_data(prj): """ From the given Project, grab Sample-independent data. There are some aspects of a Project of which it's beneficial for a Sample to be aware, particularly for post-hoc analysis. Since Sample objects within a Project are mutually independent, though, each doesn't need to know about any of the others. A Project manages its, Sample instances, so for each Sample knowledge of Project data is limited. This method facilitates adoption of that conceptual model. :param Project prj: Project from which to grab data :return Mapping: Sample-independent data sections from given Project """ if not prj: return {} data = {} for section in SAMPLE_INDEPENDENT_PROJECT_SECTIONS: try: data[section] = getattr(prj, section) except AttributeError: _LOGGER.debug("Project lacks section '%s', skipping", section) return data
python
def grab_project_data(prj): """ From the given Project, grab Sample-independent data. There are some aspects of a Project of which it's beneficial for a Sample to be aware, particularly for post-hoc analysis. Since Sample objects within a Project are mutually independent, though, each doesn't need to know about any of the others. A Project manages its, Sample instances, so for each Sample knowledge of Project data is limited. This method facilitates adoption of that conceptual model. :param Project prj: Project from which to grab data :return Mapping: Sample-independent data sections from given Project """ if not prj: return {} data = {} for section in SAMPLE_INDEPENDENT_PROJECT_SECTIONS: try: data[section] = getattr(prj, section) except AttributeError: _LOGGER.debug("Project lacks section '%s', skipping", section) return data
[ "def", "grab_project_data", "(", "prj", ")", ":", "if", "not", "prj", ":", "return", "{", "}", "data", "=", "{", "}", "for", "section", "in", "SAMPLE_INDEPENDENT_PROJECT_SECTIONS", ":", "try", ":", "data", "[", "section", "]", "=", "getattr", "(", "prj",...
From the given Project, grab Sample-independent data. There are some aspects of a Project of which it's beneficial for a Sample to be aware, particularly for post-hoc analysis. Since Sample objects within a Project are mutually independent, though, each doesn't need to know about any of the others. A Project manages its, Sample instances, so for each Sample knowledge of Project data is limited. This method facilitates adoption of that conceptual model. :param Project prj: Project from which to grab data :return Mapping: Sample-independent data sections from given Project
[ "From", "the", "given", "Project", "grab", "Sample", "-", "independent", "data", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L214-L236
train
33,493
pepkit/peppy
peppy/utils.py
import_from_source
def import_from_source(module_filepath): """ Import a module from a particular filesystem location. :param str module_filepath: path to the file that constitutes the module to import :return module: module imported from the given location, named as indicated :raises ValueError: if path provided does not point to an extant file """ import sys if not os.path.exists(module_filepath): raise ValueError("Path to alleged module file doesn't point to an " "extant file: '{}'".format(module_filepath)) # Randomly generate module name. fname_chars = string.ascii_letters + string.digits name = "".join(random.choice(fname_chars) for _ in range(20)) # Import logic is version-dependent. if sys.version_info >= (3, 5): from importlib import util as _il_util modspec = _il_util.spec_from_file_location( name, module_filepath) mod = _il_util.module_from_spec(modspec) modspec.loader.exec_module(mod) elif sys.version_info < (3, 3): import imp mod = imp.load_source(name, module_filepath) else: # 3.3 or 3.4 from importlib import machinery as _il_mach loader = _il_mach.SourceFileLoader(name, module_filepath) mod = loader.load_module() return mod
python
def import_from_source(module_filepath): """ Import a module from a particular filesystem location. :param str module_filepath: path to the file that constitutes the module to import :return module: module imported from the given location, named as indicated :raises ValueError: if path provided does not point to an extant file """ import sys if not os.path.exists(module_filepath): raise ValueError("Path to alleged module file doesn't point to an " "extant file: '{}'".format(module_filepath)) # Randomly generate module name. fname_chars = string.ascii_letters + string.digits name = "".join(random.choice(fname_chars) for _ in range(20)) # Import logic is version-dependent. if sys.version_info >= (3, 5): from importlib import util as _il_util modspec = _il_util.spec_from_file_location( name, module_filepath) mod = _il_util.module_from_spec(modspec) modspec.loader.exec_module(mod) elif sys.version_info < (3, 3): import imp mod = imp.load_source(name, module_filepath) else: # 3.3 or 3.4 from importlib import machinery as _il_mach loader = _il_mach.SourceFileLoader(name, module_filepath) mod = loader.load_module() return mod
[ "def", "import_from_source", "(", "module_filepath", ")", ":", "import", "sys", "if", "not", "os", ".", "path", ".", "exists", "(", "module_filepath", ")", ":", "raise", "ValueError", "(", "\"Path to alleged module file doesn't point to an \"", "\"extant file: '{}'\"", ...
Import a module from a particular filesystem location. :param str module_filepath: path to the file that constitutes the module to import :return module: module imported from the given location, named as indicated :raises ValueError: if path provided does not point to an extant file
[ "Import", "a", "module", "from", "a", "particular", "filesystem", "location", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L250-L285
train
33,494
pepkit/peppy
peppy/utils.py
infer_delimiter
def infer_delimiter(filepath): """ From extension infer delimiter used in a separated values file. :param str filepath: path to file about which to make inference :return str | NoneType: extension if inference succeeded; else null """ ext = os.path.splitext(filepath)[1][1:].lower() return {"txt": "\t", "tsv": "\t", "csv": ","}.get(ext)
python
def infer_delimiter(filepath): """ From extension infer delimiter used in a separated values file. :param str filepath: path to file about which to make inference :return str | NoneType: extension if inference succeeded; else null """ ext = os.path.splitext(filepath)[1][1:].lower() return {"txt": "\t", "tsv": "\t", "csv": ","}.get(ext)
[ "def", "infer_delimiter", "(", "filepath", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "[", "1", "]", "[", "1", ":", "]", ".", "lower", "(", ")", "return", "{", "\"txt\"", ":", "\"\\t\"", ",", "\"tsv\"", ":", "...
From extension infer delimiter used in a separated values file. :param str filepath: path to file about which to make inference :return str | NoneType: extension if inference succeeded; else null
[ "From", "extension", "infer", "delimiter", "used", "in", "a", "separated", "values", "file", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L288-L296
train
33,495
pepkit/peppy
peppy/utils.py
is_null_like
def is_null_like(x): """ Determine whether an object is effectively null. :param object x: Object for which null likeness is to be determined. :return bool: Whether given object is effectively "null." """ return x in [None, ""] or \ (coll_like(x) and isinstance(x, Sized) and 0 == len(x))
python
def is_null_like(x): """ Determine whether an object is effectively null. :param object x: Object for which null likeness is to be determined. :return bool: Whether given object is effectively "null." """ return x in [None, ""] or \ (coll_like(x) and isinstance(x, Sized) and 0 == len(x))
[ "def", "is_null_like", "(", "x", ")", ":", "return", "x", "in", "[", "None", ",", "\"\"", "]", "or", "(", "coll_like", "(", "x", ")", "and", "isinstance", "(", "x", ",", "Sized", ")", "and", "0", "==", "len", "(", "x", ")", ")" ]
Determine whether an object is effectively null. :param object x: Object for which null likeness is to be determined. :return bool: Whether given object is effectively "null."
[ "Determine", "whether", "an", "object", "is", "effectively", "null", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L299-L307
train
33,496
pepkit/peppy
peppy/utils.py
parse_ftype
def parse_ftype(input_file): """ Checks determine filetype from extension. :param str input_file: String to check. :return str: filetype (extension without dot prefix) :raises TypeError: if file does not appear of a supported type """ if input_file.endswith(".bam"): return "bam" elif input_file.endswith(".fastq") or \ input_file.endswith(".fq") or \ input_file.endswith(".fq.gz") or \ input_file.endswith(".fastq.gz"): return "fastq" else: raise TypeError("Type of input file ends in neither '.bam' " "nor '.fastq' [file: '" + input_file + "']")
python
def parse_ftype(input_file): """ Checks determine filetype from extension. :param str input_file: String to check. :return str: filetype (extension without dot prefix) :raises TypeError: if file does not appear of a supported type """ if input_file.endswith(".bam"): return "bam" elif input_file.endswith(".fastq") or \ input_file.endswith(".fq") or \ input_file.endswith(".fq.gz") or \ input_file.endswith(".fastq.gz"): return "fastq" else: raise TypeError("Type of input file ends in neither '.bam' " "nor '.fastq' [file: '" + input_file + "']")
[ "def", "parse_ftype", "(", "input_file", ")", ":", "if", "input_file", ".", "endswith", "(", "\".bam\"", ")", ":", "return", "\"bam\"", "elif", "input_file", ".", "endswith", "(", "\".fastq\"", ")", "or", "input_file", ".", "endswith", "(", "\".fq\"", ")", ...
Checks determine filetype from extension. :param str input_file: String to check. :return str: filetype (extension without dot prefix) :raises TypeError: if file does not appear of a supported type
[ "Checks", "determine", "filetype", "from", "extension", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L331-L348
train
33,497
pepkit/peppy
peppy/utils.py
parse_text_data
def parse_text_data(lines_or_path, delimiter=os.linesep): """ Interpret input argument as lines of data. This is intended to support multiple input argument types to core model constructors. :param str | collections.Iterable lines_or_path: :param str delimiter: line separator used when parsing a raw string that's not a file :return collections.Iterable: lines of text data :raises ValueError: if primary data argument is neither a string nor another iterable """ if os.path.isfile(lines_or_path): with open(lines_or_path, 'r') as f: return f.readlines() else: _LOGGER.debug("Not a file: '{}'".format(lines_or_path)) if isinstance(lines_or_path, str): return lines_or_path.split(delimiter) elif isinstance(lines_or_path, Iterable): return lines_or_path else: raise ValueError("Unable to parse as data lines {} ({})". format(lines_or_path, type(lines_or_path)))
python
def parse_text_data(lines_or_path, delimiter=os.linesep): """ Interpret input argument as lines of data. This is intended to support multiple input argument types to core model constructors. :param str | collections.Iterable lines_or_path: :param str delimiter: line separator used when parsing a raw string that's not a file :return collections.Iterable: lines of text data :raises ValueError: if primary data argument is neither a string nor another iterable """ if os.path.isfile(lines_or_path): with open(lines_or_path, 'r') as f: return f.readlines() else: _LOGGER.debug("Not a file: '{}'".format(lines_or_path)) if isinstance(lines_or_path, str): return lines_or_path.split(delimiter) elif isinstance(lines_or_path, Iterable): return lines_or_path else: raise ValueError("Unable to parse as data lines {} ({})". format(lines_or_path, type(lines_or_path)))
[ "def", "parse_text_data", "(", "lines_or_path", ",", "delimiter", "=", "os", ".", "linesep", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "lines_or_path", ")", ":", "with", "open", "(", "lines_or_path", ",", "'r'", ")", "as", "f", ":", "retur...
Interpret input argument as lines of data. This is intended to support multiple input argument types to core model constructors. :param str | collections.Iterable lines_or_path: :param str delimiter: line separator used when parsing a raw string that's not a file :return collections.Iterable: lines of text data :raises ValueError: if primary data argument is neither a string nor another iterable
[ "Interpret", "input", "argument", "as", "lines", "of", "data", ".", "This", "is", "intended", "to", "support", "multiple", "input", "argument", "types", "to", "core", "model", "constructors", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L351-L376
train
33,498
pepkit/peppy
peppy/utils.py
sample_folder
def sample_folder(prj, sample): """ Get the path to this Project's root folder for the given Sample. :param attmap.PathExAttMap | Project prj: project with which sample is associated :param Mapping sample: Sample or sample data for which to get root output folder path. :return str: this Project's root folder for the given Sample """ return os.path.join(prj.metadata.results_subdir, sample["sample_name"])
python
def sample_folder(prj, sample): """ Get the path to this Project's root folder for the given Sample. :param attmap.PathExAttMap | Project prj: project with which sample is associated :param Mapping sample: Sample or sample data for which to get root output folder path. :return str: this Project's root folder for the given Sample """ return os.path.join(prj.metadata.results_subdir, sample["sample_name"])
[ "def", "sample_folder", "(", "prj", ",", "sample", ")", ":", "return", "os", ".", "path", ".", "join", "(", "prj", ".", "metadata", ".", "results_subdir", ",", "sample", "[", "\"sample_name\"", "]", ")" ]
Get the path to this Project's root folder for the given Sample. :param attmap.PathExAttMap | Project prj: project with which sample is associated :param Mapping sample: Sample or sample data for which to get root output folder path. :return str: this Project's root folder for the given Sample
[ "Get", "the", "path", "to", "this", "Project", "s", "root", "folder", "for", "the", "given", "Sample", "." ]
f0f725e1557936b81c86573a77400e6f8da78f05
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L379-L389
train
33,499