Commit 0c63343f by David Baumgold

Merge pull request #2172 from edx/db/doc-build-url

Reorganize doc for i18n
parents 157f734b 7928535b
......@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import ConfigParser
from django.conf import settings
from django.template import RequestContext
from util.request import safe_get_host
requestcontext = None
......@@ -24,3 +26,21 @@ class MakoMiddleware(object):
requestcontext = RequestContext(request)
requestcontext['is_secure'] = request.is_secure()
requestcontext['site'] = safe_get_host(request)
requestcontext['doc_url'] = self.get_doc_url_func(request)
def get_doc_url_func(self, request):
config_file = open(settings.REPO_ROOT / "docs" / "config.ini")
config = ConfigParser.ConfigParser()
config.readfp(config_file)
# in the future, we will detect the locale; for now, we will
# hardcode en_us, since we only have English documentation
locale = "en_us"
def doc_url(token):
try:
return config.get(locale, token)
except ConfigParser.NoOptionError:
return config.get(locale, "default")
return doc_url
[en_us]
default=default
##############
Course Grading
##############
This document is written to help professors understand how a final grade for a
course is computed.
Course grading is the process of taking all of the problems scores for a student
in a course and generating a final score (and corresponding letter grade). This
grading process can be split into two phases - totaling sections and section
weighting.
*****************
Totaling sections
*****************
The process of totaling sections is to get a percentage score (between 0.0 and
1.0) for every section in the course. A section is any module that is a direct
child of a chapter. For example, psets, labs, and sequences are all common
sections. Only the *percentage* on the section will be available to compute the
final grade, *not* the final number of points earned / possible.
.. important::
For a section to be included in the final grade, the policies file must set
`graded = True` for the section.
For each section, the grading function retrieves all problems within the
section. The section percentage is computed as (total points earned) / (total
points possible).
******************
Weighting Problems
******************
In some cases, one might want to give weights to problems within a section. For
example, a final exam might contain four questions each worth 1 point by default.
This means each question would by default have the same weight. If one wanted
the first problem to be worth 50% of the final exam, the policy file could specify
weights of 30, 10, 10, and 10 to the four problems, respectively.
Note that the default weight of a problem **is not 1**. The default weight of a
problem is the module's `max_grade`.
If weighting is set, each problem is worth the number of points assigned, regardless of the number of responses it contains.
Consider a Homework section that contains two problems.
.. code-block:: xml
<problem display_name=”Problem 1”>
<numericalresponse> ... </numericalreponse>
</problem>
.. code-block:: xml
<problem display_name=”Problem 2”>
<numericalresponse> ... </numericalreponse>
<numericalresponse> ... </numericalreponse>
<numericalresponse> ... </numericalreponse>
</problem>
Without weighting, Problem 1 is worth 25% of the assignment, and Problem 2 is worth 75% of the assignment.
Weighting for the problems can be set in the policy.json file.
.. code-block:: json
"problem/problem1": {
"weight": 2
},
"problem/problem2": {
"weight": 2
},
With the above weighting, Problems 1 and 2 are each worth 50% of the assignment.
Please note: When problems have weight, the point value is automatically included in the display name *except* when `"weight": 1`. When the weight is 1, no visual change occurs in the display name, leaving the point value open to interpretation to the student.
******************
Weighting Sections
******************
Once each section has a percentage score, we must total those sections into a
final grade. Of course, not every section has equal weight in the final grade.
The policies for weighting sections into a final grade are specified in the
grading_policy.json file.
The `grading_policy.json` file specifies several sub-graders that are each given
a weight and factored into the final grade. There are currently two types of
sub-graders, section format graders and single section graders.
We will use this simple example of a grader with one section format grader and
one single section grader.
.. code-block:: json
"GRADER" : [
{
"type" : "Homework",
"min_count" : 12,
"drop_count" : 2,
"short_label" : "HW",
"weight" : 0.4
},
{
"type" : "Final",
"name" : "Final Exam",
"short_label" : "Final",
"weight" : 0.6
}
]
Section Format Graders
======================
A section format grader grades a set of sections with the same format, as
defined in the course policy file. To make a vertical named Homework1 be graded
by the Homework section format grader, the following definition would be in the
course policy file.
.. code-block:: json
"vertical/Homework1": {
"display_name": "Homework 1",
"graded": true,
"format": "Homework"
},
In the example above, the section format grader declares that it will expect to
find at least 12 sections with the format "Homework". It will drop the lowest 2.
All of the homework assignments will have equal weight, relative to each other
(except, of course, for the assignments that are dropped).
This format supports forecasting the number of homework assignments. For
example, if the course only has 3 homeworks written, but the section format
grader has been told to expect 12, the missing 9 will have an assumed 0% and
will still show up in the grade breakdown.
A section format grader will also show the average of that section in the grade
breakdown (shown on the Progress page, gradebook, etc.).
Single Section Graders
======================
A single section grader grades exactly that - a single section. If a section
is found with a matching format and display name then the score of that section
is used. If not, a score of 0% is assumed.
Combining sub-graders
=====================
The final grade is computed by taking the score and weight of each sub grader.
In the above example, homework will be 40% of the final grade. The final exam
will be 60% of the final grade.
**************************
Displaying the final grade
**************************
The final grade is then rounded up to the nearest percentage point. This is so
the system can consistently display a percentage without worrying whether the
displayed percentage has been rounded up or down (potentially misleading the
student). The formula for the rounding is::
rounded_percent = round(computed_percent * 100 + 0.05) / 100
The grading policy file also specifies the cutoffs for the grade levels. A
grade is either A, B, or C. If the student does not reach the cutoff threshold
for a C grade then the student has not earned a grade and will not be eligible
for a certificate. Letter grades are only awarded to students who have
completed the course. There is no notion of a failing letter grade.
##############################################################################
JS Input
##############################################################################
This document explains how to write a JSInput input type. JSInput is meant to
allow problem authors to easily turn working standalone HTML files into
problems that can be integrated into the edX platform. Since it's aim is
flexibility, it can be seen as the input and client-side equivalent of
CustomResponse.
A JSInput input creates an iframe into a static HTML page, and passes the
return value of author-specified functions to the enclosing response type
(generally CustomResponse). JSInput can also stored and retrieve state.
******************************************************************************
Format
******************************************************************************
A jsinput problem looks like this:
.. code-block:: xml
<problem>
<script type="loncapa/python">
def all_true(exp, ans): return ans == "hi"
</script>
<customresponse cfn="all_true">
<jsinput gradefn="gradefn"
height="500"
get_statefn="getstate"
set_statefn="setstate"
html_file="/static/jsinput.html"/>
</customresponse>
</problem>
The accepted attributes are:
============== ============== ========= ==========
Attribute Name Value Type Required? Default
============== ============== ========= ==========
html_file Url string Yes None
gradefn Function name Yes `gradefn`
set_statefn Function name No None
get_statefn Function name No None
height Integer No `500`
width Integer No `400`
============== ============== ========= ==========
******************************************************************************
Required Attributes
******************************************************************************
==============================================================================
html_file
==============================================================================
The `html_file` attribute specifies what html file the iframe will point to. This
should be located in the content directory.
The iframe is created using the sandbox attribute; while popups, scripts, and
pointer locks are allowed, the iframe cannot access its parent's attributes.
The html file should contain an accesible gradefn function. To check whether
the gradefn will be accessible to JSInput, check that, in the console,::
"`gradefn"
Returns the right thing. When used by JSInput, `gradefn` is called with::
`gradefn`.call(`obj`)
Where `obj` is the object-part of `gradefn`. For example, if `gradefn` is
`myprog.myfn`, JSInput will call `myprog.myfun.call(myprog)`. (This is to
ensure "`this`" continues to refer to what `gradefn` expects.)
Aside from that, more or less anything goes. Note that currently there is no
support for inheriting css or javascript from the parent (aside from the
Chrome-only `seamless` attribute, which is set to true by default).
==============================================================================
gradefn
==============================================================================
The `gradefn` attribute specifies the name of the function that will be called
when a user clicks on the "Check" button, and which should return the student's
answer. This answer will (unless both the get_statefn and set_statefn
attributes are also used) be passed as a string to the enclosing response type.
In the customresponse example above, this means cfn will be passed this answer
as `ans`.
If the `gradefn` function throws an exception when a student attempts to
submit a problem, the submission is aborted, and the student receives a generic
alert. The alert can be customised by making the exception name `Waitfor
Exception`; in that case, the alert message will be the exception message.
**IMPORTANT** : the `gradefn` function should not be at all asynchronous, since
this could result in the student's latest answer not being passed correctly.
Moreover, the function should also return promptly, since currently the student
has no indication that her answer is being calculated/produced.
******************************************************************************
Option Attributes
******************************************************************************
The `height` and `width` attributes are straightforward: they specify the
height and width of the iframe. Both are limited by the enclosing DOM elements,
so for instance there is an implicit max-width of around 900.
In the future, JSInput may attempt to make these dimensions match the html
file's dimensions (up to the aforementioned limits), but currently it defaults
to `500` and `400` for `height` and `width`, respectively.
==============================================================================
set_statefn
==============================================================================
Sometimes a problem author will want information about a student's previous
answers ("state") to be saved and reloaded. If the attribute `set_statefn` is
used, the function given as its value will be passed the state as a string
argument whenever there is a state, and the student returns to a problem. It is
the responsibility of the function to then use this state approriately.
The state that is passed is:
1. The previous output of `gradefn` (i.e., the previous answer) if
`get_statefn` is not defined.
2. The previous output of `get_statefn` (see below) otherwise.
It is the responsibility of the iframe to do proper verification of the
argument that it receives via `set_statefn`.
==============================================================================
get_statefn
==============================================================================
Sometimes the state and the answer are quite different. For instance, a problem
that involves using a javascript program that allows the student to alter a
molecule may grade based on the molecule's hidrophobicity, but from the
hidrophobicity it might be incapable of restoring the state. In that case, a
*separate* state may be stored and loaded by `set_statefn`. Note that if
`get_statefn` is defined, the answer (i.e., what is passed to the enclosing
response type) will be a json string with the following format::
{
answer: `[answer string]`
state: `[state string]`
}
It is the responsibility of the enclosing response type to then parse this as
json.
######################
Discussion Forums Data
######################
Discussions in edX are stored in a MongoDB database as collections of JSON documents.
The primary collection holding all posts and comments written by users is `contents`. There are two types of objects stored here, though they share much of the same structure. A `CommentThread` represents a comment that opens a new thread -- usually a student question of some sort. A `Comment` is a reply in the conversation started by a `CommentThread`.
*****************
Shared Attributes
*****************
The attributes that `Comment` and `CommentThread` objects share are listed below.
`_id`
-----
The 12-byte MongoDB unique ID for this collection. Like all MongoDB IDs, they are monotonically increasing and the first four bytes are a timestamp.
`_type`
-------
`CommentThread` or `Comment` depending on the type of object.
`anonymous`
-----------
If true, this `Comment` or `CommentThread` will show up as written by anonymous, even to those who have moderator privileges in the forums.
`anonymous_to_peers`
--------------------
The idea behind this field was that `anonymous_to_peers = true` would make the the comment appear anonymous to your fellow students, but would allow the course staff to see who you were. However, that was never implemented in the UI, and only `anonymous` is actually used. The `anonymous_to_peers` field is always false.
`at_position_list`
------------------
No longer used. Child comments (replies) are just sorted by their `created_at` timestamp instead.
`author_id`
-----------
The user who wrote this. Corresponds to the user IDs we store in our MySQL database as `auth_user.id`
`body`
------
Text of the comment in Markdown. UTF-8 encoded.
`course_id`
-----------
The full course_id of the course that this comment was made in, including org and run. This value can be seen in the URL when browsing the courseware section. Example: `BerkeleyX/Stat2.1x/2013_Spring`
`created_at`
------------
Timestamp in UTC. Example: `ISODate("2013-02-21T03:03:04.587Z")`
`updated_at`
------------
Timestamp in UTC. Example: `ISODate("2013-02-21T03:03:04.587Z")`
`votes`
-------
Both `CommentThread` and `Comment` objects support voting. `Comment` objects that are replies to other comments still have this attribute, even though there is no way to actually vote on them in the UI. This attribute is a dictionary that has the following inside:
* `up` = list of User IDs that up-voted this comment or thread.
* `down` = list of User IDs that down-voted this comment or thread (no longer used).
* `up_count` = total upvotes received.
* `down_count` = total downvotes received (no longer used).
* `count` = total votes cast.
* `point` = net vote, now always equal to `up_count`.
A user only has one vote per `Comment` or `CommentThread`. Though it's still written to the database, the UI no longer displays an option to downvote anything.
*************
CommentThread
*************
The following fields are specific to `CommentThread` objects. Each thread in the forums is represented by one `CommentThread`.
`closed`
--------
If true, this thread was closed by a forum moderator/admin.
`comment_count`
---------------
The number of comment replies in this thread. This includes all replies to replies, but does not include the original comment that started the thread. So if we had::
CommentThread: "What's a good breakfast?"
* Comment: "Just eat cereal!"
* Comment: "Try a Loco Moco, it's amazing!"
* Comment: "A Loco Moco? Only if you want a heart attack!"
* Comment: "But it's worth it! Just get a spam musubi on the side."
In that exchange, the `comment_count` for the `CommentThread` is `4`.
`commentable_id`
----------------
We can attach a discussion to any piece of content in the course, or to top level categories like "General" and "Troubleshooting". When the `commentable_id` is a high level category, it's specified in the course's policy file. When it's a specific content piece (e.g. `600x_l5_p8`, meaning 6.00x, Lecture Sequence 5, Problem 8), it's taken from a discussion module in the course.
`last_activity_at`
------------------
Timestamp in UTC indicating the last time there was activity in the thread (new posts, edits, etc). Closing the thread does not affect the value in this field.
`tags_array`
------------
Meant to be a list of tags that were user definable, but no longer used.
`title`
-------
Title of the thread, UTF-8 string.
*******
Comment
*******
The following fields are specific to `Comment` objects. A `Comment` is a reply to a `CommentThread` (so an answer to the question), or a reply to another `Comment` (a comment about somebody's answer). It used to be the case that `Comment` replies could nest much more deeply, but we later capped it at just these three levels (question, answer, comment) much in the way that StackOverflow does.
`endorsed`
----------
Boolean value, true if a forum moderator or instructor has marked that this `Comment` is a correct answer for whatever question the thread was asking. Exists for `Comments` that are replies to other `Comments`, but in that case `endorsed` is always false because there's no way to endorse such comments through the UI.
`comment_thread_id`
-------------------
What `CommentThread` are we a part of? All `Comment` objects have this.
`parent_id`
-----------
The `parent_id` is the `_id` of the `Comment` that this comment was made in reply to. Note that this only occurs in a `Comment` that is a reply to another `Comment`; it does not appear in a `Comment` that is a reply to a `CommentThread`.
`parent_ids`
------------
The `parent_ids` attribute appears in all `Comment` objects, and contains the `_id` of all ancestor comments. Since the UI now prevents comments from being nested more than one layer deep, it will only ever have at most one element in it. If a `Comment` has no parent, it's an empty list.
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
Q_FLAG =
ifeq ($(quiet), true)
Q_FLAG = -Q
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = $(Q_FLAG) -d $(BUILDDIR)/doctrees -c source $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/edX.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/edX.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/edX"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/edX"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
# -*- coding: utf-8 -*-
#pylint: disable=C0103
#pylint: disable=W0622
#pylint: disable=W0212
#pylint: disable=W0613
import sys, os
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
sys.path.append('../../../')
from docs.shared.conf import *
# Add any paths that contain templates here, relative to this directory.
templates_path.append('source/_templates')
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path.append('source/_static')
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../..'))
root = os.path.abspath('../../..')
sys.path.append(root)
sys.path.append(os.path.join(root, "common/djangoapps"))
sys.path.append(os.path.join(root, "common/lib"))
sys.path.append(os.path.join(root, "common/lib/sandbox-packages"))
sys.path.append(os.path.join(root, "lms/djangoapps"))
sys.path.append(os.path.join(root, "lms/lib"))
sys.path.append(os.path.join(root, "cms/djangoapps"))
sys.path.append(os.path.join(root, "cms/lib"))
sys.path.insert(0, os.path.abspath(os.path.normpath(os.path.dirname(__file__)
+ '/../../')))
sys.path.append('.')
# django configuration - careful here
if on_rtd:
os.environ['DJANGO_SETTINGS_MODULE'] = 'lms'
else:
os.environ['DJANGO_SETTINGS_MODULE'] = 'lms.envs.test'
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx',
'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath',
'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build']
# Output file base name for HTML help builder.
htmlhelp_basename = 'edXDocs'
# --- Mock modules ------------------------------------------------------------
# Mock all the modules that the readthedocs build can't import
import mock
class Mock(object):
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return Mock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].upper():
mockType = type(name, (), {})
mockType.__module__ = __name__
return mockType
else:
return Mock()
# The list of modules and submodules that we know give RTD trouble.
# Make sure you've tried including the relevant package in
# docs/share/requirements.txt before adding to this list.
MOCK_MODULES = [
'numpy',
'matplotlib',
'matplotlib.pyplot',
'scipy.interpolate',
'scipy.constants',
'scipy.optimize',
]
if on_rtd:
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
# -----------------------------------------------------------------------------
# from http://djangosnippets.org/snippets/2533/
# autogenerate models definitions
import inspect
import types
from HTMLParser import HTMLParser
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_unicode, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
if not isinstance(s, basestring,):
if hasattr(s, '__unicode__'):
s = unicode(s)
else:
s = unicode(str(s), encoding, errors)
elif not isinstance(s, unicode):
s = unicode(s, encoding, errors)
return s
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def process_docstring(app, what, name, obj, options, lines):
"""Autodoc django models"""
# This causes import errors if left outside the function
from django.db import models
# If you want extract docs from django forms:
# from django import forms
# from django.forms.models import BaseInlineFormSet
# Only look at objects that inherit from Django's base MODEL class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta._fields()
for field in fields:
# Decode and strip any html out of the field's help text
help_text = strip_tags(force_unicode(field.help_text))
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = force_unicode(field.verbose_name).capitalize()
if help_text:
# Add the model field to the end of the docstring as a param
# using the help text as the description
lines.append(u':param %s: %s' % (field.attname, help_text))
else:
# Add the model field to the end of the docstring as a param
# using the verbose name as the description
lines.append(u':param %s: %s' % (field.attname, verbose_name))
# Add the field's type to the docstring
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
return lines
def setup(app):
"""Setup docsting processors"""
#Register the docstring processor with sphinx
app.connect('autodoc-process-docstring', process_docstring)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment