Merge remote-tracking branch 'origin/master' into feature/victor/cohorts
Conflicts: common/djangoapps/student/models.py
This commit is contained in:
1
.ruby-version
Normal file
1
.ruby-version
Normal file
@@ -0,0 +1 @@
|
||||
1.8.7-p371
|
||||
8
Gemfile
8
Gemfile
@@ -1,7 +1,7 @@
|
||||
source :rubygems
|
||||
ruby "1.9.3"
|
||||
gem 'rake'
|
||||
ruby "1.8.7"
|
||||
gem 'rake', '~> 10.0.3'
|
||||
gem 'sass', '3.1.15'
|
||||
gem 'bourbon', '~> 1.3.6'
|
||||
gem 'colorize'
|
||||
gem 'launchy'
|
||||
gem 'colorize', '~> 0.5.8'
|
||||
gem 'launchy', '~> 2.1.2'
|
||||
|
||||
@@ -229,7 +229,7 @@ PIPELINE_JS = {
|
||||
'source_filenames': sorted(
|
||||
rooted_glob(COMMON_ROOT / 'static/', 'coffee/src/**/*.coffee') +
|
||||
rooted_glob(PROJECT_ROOT / 'static/', 'coffee/src/**/*.coffee')
|
||||
) + ['js/base.js'],
|
||||
) + [ 'js/hesitate.js', 'js/base.js'],
|
||||
'output_filename': 'js/cms-application.js',
|
||||
},
|
||||
'module-js': {
|
||||
|
||||
@@ -55,13 +55,6 @@ $(document).ready(function() {
|
||||
$("#start_date, #start_time, #due_date, #due_time").bind('change', autosaveInput);
|
||||
$('.sync-date, .remove-date').bind('click', autosaveInput);
|
||||
|
||||
// making the unit list sortable
|
||||
$('.sortable-unit-list').sortable({
|
||||
axis: 'y',
|
||||
handle: '.drag-handle',
|
||||
update: onUnitReordered
|
||||
});
|
||||
|
||||
// expand/collapse methods for optional date setters
|
||||
$('.set-date').bind('click', showDateSetter);
|
||||
$('.remove-date').bind('click', removeDateSetter);
|
||||
@@ -87,18 +80,56 @@ $(document).ready(function() {
|
||||
$('.import .file-input').click();
|
||||
});
|
||||
|
||||
// Subsection reordering
|
||||
$('.subsection-list > ol').sortable({
|
||||
axis: 'y',
|
||||
handle: '.section-item .drag-handle',
|
||||
update: onSubsectionReordered
|
||||
// making the unit list draggable. Note: sortable didn't work b/c it considered
|
||||
// drop points which the user hovered over as destinations and proactively changed
|
||||
// the dom; so, if the user subsequently dropped at an illegal spot, the reversion
|
||||
// point was the last dom change.
|
||||
$('.unit').draggable({
|
||||
axis: 'y',
|
||||
handle: '.drag-handle',
|
||||
stack: '.unit',
|
||||
revert: "invalid"
|
||||
});
|
||||
|
||||
|
||||
// Subsection reordering
|
||||
$('.id-holder').draggable({
|
||||
axis: 'y',
|
||||
handle: '.section-item .drag-handle',
|
||||
stack: '.id-holder',
|
||||
revert: "invalid"
|
||||
});
|
||||
|
||||
// Section reordering
|
||||
$('.courseware-overview').sortable({
|
||||
axis: 'y',
|
||||
handle: 'header .drag-handle',
|
||||
update: onSectionReordered
|
||||
$('.courseware-section').draggable({
|
||||
axis: 'y',
|
||||
handle: 'header .drag-handle',
|
||||
stack: '.courseware-section',
|
||||
revert: "invalid"
|
||||
});
|
||||
|
||||
|
||||
$('.sortable-unit-list').droppable({
|
||||
accept : '.unit',
|
||||
greedy: true,
|
||||
tolerance: "pointer",
|
||||
hoverClass: "dropover",
|
||||
drop: onUnitReordered
|
||||
});
|
||||
$('.subsection-list > ol').droppable({
|
||||
// why don't we have a more useful class for subsections than id-holder?
|
||||
accept : '.id-holder', // '.unit, .id-holder',
|
||||
tolerance: "pointer",
|
||||
hoverClass: "dropover",
|
||||
drop: onSubsectionReordered,
|
||||
greedy: true
|
||||
});
|
||||
|
||||
// Section reordering
|
||||
$('.courseware-overview').droppable({
|
||||
accept : '.courseware-section',
|
||||
tolerance: "pointer",
|
||||
drop: onSectionReordered,
|
||||
greedy: true
|
||||
});
|
||||
|
||||
$('.new-course-button').bind('click', addNewCourse);
|
||||
@@ -240,54 +271,76 @@ function removePolicyMetadata(e) {
|
||||
saveSubsection()
|
||||
}
|
||||
|
||||
function expandSection(event) {
|
||||
$(event.delegateTarget).removeClass('collapsed');
|
||||
$(event.delegateTarget).find('.expand-collapse-icon').removeClass('expand').addClass('collapse');
|
||||
}
|
||||
|
||||
// This method only changes the ordering of the child objects in a subsection
|
||||
function onUnitReordered() {
|
||||
var subsection_id = $(this).data('subsection-id');
|
||||
function onUnitReordered(event, ui) {
|
||||
// a unit's been dropped on this subsection,
|
||||
// figure out where it came from and where it slots in.
|
||||
_handleReorder(event, ui, 'subsection-id', 'li:.leaf');
|
||||
}
|
||||
|
||||
var _els = $(this).children('li:.leaf');
|
||||
var children = _els.map(function(idx, el) { return $(el).data('id'); }).get();
|
||||
function onSubsectionReordered(event, ui) {
|
||||
// a subsection has been dropped on this section,
|
||||
// figure out where it came from and where it slots in.
|
||||
_handleReorder(event, ui, 'section-id', 'li:.branch');
|
||||
}
|
||||
|
||||
// call into server to commit the new order
|
||||
$.ajax({
|
||||
url: "/save_item",
|
||||
function onSectionReordered(event, ui) {
|
||||
// a section moved w/in the overall (cannot change course via this, so no parentage change possible, just order)
|
||||
_handleReorder(event, ui, 'course-id', '.courseware-section');
|
||||
}
|
||||
|
||||
function _handleReorder(event, ui, parentIdField, childrenSelector) {
|
||||
// figure out where it came from and where it slots in.
|
||||
var subsection_id = $(event.target).data(parentIdField);
|
||||
var _els = $(event.target).children(childrenSelector);
|
||||
var children = _els.map(function(idx, el) { return $(el).data('id'); }).get();
|
||||
// if new to this parent, figure out which parent to remove it from and do so
|
||||
if (!_.contains(children, ui.draggable.data('id'))) {
|
||||
var old_parent = ui.draggable.parent();
|
||||
var old_children = old_parent.children(childrenSelector).map(function(idx, el) { return $(el).data('id'); }).get();
|
||||
old_children = _.without(old_children, ui.draggable.data('id'));
|
||||
$.ajax({
|
||||
url: "/save_item",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json",
|
||||
data:JSON.stringify({ 'id' : old_parent.data(parentIdField), 'children' : old_children})
|
||||
});
|
||||
}
|
||||
else {
|
||||
// staying in same parent
|
||||
// remove so that the replacement in the right place doesn't double it
|
||||
children = _.without(children, ui.draggable.data('id'));
|
||||
}
|
||||
// add to this parent (figure out where)
|
||||
for (var i = 0; i < _els.length; i++) {
|
||||
if (!ui.draggable.is(_els[i]) && ui.offset.top < $(_els[i]).offset().top) {
|
||||
// insert at i in children and _els
|
||||
ui.draggable.insertBefore($(_els[i]));
|
||||
// TODO figure out correct way to have it remove the style: top:n; setting (and similar line below)
|
||||
ui.draggable.attr("style", "position:relative;");
|
||||
children.splice(i, 0, ui.draggable.data('id'));
|
||||
break;
|
||||
}
|
||||
}
|
||||
// see if it goes at end (the above loop didn't insert it)
|
||||
if (!_.contains(children, ui.draggable.data('id'))) {
|
||||
$(event.target).append(ui.draggable);
|
||||
ui.draggable.attr("style", "position:relative;"); // STYLE hack too
|
||||
children.push(ui.draggable.data('id'));
|
||||
}
|
||||
$.ajax({
|
||||
url: "/save_item",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json",
|
||||
data:JSON.stringify({ 'id' : subsection_id, 'children' : children})
|
||||
});
|
||||
}
|
||||
|
||||
function onSubsectionReordered() {
|
||||
var section_id = $(this).data('section-id');
|
||||
|
||||
var _els = $(this).children('li:.branch');
|
||||
var children = _els.map(function(idx, el) { return $(el).data('id'); }).get();
|
||||
|
||||
// call into server to commit the new order
|
||||
$.ajax({
|
||||
url: "/save_item",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json",
|
||||
data:JSON.stringify({ 'id' : section_id, 'children' : children})
|
||||
});
|
||||
}
|
||||
|
||||
function onSectionReordered() {
|
||||
var course_id = $(this).data('course-id');
|
||||
|
||||
var _els = $(this).children('section:.branch');
|
||||
var children = _els.map(function(idx, el) { return $(el).data('id'); }).get();
|
||||
|
||||
// call into server to commit the new order
|
||||
$.ajax({
|
||||
url: "/save_item",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json",
|
||||
data:JSON.stringify({ 'id' : course_id, 'children' : children})
|
||||
});
|
||||
}
|
||||
|
||||
function getEdxTimeFromDateTimeVals(date_val, time_val, format) {
|
||||
|
||||
50
cms/static/js/hesitate.js
Normal file
50
cms/static/js/hesitate.js
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Create a HesitateEvent and assign it as the event to execute:
|
||||
* $(el).on('mouseEnter', CMS.HesitateEvent( expand, 'mouseLeave').trigger);
|
||||
* It calls the executeOnTimeOut function with the event.currentTarget after the configurable timeout IFF the cancelSelector event
|
||||
* did not occur on the event.currentTarget.
|
||||
*
|
||||
* More specifically, when trigger is called (triggered by the event you bound it to), it starts a timer
|
||||
* which the cancelSelector event will cancel or if the timer finished, it executes the executeOnTimeOut function
|
||||
* passing it the original event (whose currentTarget s/b the specific ele). It never accumulates events; however, it doesn't hurt for your
|
||||
* code to minimize invocations of trigger by binding to mouseEnter v mouseOver and such.
|
||||
*
|
||||
* NOTE: if something outside of this wants to cancel the event, invoke cachedhesitation.untrigger(null | anything);
|
||||
*/
|
||||
|
||||
CMS.HesitateEvent = function(executeOnTimeOut, cancelSelector, onlyOnce) {
|
||||
this.executeOnTimeOut = executeOnTimeOut;
|
||||
this.cancelSelector = cancelSelector;
|
||||
this.timeoutEventId = null;
|
||||
this.originalEvent = null;
|
||||
this.onlyOnce = (onlyOnce === true);
|
||||
}
|
||||
|
||||
CMS.HesitateEvent.DURATION = 400;
|
||||
|
||||
CMS.HesitateEvent.prototype.trigger = function(event) {
|
||||
console.log('trigger');
|
||||
if (this.timeoutEventId === null) {
|
||||
this.timeoutEventId = window.setTimeout(this.fireEvent, CMS.HesitateEvent.DURATION);
|
||||
this.originalEvent = event;
|
||||
// is it wrong to bind to the below v $(event.currentTarget)?
|
||||
$(this.originalEvent.delegateTarget).on(this.cancelSelector, this.untrigger);
|
||||
}
|
||||
}
|
||||
|
||||
CMS.HesitateEvent.prototype.fireEvent = function(event) {
|
||||
console.log('fire');
|
||||
this.timeoutEventId = null;
|
||||
$(this.originalEvent.delegateTarget).off(this.cancelSelector, this.untrigger);
|
||||
if (this.onlyOnce) $(this.originalEvent.delegateTarget).off(this.originalEvent.type, this.trigger);
|
||||
this.executeOnTimeOut(this.originalEvent);
|
||||
}
|
||||
|
||||
CMS.HesitateEvent.prototype.untrigger = function(event) {
|
||||
console.log('untrigger');
|
||||
if (this.timeoutEventId) {
|
||||
window.clearTimeout(this.timeoutEventId);
|
||||
$(this.originalEvent.delegateTarget).off(this.cancelSelector, this.untrigger);
|
||||
}
|
||||
this.timeoutEventId = null;
|
||||
}
|
||||
@@ -25,18 +25,18 @@ input.courseware-unit-search-input {
|
||||
width: 145px;
|
||||
|
||||
.status-label {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: -5px;
|
||||
display: none;
|
||||
width: 110px;
|
||||
padding: 5px 40px 5px 10px;
|
||||
@include border-radius(3px);
|
||||
color: $lightGrey;
|
||||
text-align: right;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
line-height: 16px;
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: -5px;
|
||||
display: none;
|
||||
width: 110px;
|
||||
padding: 5px 40px 5px 10px;
|
||||
@include border-radius(3px);
|
||||
color: $lightGrey;
|
||||
text-align: right;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.menu-toggle {
|
||||
@@ -643,4 +643,21 @@ input.courseware-unit-search-input {
|
||||
margin-top: 10px;
|
||||
font-size: 13px;
|
||||
color: $darkGrey;
|
||||
}
|
||||
}
|
||||
|
||||
// sort/drag and drop
|
||||
.ui-droppable {
|
||||
min-height: 20px;
|
||||
|
||||
&.dropover {
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
ol.ui-droppable .branch:first-child .section-item {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime
|
||||
from os.path import isdir
|
||||
from optparse import make_option
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.conf import settings
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
from student.models import TestCenterUser
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
|
||||
CSV_TO_MODEL_FIELDS = OrderedDict([
|
||||
# Skipping optional field CandidateID
|
||||
("ClientCandidateID", "client_candidate_id"),
|
||||
@@ -34,43 +36,52 @@ class Command(BaseCommand):
|
||||
("FAXCountryCode", "fax_country_code"),
|
||||
("CompanyName", "company_name"),
|
||||
# Skipping optional field CustomQuestion
|
||||
("LastUpdate", "user_updated_at"), # in UTC, so same as what we store
|
||||
("LastUpdate", "user_updated_at"), # in UTC, so same as what we store
|
||||
])
|
||||
|
||||
# define defaults, even thought 'store_true' shouldn't need them.
|
||||
# (call_command will set None as default value for all options that don't have one,
|
||||
# so one cannot rely on presence/absence of flags in that world.)
|
||||
option_list = BaseCommand.option_list + (
|
||||
make_option(
|
||||
'--dump_all',
|
||||
action='store_true',
|
||||
dest='dump_all',
|
||||
),
|
||||
make_option('--dest-from-settings',
|
||||
action='store_true',
|
||||
dest='dest-from-settings',
|
||||
default=False,
|
||||
help='Retrieve the destination to export to from django.'),
|
||||
make_option('--destination',
|
||||
action='store',
|
||||
dest='destination',
|
||||
default=None,
|
||||
help='Where to store the exported files')
|
||||
)
|
||||
|
||||
args = '<output_file_or_dir>'
|
||||
help = """
|
||||
Export user demographic information from TestCenterUser model into a tab delimited
|
||||
text file with a format that Pearson expects.
|
||||
"""
|
||||
def handle(self, *args, **kwargs):
|
||||
if len(args) < 1:
|
||||
print Command.help
|
||||
return
|
||||
|
||||
def handle(self, **options):
|
||||
# update time should use UTC in order to be comparable to the user_updated_at
|
||||
# field
|
||||
uploaded_at = datetime.utcnow()
|
||||
|
||||
# if specified destination is an existing directory, then
|
||||
# if specified destination is an existing directory, then
|
||||
# create a filename for it automatically. If it doesn't exist,
|
||||
# or exists as a file, then we will just write to it.
|
||||
# then we will create the directory.
|
||||
# Name will use timestamp -- this is UTC, so it will look funny,
|
||||
# but it should at least be consistent with the other timestamps
|
||||
# but it should at least be consistent with the other timestamps
|
||||
# used in the system.
|
||||
dest = args[0]
|
||||
if isdir(dest):
|
||||
destfile = os.path.join(dest, uploaded_at.strftime("cdd-%Y%m%d-%H%M%S.dat"))
|
||||
if 'dest-from-settings' in options and options['dest-from-settings']:
|
||||
if 'LOCAL_EXPORT' in settings.PEARSON:
|
||||
dest = settings.PEARSON['LOCAL_EXPORT']
|
||||
else:
|
||||
raise CommandError('--dest-from-settings was enabled but the'
|
||||
'PEARSON[LOCAL_EXPORT] setting was not set.')
|
||||
elif 'destination' in options and options['destination']:
|
||||
dest = options['destination']
|
||||
else:
|
||||
destfile = dest
|
||||
|
||||
raise CommandError('--destination or --dest-from-settings must be used')
|
||||
|
||||
if not os.path.isdir(dest):
|
||||
os.makedirs(dest)
|
||||
|
||||
destfile = os.path.join(dest, uploaded_at.strftime("cdd-%Y%m%d-%H%M%S.dat"))
|
||||
|
||||
# strings must be in latin-1 format. CSV parser will
|
||||
# otherwise convert unicode objects to ascii.
|
||||
def ensure_encoding(value):
|
||||
@@ -78,8 +89,8 @@ class Command(BaseCommand):
|
||||
return value.encode('iso-8859-1')
|
||||
else:
|
||||
return value
|
||||
|
||||
dump_all = kwargs['dump_all']
|
||||
|
||||
# dump_all = options['dump_all']
|
||||
|
||||
with open(destfile, "wb") as outfile:
|
||||
writer = csv.DictWriter(outfile,
|
||||
@@ -89,7 +100,7 @@ class Command(BaseCommand):
|
||||
extrasaction='ignore')
|
||||
writer.writeheader()
|
||||
for tcu in TestCenterUser.objects.order_by('id'):
|
||||
if dump_all or tcu.needs_uploading:
|
||||
if tcu.needs_uploading: # or dump_all
|
||||
record = dict((csv_field, ensure_encoding(getattr(tcu, model_field)))
|
||||
for csv_field, model_field
|
||||
in Command.CSV_TO_MODEL_FIELDS.items())
|
||||
@@ -97,6 +108,3 @@ class Command(BaseCommand):
|
||||
writer.writerow(record)
|
||||
tcu.uploaded_at = uploaded_at
|
||||
tcu.save()
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime
|
||||
from os.path import isdir, join
|
||||
from optparse import make_option
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.conf import settings
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
from student.models import TestCenterRegistration, ACCOMMODATION_REJECTED_CODE
|
||||
|
||||
from student.models import TestCenterRegistration
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
|
||||
CSV_TO_MODEL_FIELDS = OrderedDict([
|
||||
('AuthorizationTransactionType', 'authorization_transaction_type'),
|
||||
('AuthorizationID', 'authorization_id'),
|
||||
@@ -20,51 +22,60 @@ class Command(BaseCommand):
|
||||
('Accommodations', 'accommodation_code'),
|
||||
('EligibilityApptDateFirst', 'eligibility_appointment_date_first'),
|
||||
('EligibilityApptDateLast', 'eligibility_appointment_date_last'),
|
||||
("LastUpdate", "user_updated_at"), # in UTC, so same as what we store
|
||||
("LastUpdate", "user_updated_at"), # in UTC, so same as what we store
|
||||
])
|
||||
|
||||
args = '<output_file_or_dir>'
|
||||
help = """
|
||||
Export user registration information from TestCenterRegistration model into a tab delimited
|
||||
text file with a format that Pearson expects.
|
||||
"""
|
||||
|
||||
option_list = BaseCommand.option_list + (
|
||||
make_option(
|
||||
'--dump_all',
|
||||
action='store_true',
|
||||
dest='dump_all',
|
||||
),
|
||||
make_option(
|
||||
'--force_add',
|
||||
action='store_true',
|
||||
dest='force_add',
|
||||
),
|
||||
make_option('--dest-from-settings',
|
||||
action='store_true',
|
||||
dest='dest-from-settings',
|
||||
default=False,
|
||||
help='Retrieve the destination to export to from django.'),
|
||||
make_option('--destination',
|
||||
action='store',
|
||||
dest='destination',
|
||||
default=None,
|
||||
help='Where to store the exported files'),
|
||||
make_option('--dump_all',
|
||||
action='store_true',
|
||||
dest='dump_all',
|
||||
default=False,
|
||||
),
|
||||
make_option('--force_add',
|
||||
action='store_true',
|
||||
dest='force_add',
|
||||
default=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def handle(self, *args, **kwargs):
|
||||
if len(args) < 1:
|
||||
print Command.help
|
||||
return
|
||||
|
||||
# update time should use UTC in order to be comparable to the user_updated_at
|
||||
def handle(self, **options):
|
||||
# update time should use UTC in order to be comparable to the user_updated_at
|
||||
# field
|
||||
uploaded_at = datetime.utcnow()
|
||||
|
||||
# if specified destination is an existing directory, then
|
||||
# if specified destination is an existing directory, then
|
||||
# create a filename for it automatically. If it doesn't exist,
|
||||
# or exists as a file, then we will just write to it.
|
||||
# then we will create the directory.
|
||||
# Name will use timestamp -- this is UTC, so it will look funny,
|
||||
# but it should at least be consistent with the other timestamps
|
||||
# but it should at least be consistent with the other timestamps
|
||||
# used in the system.
|
||||
dest = args[0]
|
||||
if isdir(dest):
|
||||
destfile = join(dest, uploaded_at.strftime("ead-%Y%m%d-%H%M%S.dat"))
|
||||
if 'dest-from-settings' in options and options['dest-from-settings']:
|
||||
if 'LOCAL_EXPORT' in settings.PEARSON:
|
||||
dest = settings.PEARSON['LOCAL_EXPORT']
|
||||
else:
|
||||
raise CommandError('--dest-from-settings was enabled but the'
|
||||
'PEARSON[LOCAL_EXPORT] setting was not set.')
|
||||
elif 'destination' in options and options['destination']:
|
||||
dest = options['destination']
|
||||
else:
|
||||
destfile = dest
|
||||
raise CommandError('--destination or --dest-from-settings must be used')
|
||||
|
||||
dump_all = kwargs['dump_all']
|
||||
if not os.path.isdir(dest):
|
||||
os.makedirs(dest)
|
||||
|
||||
destfile = os.path.join(dest, uploaded_at.strftime("ead-%Y%m%d-%H%M%S.dat"))
|
||||
|
||||
dump_all = options['dump_all']
|
||||
|
||||
with open(destfile, "wb") as outfile:
|
||||
writer = csv.DictWriter(outfile,
|
||||
@@ -81,13 +92,11 @@ class Command(BaseCommand):
|
||||
record["LastUpdate"] = record["LastUpdate"].strftime("%Y/%m/%d %H:%M:%S")
|
||||
record["EligibilityApptDateFirst"] = record["EligibilityApptDateFirst"].strftime("%Y/%m/%d")
|
||||
record["EligibilityApptDateLast"] = record["EligibilityApptDateLast"].strftime("%Y/%m/%d")
|
||||
if kwargs['force_add']:
|
||||
if record["Accommodations"] == ACCOMMODATION_REJECTED_CODE:
|
||||
record["Accommodations"] = ""
|
||||
if options['force_add']:
|
||||
record['AuthorizationTransactionType'] = 'Add'
|
||||
|
||||
writer.writerow(record)
|
||||
tcr.uploaded_at = uploaded_at
|
||||
tcr.save()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import csv
|
||||
|
||||
from zipfile import ZipFile, is_zipfile
|
||||
from time import strptime, strftime
|
||||
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime
|
||||
from os.path import isdir
|
||||
from optparse import make_option
|
||||
from dogapi import dog_http_api, dog_stats_api
|
||||
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.conf import settings
|
||||
|
||||
from student.models import TestCenterUser, TestCenterRegistration
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
dog_http_api.api_key = settings.DATADOG_API
|
||||
args = '<input zip file>'
|
||||
help = """
|
||||
Import Pearson confirmation files and update TestCenterUser
|
||||
and TestCenterRegistration tables with status.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def datadog_error(string, tags):
|
||||
dog_http_api.event("Pearson Import", string, alert_type='error', tags=[tags])
|
||||
|
||||
def handle(self, *args, **kwargs):
|
||||
if len(args) < 1:
|
||||
print Command.help
|
||||
return
|
||||
|
||||
source_zip = args[0]
|
||||
if not is_zipfile(source_zip):
|
||||
error = "Input file is not a zipfile: \"{}\"".format(source_zip)
|
||||
Command.datadog_error(error, source_zip)
|
||||
raise CommandError(error)
|
||||
|
||||
# loop through all files in zip, and process them based on filename prefix:
|
||||
with ZipFile(source_zip, 'r') as zipfile:
|
||||
for fileinfo in zipfile.infolist():
|
||||
with zipfile.open(fileinfo) as zipentry:
|
||||
if fileinfo.filename.startswith("eac-"):
|
||||
self.process_eac(zipentry)
|
||||
elif fileinfo.filename.startswith("vcdc-"):
|
||||
self.process_vcdc(zipentry)
|
||||
else:
|
||||
error = "Unrecognized confirmation file type\"{}\" in confirmation zip file \"{}\"".format(fileinfo.filename, zipfile)
|
||||
Command.datadog_error(error, source_zip)
|
||||
raise CommandError(error)
|
||||
|
||||
def process_eac(self, eacfile):
|
||||
print "processing eac"
|
||||
reader = csv.DictReader(eacfile, delimiter="\t")
|
||||
for row in reader:
|
||||
client_authorization_id = row['ClientAuthorizationID']
|
||||
if not client_authorization_id:
|
||||
if row['Status'] == 'Error':
|
||||
Command.datadog_error("Error in EAD file processing ({}): {}".format(row['Date'], row['Message']), eacfile.name)
|
||||
else:
|
||||
Command.datadog_error("Encountered bad record: {}".format(row), eacfile.name)
|
||||
else:
|
||||
try:
|
||||
registration = TestCenterRegistration.objects.get(client_authorization_id=client_authorization_id)
|
||||
Command.datadog_error("Found authorization record for user {}".format(registration.testcenter_user.user.username), eacfile)
|
||||
# now update the record:
|
||||
registration.upload_status = row['Status']
|
||||
registration.upload_error_message = row['Message']
|
||||
try:
|
||||
registration.processed_at = strftime('%Y-%m-%d %H:%M:%S', strptime(row['Date'], '%Y/%m/%d %H:%M:%S'))
|
||||
except ValueError as ve:
|
||||
Command.datadog_error("Bad Date value found for {}: message {}".format(client_authorization_id, ve), eacfile.name)
|
||||
# store the authorization Id if one is provided. (For debugging)
|
||||
if row['AuthorizationID']:
|
||||
try:
|
||||
registration.authorization_id = int(row['AuthorizationID'])
|
||||
except ValueError as ve:
|
||||
Command.datadog_error("Bad AuthorizationID value found for {}: message {}".format(client_authorization_id, ve), eacfile.name)
|
||||
|
||||
registration.confirmed_at = datetime.utcnow()
|
||||
registration.save()
|
||||
except TestCenterRegistration.DoesNotExist:
|
||||
Command.datadog_error("Failed to find record for client_auth_id {}".format(client_authorization_id), eacfile.name)
|
||||
|
||||
def process_vcdc(self, vcdcfile):
|
||||
print "processing vcdc"
|
||||
reader = csv.DictReader(vcdcfile, delimiter="\t")
|
||||
for row in reader:
|
||||
client_candidate_id = row['ClientCandidateID']
|
||||
if not client_candidate_id:
|
||||
if row['Status'] == 'Error':
|
||||
Command.datadog_error("Error in CDD file processing ({}): {}".format(row['Date'], row['Message']), vcdcfile.name)
|
||||
else:
|
||||
Command.datadog_error("Encountered bad record: {}".format(row), vcdcfile.name)
|
||||
else:
|
||||
try:
|
||||
tcuser = TestCenterUser.objects.get(client_candidate_id=client_candidate_id)
|
||||
Command.datadog_error("Found demographics record for user {}".format(tcuser.user.username), vcdcfile.name)
|
||||
# now update the record:
|
||||
tcuser.upload_status = row['Status']
|
||||
tcuser.upload_error_message = row['Message']
|
||||
try:
|
||||
tcuser.processed_at = strftime('%Y-%m-%d %H:%M:%S', strptime(row['Date'], '%Y/%m/%d %H:%M:%S'))
|
||||
except ValueError as ve:
|
||||
Command.datadog_error("Bad Date value found for {}: message {}".format(client_candidate_id, ve), vcdcfile.name)
|
||||
# store the candidate Id if one is provided. (For debugging)
|
||||
if row['CandidateID']:
|
||||
try:
|
||||
tcuser.candidate_id = int(row['CandidateID'])
|
||||
except ValueError as ve:
|
||||
Command.datadog_error("Bad CandidateID value found for {}: message {}".format(client_candidate_id, ve), vcdcfile.name)
|
||||
tcuser.confirmed_at = datetime.utcnow()
|
||||
tcuser.save()
|
||||
except TestCenterUser.DoesNotExist:
|
||||
Command.datadog_error(" Failed to find record for client_candidate_id {}".format(client_candidate_id), vcdcfile.name)
|
||||
|
||||
@@ -71,6 +71,12 @@ class Command(BaseCommand):
|
||||
dest='ignore_registration_dates',
|
||||
help='find exam info for course based on exam_series_code, even if the exam is not active.'
|
||||
),
|
||||
make_option(
|
||||
'--create_dummy_exam',
|
||||
action='store_true',
|
||||
dest='create_dummy_exam',
|
||||
help='create dummy exam info for course, even if course exists'
|
||||
),
|
||||
)
|
||||
args = "<student_username course_id>"
|
||||
help = "Create or modify a TestCenterRegistration entry for a given Student"
|
||||
@@ -98,15 +104,20 @@ class Command(BaseCommand):
|
||||
except TestCenterUser.DoesNotExist:
|
||||
raise CommandError("User \"{}\" does not have an existing demographics record".format(username))
|
||||
|
||||
# check to see if a course_id was specified, and use information from that:
|
||||
try:
|
||||
course = course_from_id(course_id)
|
||||
if 'ignore_registration_dates' in our_options:
|
||||
examlist = [exam for exam in course.test_center_exams if exam.exam_series_code == our_options.get('exam_series_code')]
|
||||
exam = examlist[0] if len(examlist) > 0 else None
|
||||
else:
|
||||
exam = course.current_test_center_exam
|
||||
except ItemNotFoundError:
|
||||
# get an "exam" object. Check to see if a course_id was specified, and use information from that:
|
||||
exam = None
|
||||
create_dummy_exam = 'create_dummy_exam' in our_options and our_options['create_dummy_exam']
|
||||
if not create_dummy_exam:
|
||||
try:
|
||||
course = course_from_id(course_id)
|
||||
if 'ignore_registration_dates' in our_options:
|
||||
examlist = [exam for exam in course.test_center_exams if exam.exam_series_code == our_options.get('exam_series_code')]
|
||||
exam = examlist[0] if len(examlist) > 0 else None
|
||||
else:
|
||||
exam = course.current_test_center_exam
|
||||
except ItemNotFoundError:
|
||||
pass
|
||||
else:
|
||||
# otherwise use explicit values (so we don't have to define a course):
|
||||
exam_name = "Dummy Placeholder Name"
|
||||
exam_info = { 'Exam_Series_Code': our_options['exam_series_code'],
|
||||
@@ -120,7 +131,7 @@ class Command(BaseCommand):
|
||||
our_options['eligibility_appointment_date_last'] = strftime("%Y-%m-%d", exam.last_eligible_appointment_date)
|
||||
|
||||
if exam is None:
|
||||
raise CommandError("Exam for course_id {%s} does not exist".format(course_id))
|
||||
raise CommandError("Exam for course_id {} does not exist".format(course_id))
|
||||
|
||||
exam_code = exam.exam_series_code
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from optparse import make_option
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
from student.models import TestCenterUser, TestCenterUserForm
|
||||
|
||||
@@ -161,15 +161,16 @@ class Command(BaseCommand):
|
||||
if form.is_valid():
|
||||
form.update_and_save()
|
||||
else:
|
||||
errorlist = []
|
||||
if (len(form.errors) > 0):
|
||||
print "Field Form errors encountered:"
|
||||
for fielderror in form.errors:
|
||||
print "Field Form Error: %s" % fielderror
|
||||
if (len(form.non_field_errors()) > 0):
|
||||
print "Non-field Form errors encountered:"
|
||||
for nonfielderror in form.non_field_errors:
|
||||
print "Non-field Form Error: %s" % nonfielderror
|
||||
|
||||
errorlist.append("Field Form errors encountered:")
|
||||
for fielderror in form.errors:
|
||||
errorlist.append("Field Form Error: {}".format(fielderror))
|
||||
if (len(form.non_field_errors()) > 0):
|
||||
errorlist.append("Non-field Form errors encountered:")
|
||||
for nonfielderror in form.non_field_errors:
|
||||
errorlist.append("Non-field Form Error: {}".format(nonfielderror))
|
||||
raise CommandError("\n".join(errorlist))
|
||||
else:
|
||||
print "No changes necessary to make to existing user's demographics."
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import os
|
||||
from optparse import make_option
|
||||
from stat import S_ISDIR
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.core.management import call_command
|
||||
from dogapi import dog_http_api, dog_stats_api
|
||||
import paramiko
|
||||
import boto
|
||||
|
||||
dog_http_api.api_key = settings.DATADOG_API
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = """
|
||||
This command handles the importing and exporting of student records for
|
||||
Pearson. It uses some other Django commands to export and import the
|
||||
files and then uploads over SFTP to Pearson and stuffs the entry in an
|
||||
S3 bucket for archive purposes.
|
||||
|
||||
Usage: django-admin.py pearson-transfer --mode [import|export|both]
|
||||
"""
|
||||
|
||||
option_list = BaseCommand.option_list + (
|
||||
make_option('--mode',
|
||||
action='store',
|
||||
dest='mode',
|
||||
default='both',
|
||||
choices=('import', 'export', 'both'),
|
||||
help='mode is import, export, or both'),
|
||||
)
|
||||
|
||||
def handle(self, **options):
|
||||
|
||||
if not hasattr(settings, 'PEARSON'):
|
||||
raise CommandError('No PEARSON entries in auth/env.json.')
|
||||
|
||||
# check settings needed for either import or export:
|
||||
for value in ['SFTP_HOSTNAME', 'SFTP_USERNAME', 'SFTP_PASSWORD', 'S3_BUCKET']:
|
||||
if value not in settings.PEARSON:
|
||||
raise CommandError('No entry in the PEARSON settings'
|
||||
'(env/auth.json) for {0}'.format(value))
|
||||
|
||||
for value in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']:
|
||||
if not hasattr(settings, value):
|
||||
raise CommandError('No entry in the AWS settings'
|
||||
'(env/auth.json) for {0}'.format(value))
|
||||
|
||||
# check additional required settings for import and export:
|
||||
if options['mode'] in ('export', 'both'):
|
||||
for value in ['LOCAL_EXPORT','SFTP_EXPORT']:
|
||||
if value not in settings.PEARSON:
|
||||
raise CommandError('No entry in the PEARSON settings'
|
||||
'(env/auth.json) for {0}'.format(value))
|
||||
# make sure that the import directory exists or can be created:
|
||||
source_dir = settings.PEARSON['LOCAL_EXPORT']
|
||||
if not os.path.isdir(source_dir):
|
||||
os.makedirs(source_dir)
|
||||
|
||||
if options['mode'] in ('import', 'both'):
|
||||
for value in ['LOCAL_IMPORT','SFTP_IMPORT']:
|
||||
if value not in settings.PEARSON:
|
||||
raise CommandError('No entry in the PEARSON settings'
|
||||
'(env/auth.json) for {0}'.format(value))
|
||||
# make sure that the import directory exists or can be created:
|
||||
dest_dir = settings.PEARSON['LOCAL_IMPORT']
|
||||
if not os.path.isdir(dest_dir):
|
||||
os.makedirs(dest_dir)
|
||||
|
||||
|
||||
def sftp(files_from, files_to, mode, deleteAfterCopy=False):
|
||||
with dog_stats_api.timer('pearson.{0}'.format(mode), tags='sftp'):
|
||||
try:
|
||||
t = paramiko.Transport((settings.PEARSON['SFTP_HOSTNAME'], 22))
|
||||
t.connect(username=settings.PEARSON['SFTP_USERNAME'],
|
||||
password=settings.PEARSON['SFTP_PASSWORD'])
|
||||
sftp = paramiko.SFTPClient.from_transport(t)
|
||||
|
||||
if mode == 'export':
|
||||
try:
|
||||
sftp.chdir(files_to)
|
||||
except IOError:
|
||||
raise CommandError('SFTP destination path does not exist: {}'.format(files_to))
|
||||
for filename in os.listdir(files_from):
|
||||
sftp.put(files_from + '/' + filename, filename)
|
||||
if deleteAfterCopy:
|
||||
os.remove(os.path.join(files_from, filename))
|
||||
else:
|
||||
try:
|
||||
sftp.chdir(files_from)
|
||||
except IOError:
|
||||
raise CommandError('SFTP source path does not exist: {}'.format(files_from))
|
||||
for filename in sftp.listdir('.'):
|
||||
# skip subdirectories
|
||||
if not S_ISDIR(sftp.stat(filename).st_mode):
|
||||
sftp.get(filename, files_to + '/' + filename)
|
||||
# delete files from sftp server once they are successfully pulled off:
|
||||
if deleteAfterCopy:
|
||||
sftp.remove(filename)
|
||||
except:
|
||||
dog_http_api.event('pearson {0}'.format(mode),
|
||||
'sftp uploading failed',
|
||||
alert_type='error')
|
||||
raise
|
||||
finally:
|
||||
sftp.close()
|
||||
t.close()
|
||||
|
||||
def s3(files_from, bucket, mode, deleteAfterCopy=False):
|
||||
with dog_stats_api.timer('pearson.{0}'.format(mode), tags='s3'):
|
||||
try:
|
||||
for filename in os.listdir(files_from):
|
||||
source_file = os.path.join(files_from, filename)
|
||||
# use mode as name of directory into which to write files
|
||||
dest_file = os.path.join(mode, filename)
|
||||
upload_file_to_s3(bucket, source_file, dest_file)
|
||||
if deleteAfterCopy:
|
||||
os.remove(files_from + '/' + filename)
|
||||
except:
|
||||
dog_http_api.event('pearson {0}'.format(mode),
|
||||
's3 archiving failed')
|
||||
raise
|
||||
|
||||
def upload_file_to_s3(bucket, source_file, dest_file):
|
||||
"""
|
||||
Upload file to S3
|
||||
"""
|
||||
s3 = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
|
||||
settings.AWS_SECRET_ACCESS_KEY)
|
||||
from boto.s3.key import Key
|
||||
b = s3.get_bucket(bucket)
|
||||
k = Key(b)
|
||||
k.key = "{filename}".format(filename=dest_file)
|
||||
k.set_contents_from_filename(source_file)
|
||||
|
||||
def export_pearson():
|
||||
options = { 'dest-from-settings' : True }
|
||||
call_command('pearson_export_cdd', **options)
|
||||
call_command('pearson_export_ead', **options)
|
||||
mode = 'export'
|
||||
sftp(settings.PEARSON['LOCAL_EXPORT'], settings.PEARSON['SFTP_EXPORT'], mode, deleteAfterCopy = False)
|
||||
s3(settings.PEARSON['LOCAL_EXPORT'], settings.PEARSON['S3_BUCKET'], mode, deleteAfterCopy=True)
|
||||
|
||||
def import_pearson():
|
||||
mode = 'import'
|
||||
try:
|
||||
sftp(settings.PEARSON['SFTP_IMPORT'], settings.PEARSON['LOCAL_IMPORT'], mode, deleteAfterCopy = True)
|
||||
s3(settings.PEARSON['LOCAL_IMPORT'], settings.PEARSON['S3_BUCKET'], mode, deleteAfterCopy=False)
|
||||
except Exception as e:
|
||||
dog_http_api.event('Pearson Import failure', str(e))
|
||||
raise e
|
||||
else:
|
||||
for filename in os.listdir(settings.PEARSON['LOCAL_IMPORT']):
|
||||
filepath = os.path.join(settings.PEARSON['LOCAL_IMPORT'], filename)
|
||||
call_command('pearson_import_conf_zip', filepath)
|
||||
os.remove(filepath)
|
||||
|
||||
# actually do the work!
|
||||
if options['mode'] in ('export', 'both'):
|
||||
export_pearson()
|
||||
if options['mode'] in ('import', 'both'):
|
||||
import_pearson()
|
||||
@@ -0,0 +1,382 @@
|
||||
'''
|
||||
Created on Jan 17, 2013
|
||||
|
||||
@author: brian
|
||||
'''
|
||||
import logging
|
||||
import os
|
||||
from tempfile import mkdtemp
|
||||
import cStringIO
|
||||
import sys
|
||||
|
||||
from django.test import TestCase
|
||||
from django.core.management import call_command
|
||||
from nose.plugins.skip import SkipTest
|
||||
|
||||
from student.models import User, TestCenterRegistration, TestCenterUser, get_testcenter_registration
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
def create_tc_user(username):
|
||||
user = User.objects.create_user(username, '{}@edx.org'.format(username), 'fakepass')
|
||||
options = {
|
||||
'first_name' : 'TestFirst',
|
||||
'last_name' : 'TestLast',
|
||||
'address_1' : 'Test Address',
|
||||
'city' : 'TestCity',
|
||||
'state' : 'Alberta',
|
||||
'postal_code' : 'A0B 1C2',
|
||||
'country' : 'CAN',
|
||||
'phone' : '252-1866',
|
||||
'phone_country_code' : '1',
|
||||
}
|
||||
call_command('pearson_make_tc_user', username, **options)
|
||||
return TestCenterUser.objects.get(user=user)
|
||||
|
||||
|
||||
def create_tc_registration(username, course_id = 'org1/course1/term1', exam_code = 'exam1', accommodation_code = None):
|
||||
|
||||
options = { 'exam_series_code' : exam_code,
|
||||
'eligibility_appointment_date_first' : '2013-01-01T00:00',
|
||||
'eligibility_appointment_date_last' : '2013-12-31T23:59',
|
||||
'accommodation_code' : accommodation_code,
|
||||
}
|
||||
|
||||
call_command('pearson_make_tc_registration', username, course_id, **options)
|
||||
user = User.objects.get(username=username)
|
||||
registrations = get_testcenter_registration(user, course_id, exam_code)
|
||||
return registrations[0]
|
||||
|
||||
def create_multiple_registrations(prefix='test'):
|
||||
username1 = '{}_multiple1'.format(prefix)
|
||||
create_tc_user(username1)
|
||||
create_tc_registration(username1)
|
||||
create_tc_registration(username1, course_id = 'org1/course2/term1')
|
||||
create_tc_registration(username1, exam_code = 'exam2')
|
||||
username2 = '{}_multiple2'.format(prefix)
|
||||
create_tc_user(username2)
|
||||
create_tc_registration(username2)
|
||||
username3 = '{}_multiple3'.format(prefix)
|
||||
create_tc_user(username3)
|
||||
create_tc_registration(username3, course_id = 'org1/course2/term1')
|
||||
username4 = '{}_multiple4'.format(prefix)
|
||||
create_tc_user(username4)
|
||||
create_tc_registration(username4, exam_code = 'exam2')
|
||||
|
||||
def get_command_error_text(*args, **options):
|
||||
stderr_string = None
|
||||
old_stderr = sys.stderr
|
||||
sys.stderr = cStringIO.StringIO()
|
||||
try:
|
||||
call_command(*args, **options)
|
||||
except SystemExit, why1:
|
||||
# The goal here is to catch CommandError calls.
|
||||
# But these are actually translated into nice messages,
|
||||
# and sys.exit(1) is then called. For testing, we
|
||||
# want to catch what sys.exit throws, and get the
|
||||
# relevant text either from stdout or stderr.
|
||||
if (why1.message > 0):
|
||||
stderr_string = sys.stderr.getvalue()
|
||||
else:
|
||||
raise why1
|
||||
except Exception, why:
|
||||
raise why
|
||||
|
||||
finally:
|
||||
sys.stderr = old_stderr
|
||||
|
||||
if stderr_string is None:
|
||||
raise Exception("Expected call to {} to fail, but it succeeded!".format(args[0]))
|
||||
return stderr_string
|
||||
|
||||
def get_error_string_for_management_call(*args, **options):
|
||||
stdout_string = None
|
||||
old_stdout = sys.stdout
|
||||
old_stderr = sys.stderr
|
||||
sys.stdout = cStringIO.StringIO()
|
||||
sys.stderr = cStringIO.StringIO()
|
||||
try:
|
||||
call_command(*args, **options)
|
||||
except SystemExit, why1:
|
||||
# The goal here is to catch CommandError calls.
|
||||
# But these are actually translated into nice messages,
|
||||
# and sys.exit(1) is then called. For testing, we
|
||||
# want to catch what sys.exit throws, and get the
|
||||
# relevant text either from stdout or stderr.
|
||||
if (why1.message == 1):
|
||||
stdout_string = sys.stdout.getvalue()
|
||||
stderr_string = sys.stderr.getvalue()
|
||||
else:
|
||||
raise why1
|
||||
except Exception, why:
|
||||
raise why
|
||||
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
sys.stderr = old_stderr
|
||||
|
||||
if stdout_string is None:
|
||||
raise Exception("Expected call to {} to fail, but it succeeded!".format(args[0]))
|
||||
return stdout_string, stderr_string
|
||||
|
||||
|
||||
def get_file_info(dirpath):
|
||||
filelist = os.listdir(dirpath)
|
||||
print 'Files found: {}'.format(filelist)
|
||||
numfiles = len(filelist)
|
||||
if numfiles == 1:
|
||||
filepath = os.path.join(dirpath, filelist[0])
|
||||
with open(filepath, 'r') as cddfile:
|
||||
filecontents = cddfile.readlines()
|
||||
numlines = len(filecontents)
|
||||
return filepath, numlines
|
||||
else:
|
||||
raise Exception("Expected to find a single file in {}, but found {}".format(dirpath,filelist))
|
||||
|
||||
class PearsonTestCase(TestCase):
|
||||
'''
|
||||
Base class for tests running Pearson-related commands
|
||||
'''
|
||||
import_dir = mkdtemp(prefix="import")
|
||||
export_dir = mkdtemp(prefix="export")
|
||||
|
||||
def assertErrorContains(self, error_message, expected):
|
||||
self.assertTrue(error_message.find(expected) >= 0, 'error message "{}" did not contain "{}"'.format(error_message, expected))
|
||||
|
||||
def tearDown(self):
|
||||
def delete_temp_dir(dirname):
|
||||
if os.path.exists(dirname):
|
||||
for filename in os.listdir(dirname):
|
||||
os.remove(os.path.join(dirname, filename))
|
||||
os.rmdir(dirname)
|
||||
|
||||
# clean up after any test data was dumped to temp directory
|
||||
delete_temp_dir(self.import_dir)
|
||||
delete_temp_dir(self.export_dir)
|
||||
|
||||
# and clean up the database:
|
||||
# TestCenterUser.objects.all().delete()
|
||||
# TestCenterRegistration.objects.all().delete()
|
||||
|
||||
class PearsonCommandTestCase(PearsonTestCase):
|
||||
|
||||
def test_missing_demographic_fields(self):
|
||||
# We won't bother to test all details of form validation here.
|
||||
# It is enough to show that it works here, but deal with test cases for the form
|
||||
# validation in the student tests, not these management tests.
|
||||
username = 'baduser'
|
||||
User.objects.create_user(username, '{}@edx.org'.format(username), 'fakepass')
|
||||
options = {}
|
||||
error_string = get_command_error_text('pearson_make_tc_user', username, **options)
|
||||
self.assertTrue(error_string.find('Field Form errors encountered:') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: city') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: first_name') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: last_name') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: country') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: phone_country_code') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: phone') >= 0)
|
||||
self.assertTrue(error_string.find('Field Form Error: address_1') >= 0)
|
||||
self.assertErrorContains(error_string, 'Field Form Error: address_1')
|
||||
|
||||
def test_create_good_testcenter_user(self):
|
||||
testcenter_user = create_tc_user("test1")
|
||||
self.assertIsNotNone(testcenter_user)
|
||||
|
||||
def test_create_good_testcenter_registration(self):
|
||||
username = 'test1'
|
||||
create_tc_user(username)
|
||||
registration = create_tc_registration(username)
|
||||
self.assertIsNotNone(registration)
|
||||
|
||||
def test_cdd_missing_option(self):
|
||||
error_string = get_command_error_text('pearson_export_cdd', **{})
|
||||
self.assertErrorContains(error_string, 'Error: --destination or --dest-from-settings must be used')
|
||||
|
||||
def test_ead_missing_option(self):
|
||||
error_string = get_command_error_text('pearson_export_ead', **{})
|
||||
self.assertErrorContains(error_string, 'Error: --destination or --dest-from-settings must be used')
|
||||
|
||||
def test_export_single_cdd(self):
|
||||
# before we generate any tc_users, we expect there to be nothing to output:
|
||||
options = { 'dest-from-settings' : True }
|
||||
with self.settings(PEARSON={ 'LOCAL_EXPORT' : self.export_dir }):
|
||||
call_command('pearson_export_cdd', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 1, "Expect cdd file to have no non-header lines")
|
||||
os.remove(filepath)
|
||||
|
||||
# generating a tc_user should result in a line in the output
|
||||
username = 'test_single_cdd'
|
||||
create_tc_user(username)
|
||||
call_command('pearson_export_cdd', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 2, "Expect cdd file to have one non-header line")
|
||||
os.remove(filepath)
|
||||
|
||||
# output after registration should not have any entries again.
|
||||
call_command('pearson_export_cdd', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 1, "Expect cdd file to have no non-header lines")
|
||||
os.remove(filepath)
|
||||
|
||||
# if we modify the record, then it should be output again:
|
||||
user_options = { 'first_name' : 'NewTestFirst', }
|
||||
call_command('pearson_make_tc_user', username, **user_options)
|
||||
call_command('pearson_export_cdd', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 2, "Expect cdd file to have one non-header line")
|
||||
os.remove(filepath)
|
||||
|
||||
def test_export_single_ead(self):
|
||||
# before we generate any registrations, we expect there to be nothing to output:
|
||||
options = { 'dest-from-settings' : True }
|
||||
with self.settings(PEARSON={ 'LOCAL_EXPORT' : self.export_dir }):
|
||||
call_command('pearson_export_ead', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 1, "Expect ead file to have no non-header lines")
|
||||
os.remove(filepath)
|
||||
|
||||
# generating a registration should result in a line in the output
|
||||
username = 'test_single_ead'
|
||||
create_tc_user(username)
|
||||
create_tc_registration(username)
|
||||
call_command('pearson_export_ead', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 2, "Expect ead file to have one non-header line")
|
||||
os.remove(filepath)
|
||||
|
||||
# output after registration should not have any entries again.
|
||||
call_command('pearson_export_ead', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 1, "Expect ead file to have no non-header lines")
|
||||
os.remove(filepath)
|
||||
|
||||
# if we modify the record, then it should be output again:
|
||||
create_tc_registration(username, accommodation_code='EQPMNT')
|
||||
call_command('pearson_export_ead', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 2, "Expect ead file to have one non-header line")
|
||||
os.remove(filepath)
|
||||
|
||||
def test_export_multiple(self):
|
||||
create_multiple_registrations("export")
|
||||
with self.settings(PEARSON={ 'LOCAL_EXPORT' : self.export_dir }):
|
||||
options = { 'dest-from-settings' : True }
|
||||
call_command('pearson_export_cdd', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 5, "Expect cdd file to have four non-header lines: total was {}".format(numlines))
|
||||
os.remove(filepath)
|
||||
|
||||
call_command('pearson_export_ead', **options)
|
||||
(filepath, numlines) = get_file_info(self.export_dir)
|
||||
self.assertEquals(numlines, 7, "Expect ead file to have six non-header lines: total was {}".format(numlines))
|
||||
os.remove(filepath)
|
||||
|
||||
|
||||
# def test_bad_demographic_option(self):
|
||||
# username = 'nonuser'
|
||||
# output_string, stderrmsg = get_error_string_for_management_call('pearson_make_tc_user', username, **{'--garbage' : None })
|
||||
# print stderrmsg
|
||||
# self.assertErrorContains(stderrmsg, 'Unexpected option')
|
||||
#
|
||||
# def test_missing_demographic_user(self):
|
||||
# username = 'nonuser'
|
||||
# output_string, error_string = get_error_string_for_management_call('pearson_make_tc_user', username, **{})
|
||||
# self.assertErrorContains(error_string, 'User matching query does not exist')
|
||||
|
||||
# credentials for a test SFTP site:
|
||||
SFTP_HOSTNAME = 'ec2-23-20-150-101.compute-1.amazonaws.com'
|
||||
SFTP_USERNAME = 'pearsontest'
|
||||
SFTP_PASSWORD = 'password goes here'
|
||||
|
||||
S3_BUCKET = 'edx-pearson-archive'
|
||||
AWS_ACCESS_KEY_ID = 'put yours here'
|
||||
AWS_SECRET_ACCESS_KEY = 'put yours here'
|
||||
|
||||
class PearsonTransferTestCase(PearsonTestCase):
|
||||
'''
|
||||
Class for tests running Pearson transfers
|
||||
'''
|
||||
|
||||
def test_transfer_config(self):
|
||||
with self.settings(DATADOG_API='FAKE_KEY'):
|
||||
# TODO: why is this failing with the wrong error message?!
|
||||
stderrmsg = get_command_error_text('pearson_transfer', **{'mode' : 'garbage'})
|
||||
self.assertErrorContains(stderrmsg, 'Error: No PEARSON entries')
|
||||
with self.settings(DATADOG_API='FAKE_KEY'):
|
||||
stderrmsg = get_command_error_text('pearson_transfer')
|
||||
self.assertErrorContains(stderrmsg, 'Error: No PEARSON entries')
|
||||
with self.settings(DATADOG_API='FAKE_KEY',
|
||||
PEARSON={'LOCAL_EXPORT' : self.export_dir,
|
||||
'LOCAL_IMPORT' : self.import_dir }):
|
||||
stderrmsg = get_command_error_text('pearson_transfer')
|
||||
self.assertErrorContains(stderrmsg, 'Error: No entry in the PEARSON settings')
|
||||
|
||||
def test_transfer_export_missing_dest_dir(self):
|
||||
raise SkipTest()
|
||||
create_multiple_registrations('export_missing_dest')
|
||||
with self.settings(DATADOG_API='FAKE_KEY',
|
||||
PEARSON={'LOCAL_EXPORT' : self.export_dir,
|
||||
'SFTP_EXPORT' : 'this/does/not/exist',
|
||||
'SFTP_HOSTNAME' : SFTP_HOSTNAME,
|
||||
'SFTP_USERNAME' : SFTP_USERNAME,
|
||||
'SFTP_PASSWORD' : SFTP_PASSWORD,
|
||||
'S3_BUCKET' : S3_BUCKET,
|
||||
},
|
||||
AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID,
|
||||
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY):
|
||||
options = { 'mode' : 'export'}
|
||||
stderrmsg = get_command_error_text('pearson_transfer', **options)
|
||||
self.assertErrorContains(stderrmsg, 'Error: SFTP destination path does not exist')
|
||||
|
||||
def test_transfer_export(self):
|
||||
raise SkipTest()
|
||||
create_multiple_registrations("transfer_export")
|
||||
with self.settings(DATADOG_API='FAKE_KEY',
|
||||
PEARSON={'LOCAL_EXPORT' : self.export_dir,
|
||||
'SFTP_EXPORT' : 'results/topvue',
|
||||
'SFTP_HOSTNAME' : SFTP_HOSTNAME,
|
||||
'SFTP_USERNAME' : SFTP_USERNAME,
|
||||
'SFTP_PASSWORD' : SFTP_PASSWORD,
|
||||
'S3_BUCKET' : S3_BUCKET,
|
||||
},
|
||||
AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID,
|
||||
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY):
|
||||
options = { 'mode' : 'export'}
|
||||
# call_command('pearson_transfer', **options)
|
||||
# # confirm that the export directory is still empty:
|
||||
# self.assertEqual(len(os.listdir(self.export_dir)), 0, "expected export directory to be empty")
|
||||
|
||||
def test_transfer_import_missing_source_dir(self):
|
||||
raise SkipTest()
|
||||
create_multiple_registrations('import_missing_src')
|
||||
with self.settings(DATADOG_API='FAKE_KEY',
|
||||
PEARSON={'LOCAL_IMPORT' : self.import_dir,
|
||||
'SFTP_IMPORT' : 'this/does/not/exist',
|
||||
'SFTP_HOSTNAME' : SFTP_HOSTNAME,
|
||||
'SFTP_USERNAME' : SFTP_USERNAME,
|
||||
'SFTP_PASSWORD' : SFTP_PASSWORD,
|
||||
'S3_BUCKET' : S3_BUCKET,
|
||||
},
|
||||
AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID,
|
||||
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY):
|
||||
options = { 'mode' : 'import'}
|
||||
stderrmsg = get_command_error_text('pearson_transfer', **options)
|
||||
self.assertErrorContains(stderrmsg, 'Error: SFTP source path does not exist')
|
||||
|
||||
def test_transfer_import(self):
|
||||
raise SkipTest()
|
||||
create_multiple_registrations('import_missing_src')
|
||||
with self.settings(DATADOG_API='FAKE_KEY',
|
||||
PEARSON={'LOCAL_IMPORT' : self.import_dir,
|
||||
'SFTP_IMPORT' : 'results',
|
||||
'SFTP_HOSTNAME' : SFTP_HOSTNAME,
|
||||
'SFTP_USERNAME' : SFTP_USERNAME,
|
||||
'SFTP_PASSWORD' : SFTP_PASSWORD,
|
||||
'S3_BUCKET' : S3_BUCKET,
|
||||
},
|
||||
AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID,
|
||||
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY):
|
||||
options = { 'mode' : 'import'}
|
||||
call_command('pearson_transfer', **options)
|
||||
self.assertEqual(len(os.listdir(self.import_dir)), 0, "expected import directory to be empty")
|
||||
@@ -402,7 +402,11 @@ class TestCenterRegistration(models.Model):
|
||||
def exam_authorization_count(self):
|
||||
# TODO: figure out if this should really go in the database (with a default value).
|
||||
return 1
|
||||
|
||||
|
||||
@property
|
||||
def needs_uploading(self):
|
||||
return self.uploaded_at is None or self.uploaded_at < self.user_updated_at
|
||||
|
||||
@classmethod
|
||||
def create(cls, testcenter_user, exam, accommodation_request):
|
||||
registration = cls(testcenter_user = testcenter_user)
|
||||
@@ -525,6 +529,10 @@ def get_testcenter_registration(user, course_id, exam_series_code):
|
||||
return []
|
||||
return TestCenterRegistration.objects.filter(testcenter_user=tcu, course_id=course_id, exam_series_code=exam_series_code)
|
||||
|
||||
# nosetests thinks that anything with _test_ in the name is a test.
|
||||
# Correct this (https://nose.readthedocs.org/en/latest/finding_tests.html)
|
||||
get_testcenter_registration.__test__ = False
|
||||
|
||||
def unique_id_for_user(user):
|
||||
"""
|
||||
Return a unique id for a user, suitable for inserting into
|
||||
|
||||
@@ -116,9 +116,11 @@ class CapaModule(XModule):
|
||||
self.grace_period = None
|
||||
self.close_date = self.display_due_date
|
||||
|
||||
self.max_attempts = self.metadata.get('attempts', None)
|
||||
if self.max_attempts is not None:
|
||||
self.max_attempts = int(self.max_attempts)
|
||||
max_attempts = self.metadata.get('attempts', None)
|
||||
if max_attempts:
|
||||
self.max_attempts = int(max_attempts)
|
||||
else:
|
||||
self.max_attempts = None
|
||||
|
||||
self.show_answer = self.metadata.get('showanswer', 'closed')
|
||||
|
||||
|
||||
@@ -690,7 +690,7 @@ class CourseDescriptor(SequenceDescriptor):
|
||||
|
||||
@property
|
||||
def registration_end_date_text(self):
|
||||
return time.strftime("%b %d, %Y", self.registration_end_date)
|
||||
return time.strftime("%b %d, %Y at %H:%M UTC", self.registration_end_date)
|
||||
|
||||
@property
|
||||
def current_test_center_exam(self):
|
||||
|
||||
@@ -8,13 +8,13 @@ define('ElOutput', ['logme'], function (logme) {
|
||||
|
||||
function ElOutput(config, state) {
|
||||
|
||||
if ($.isPlainObject(config.functions.function)) {
|
||||
processFuncObj(config.functions.function);
|
||||
} else if ($.isArray(config.functions.function)) {
|
||||
if ($.isPlainObject(config.functions["function"])) {
|
||||
processFuncObj(config.functions["function"]);
|
||||
} else if ($.isArray(config.functions["function"])) {
|
||||
(function (c1) {
|
||||
while (c1 < config.functions.function.length) {
|
||||
if ($.isPlainObject(config.functions.function[c1])) {
|
||||
processFuncObj(config.functions.function[c1]);
|
||||
while (c1 < config.functions["function"].length) {
|
||||
if ($.isPlainObject(config.functions["function"][c1])) {
|
||||
processFuncObj(config.functions["function"][c1]);
|
||||
}
|
||||
|
||||
c1 += 1;
|
||||
|
||||
@@ -6,13 +6,13 @@ define('GLabelElOutput', ['logme'], function (logme) {
|
||||
return GLabelElOutput;
|
||||
|
||||
function GLabelElOutput(config, state) {
|
||||
if ($.isPlainObject(config.functions.function)) {
|
||||
processFuncObj(config.functions.function);
|
||||
} else if ($.isArray(config.functions.function)) {
|
||||
if ($.isPlainObject(config.functions["function"])) {
|
||||
processFuncObj(config.functions["function"]);
|
||||
} else if ($.isArray(config.functions["function"])) {
|
||||
(function (c1) {
|
||||
while (c1 < config.functions.function.length) {
|
||||
if ($.isPlainObject(config.functions.function[c1])) {
|
||||
processFuncObj(config.functions.function[c1]);
|
||||
while (c1 < config.functions["function"].length) {
|
||||
if ($.isPlainObject(config.functions["function"][c1])) {
|
||||
processFuncObj(config.functions["function"][c1]);
|
||||
}
|
||||
|
||||
c1 += 1;
|
||||
|
||||
@@ -838,33 +838,33 @@ define('Graph', ['logme'], function (logme) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof config.functions.function === 'string') {
|
||||
if (typeof config.functions["function"] === 'string') {
|
||||
|
||||
// If just one function string is present.
|
||||
addFunction(config.functions.function);
|
||||
addFunction(config.functions["function"]);
|
||||
|
||||
} else if ($.isPlainObject(config.functions.function) === true) {
|
||||
} else if ($.isPlainObject(config.functions["function"]) === true) {
|
||||
|
||||
// If a function is present, but it also has properties
|
||||
// defined.
|
||||
callAddFunction(config.functions.function);
|
||||
callAddFunction(config.functions["function"]);
|
||||
|
||||
} else if ($.isArray(config.functions.function)) {
|
||||
} else if ($.isArray(config.functions["function"])) {
|
||||
|
||||
// If more than one function is defined.
|
||||
for (c1 = 0; c1 < config.functions.function.length; c1 += 1) {
|
||||
for (c1 = 0; c1 < config.functions["function"].length; c1 += 1) {
|
||||
|
||||
// For each definition, we must check if it is a simple
|
||||
// string definition, or a complex one with properties.
|
||||
if (typeof config.functions.function[c1] === 'string') {
|
||||
if (typeof config.functions["function"][c1] === 'string') {
|
||||
|
||||
// Simple string.
|
||||
addFunction(config.functions.function[c1]);
|
||||
addFunction(config.functions["function"][c1]);
|
||||
|
||||
} else if ($.isPlainObject(config.functions.function[c1])) {
|
||||
} else if ($.isPlainObject(config.functions["function"][c1])) {
|
||||
|
||||
// Properties are present.
|
||||
callAddFunction(config.functions.function[c1]);
|
||||
callAddFunction(config.functions["function"][c1]);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,13 +20,17 @@ class @HTMLEditingDescriptor
|
||||
theme : "advanced",
|
||||
skin: 'studio',
|
||||
schema: "html5",
|
||||
# Necessary to preserve relative URLs to our images.
|
||||
convert_urls : false,
|
||||
# TODO: we should share this CSS with studio (and LMS)
|
||||
content_css : "/static/css/tiny-mce.css",
|
||||
# Disable h4, h5, and h6 styles as we don't have CSS for them.
|
||||
formats : {
|
||||
# Disable h4, h5, and h6 styles as we don't have CSS for them.
|
||||
h4: {},
|
||||
h5: {},
|
||||
h6: {}
|
||||
h6: {},
|
||||
# tinyMCE does block level for code by default
|
||||
code: {inline: 'code'}
|
||||
},
|
||||
# Disable visual aid on borderless table.
|
||||
visual:false,
|
||||
@@ -50,7 +54,7 @@ class @HTMLEditingDescriptor
|
||||
|
||||
@setupTinyMCE: (ed) ->
|
||||
ed.addButton('wrapAsCode', {
|
||||
title : 'Code Block',
|
||||
title : 'Code',
|
||||
image : '/static/images/ico-tinymce-code.png',
|
||||
onclick : () ->
|
||||
ed.formatter.toggle('code')
|
||||
|
||||
@@ -45,6 +45,7 @@ class @VideoPlayer extends Subview
|
||||
modestbranding: 1
|
||||
if @video.start
|
||||
@playerVars.start = @video.start
|
||||
@playerVars.wmode = 'window'
|
||||
if @video.end
|
||||
# work in AS3, not HMLT5. but iframe use AS3
|
||||
@playerVars.end = @video.end
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Circuit Schematic
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
data: |
|
||||
<problem >
|
||||
Please make a voltage divider that splits the provided voltage evenly.
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Custom Grader
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
data: |
|
||||
<problem>
|
||||
<p>
|
||||
|
||||
@@ -4,6 +4,8 @@ metadata:
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
markdown: ""
|
||||
weight: ""
|
||||
attempts: ""
|
||||
data: |
|
||||
<problem>
|
||||
</problem>
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Formula Response
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
data: |
|
||||
<problem>
|
||||
<p>
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Image Response
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
data: |
|
||||
<problem>
|
||||
<p>
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Multiple Choice
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
markdown:
|
||||
"A multiple choice problem presents radio buttons for student input. Students can only select a single
|
||||
option presented. Multiple Choice questions have been the subject of many areas of research due to the early
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Numerical Response
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
markdown:
|
||||
"A numerical response problem accepts a line of text input from the
|
||||
student, and evaluates the input for correctness based on its
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: Option Response
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
markdown:
|
||||
"OptionResponse gives a limited set of options for students to respond with, and presents those options
|
||||
in a format that encourages them to search for a specific answer rather than being immediately presented
|
||||
|
||||
@@ -3,6 +3,8 @@ metadata:
|
||||
display_name: String Response
|
||||
rerandomize: never
|
||||
showanswer: always
|
||||
weight: ""
|
||||
attempts: ""
|
||||
# Note, the extra newlines are needed to make the yaml parser add blank lines instead of folding
|
||||
markdown:
|
||||
"A string response problem accepts a line of text input from the
|
||||
|
||||
131
common/static/js/vendor/jquery-ui.min.js
vendored
131
common/static/js/vendor/jquery-ui.min.js
vendored
File diff suppressed because one or more lines are too long
956
common/static/js/vendor/jquery.ui.draggable.js
vendored
Normal file
956
common/static/js/vendor/jquery.ui.draggable.js
vendored
Normal file
@@ -0,0 +1,956 @@
|
||||
/*!
|
||||
* jQuery UI Draggable 1.10.0
|
||||
* http://jqueryui.com
|
||||
*
|
||||
* Copyright 2013 jQuery Foundation and other contributors
|
||||
* Released under the MIT license.
|
||||
* http://jquery.org/license
|
||||
*
|
||||
* http://api.jqueryui.com/draggable/
|
||||
*
|
||||
* Depends:
|
||||
* jquery.ui.core.js
|
||||
* jquery.ui.mouse.js
|
||||
* jquery.ui.widget.js
|
||||
*/
|
||||
(function( $, undefined ) {
|
||||
|
||||
$.widget("ui.draggable", $.ui.mouse, {
|
||||
version: "1.10.0",
|
||||
widgetEventPrefix: "drag",
|
||||
options: {
|
||||
addClasses: true,
|
||||
appendTo: "parent",
|
||||
axis: false,
|
||||
connectToSortable: false,
|
||||
containment: false,
|
||||
cursor: "auto",
|
||||
cursorAt: false,
|
||||
grid: false,
|
||||
handle: false,
|
||||
helper: "original",
|
||||
iframeFix: false,
|
||||
opacity: false,
|
||||
refreshPositions: false,
|
||||
revert: false,
|
||||
revertDuration: 500,
|
||||
scope: "default",
|
||||
scroll: true,
|
||||
scrollSensitivity: 20,
|
||||
scrollSpeed: 20,
|
||||
snap: false,
|
||||
snapMode: "both",
|
||||
snapTolerance: 20,
|
||||
stack: false,
|
||||
zIndex: false,
|
||||
|
||||
// callbacks
|
||||
drag: null,
|
||||
start: null,
|
||||
stop: null
|
||||
},
|
||||
_create: function() {
|
||||
|
||||
if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
|
||||
this.element[0].style.position = "relative";
|
||||
}
|
||||
if (this.options.addClasses){
|
||||
this.element.addClass("ui-draggable");
|
||||
}
|
||||
if (this.options.disabled){
|
||||
this.element.addClass("ui-draggable-disabled");
|
||||
}
|
||||
|
||||
this._mouseInit();
|
||||
|
||||
},
|
||||
|
||||
_destroy: function() {
|
||||
this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
|
||||
this._mouseDestroy();
|
||||
},
|
||||
|
||||
_mouseCapture: function(event) {
|
||||
|
||||
var o = this.options;
|
||||
|
||||
// among others, prevent a drag on a resizable-handle
|
||||
if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//Quit if we're not on a valid handle
|
||||
this.handle = this._getHandle(event);
|
||||
if (!this.handle) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
|
||||
$("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
|
||||
.css({
|
||||
width: this.offsetWidth+"px", height: this.offsetHeight+"px",
|
||||
position: "absolute", opacity: "0.001", zIndex: 1000
|
||||
})
|
||||
.css($(this).offset())
|
||||
.appendTo("body");
|
||||
});
|
||||
|
||||
return true;
|
||||
|
||||
},
|
||||
|
||||
_mouseStart: function(event) {
|
||||
|
||||
var o = this.options;
|
||||
|
||||
//Create and append the visible helper
|
||||
this.helper = this._createHelper(event);
|
||||
|
||||
this.helper.addClass("ui-draggable-dragging");
|
||||
|
||||
//Cache the helper size
|
||||
this._cacheHelperProportions();
|
||||
|
||||
//If ddmanager is used for droppables, set the global draggable
|
||||
if($.ui.ddmanager) {
|
||||
$.ui.ddmanager.current = this;
|
||||
}
|
||||
|
||||
/*
|
||||
* - Position generation -
|
||||
* This block generates everything position related - it's the core of draggables.
|
||||
*/
|
||||
|
||||
//Cache the margins of the original element
|
||||
this._cacheMargins();
|
||||
|
||||
//Store the helper's css position
|
||||
this.cssPosition = this.helper.css("position");
|
||||
this.scrollParent = this.helper.scrollParent();
|
||||
|
||||
//The element's absolute position on the page minus margins
|
||||
this.offset = this.positionAbs = this.element.offset();
|
||||
this.offset = {
|
||||
top: this.offset.top - this.margins.top,
|
||||
left: this.offset.left - this.margins.left
|
||||
};
|
||||
|
||||
$.extend(this.offset, {
|
||||
click: { //Where the click happened, relative to the element
|
||||
left: event.pageX - this.offset.left,
|
||||
top: event.pageY - this.offset.top
|
||||
},
|
||||
parent: this._getParentOffset(),
|
||||
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
|
||||
});
|
||||
|
||||
//Generate the original position
|
||||
this.originalPosition = this.position = this._generatePosition(event);
|
||||
this.originalPageX = event.pageX;
|
||||
this.originalPageY = event.pageY;
|
||||
|
||||
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
|
||||
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
|
||||
|
||||
//Set a containment if given in the options
|
||||
if(o.containment) {
|
||||
this._setContainment();
|
||||
}
|
||||
|
||||
//Trigger event + callbacks
|
||||
if(this._trigger("start", event) === false) {
|
||||
this._clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
//Recache the helper size
|
||||
this._cacheHelperProportions();
|
||||
|
||||
//Prepare the droppable offsets
|
||||
if ($.ui.ddmanager && !o.dropBehaviour) {
|
||||
$.ui.ddmanager.prepareOffsets(this, event);
|
||||
}
|
||||
|
||||
|
||||
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
|
||||
|
||||
//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
|
||||
if ( $.ui.ddmanager ) {
|
||||
$.ui.ddmanager.dragStart(this, event);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
_mouseDrag: function(event, noPropagation) {
|
||||
|
||||
//Compute the helpers position
|
||||
this.position = this._generatePosition(event);
|
||||
this.positionAbs = this._convertPositionTo("absolute");
|
||||
|
||||
//Call plugins and callbacks and use the resulting position if something is returned
|
||||
if (!noPropagation) {
|
||||
var ui = this._uiHash();
|
||||
if(this._trigger("drag", event, ui) === false) {
|
||||
this._mouseUp({});
|
||||
return false;
|
||||
}
|
||||
this.position = ui.position;
|
||||
}
|
||||
|
||||
if(!this.options.axis || this.options.axis !== "y") {
|
||||
this.helper[0].style.left = this.position.left+"px";
|
||||
}
|
||||
if(!this.options.axis || this.options.axis !== "x") {
|
||||
// BUG: either due to race condition of scrollTop() changing after pageY set or
|
||||
// a bug in the computation of pageY, they're changing at different rates during
|
||||
// scroll. This causes position to change faster than the mouse which races the helper
|
||||
// ahead. This "fixes" that bug here whereas the real fix should be in either the
|
||||
// computation of pageY or scrollTop() or caching of scrollTop at same state as pageY
|
||||
// btw: known bug in jqueryui http://bugs.jqueryui.com/ticket/5718
|
||||
if (this.scrollParent.is(document) && this.cssPosition === 'relative') {
|
||||
this.helper[0].style.top = (event.pageY - this.originalPageY) +"px";
|
||||
}
|
||||
else this.helper[0].style.top = this.position.top+"px";
|
||||
}
|
||||
if($.ui.ddmanager) {
|
||||
$.ui.ddmanager.drag(this, event);
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
_mouseStop: function(event) {
|
||||
|
||||
//If we are using droppables, inform the manager about the drop
|
||||
var element,
|
||||
that = this,
|
||||
elementInDom = false,
|
||||
dropped = false;
|
||||
if ($.ui.ddmanager && !this.options.dropBehaviour) {
|
||||
dropped = $.ui.ddmanager.drop(this, event);
|
||||
}
|
||||
|
||||
//if a drop comes from outside (a sortable)
|
||||
if(this.dropped) {
|
||||
dropped = this.dropped;
|
||||
this.dropped = false;
|
||||
}
|
||||
|
||||
//if the original element is no longer in the DOM don't bother to continue (see #8269)
|
||||
element = this.element[0];
|
||||
while ( element && (element = element.parentNode) ) {
|
||||
if (element === document ) {
|
||||
elementInDom = true;
|
||||
}
|
||||
}
|
||||
if ( !elementInDom && this.options.helper === "original" ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
|
||||
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
|
||||
if(that._trigger("stop", event) !== false) {
|
||||
that._clear();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if(this._trigger("stop", event) !== false) {
|
||||
this._clear();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
_mouseUp: function(event) {
|
||||
//Remove frame helpers
|
||||
$("div.ui-draggable-iframeFix").each(function() {
|
||||
this.parentNode.removeChild(this);
|
||||
});
|
||||
|
||||
//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
|
||||
if( $.ui.ddmanager ) {
|
||||
$.ui.ddmanager.dragStop(this, event);
|
||||
}
|
||||
|
||||
return $.ui.mouse.prototype._mouseUp.call(this, event);
|
||||
},
|
||||
|
||||
cancel: function() {
|
||||
|
||||
if(this.helper.is(".ui-draggable-dragging")) {
|
||||
this._mouseUp({});
|
||||
} else {
|
||||
this._clear();
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
_getHandle: function(event) {
|
||||
|
||||
var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
|
||||
$(this.options.handle, this.element)
|
||||
.find("*")
|
||||
.addBack()
|
||||
.each(function() {
|
||||
if(this === event.target) {
|
||||
handle = true;
|
||||
}
|
||||
});
|
||||
|
||||
return handle;
|
||||
|
||||
},
|
||||
|
||||
_createHelper: function(event) {
|
||||
|
||||
var o = this.options,
|
||||
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
|
||||
|
||||
if(!helper.parents("body").length) {
|
||||
helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
|
||||
}
|
||||
|
||||
if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
|
||||
helper.css("position", "absolute");
|
||||
}
|
||||
|
||||
return helper;
|
||||
|
||||
},
|
||||
|
||||
_adjustOffsetFromHelper: function(obj) {
|
||||
if (typeof obj === "string") {
|
||||
obj = obj.split(" ");
|
||||
}
|
||||
if ($.isArray(obj)) {
|
||||
obj = {left: +obj[0], top: +obj[1] || 0};
|
||||
}
|
||||
if ("left" in obj) {
|
||||
this.offset.click.left = obj.left + this.margins.left;
|
||||
}
|
||||
if ("right" in obj) {
|
||||
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
|
||||
}
|
||||
if ("top" in obj) {
|
||||
this.offset.click.top = obj.top + this.margins.top;
|
||||
}
|
||||
if ("bottom" in obj) {
|
||||
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
|
||||
}
|
||||
},
|
||||
|
||||
_getParentOffset: function() {
|
||||
|
||||
//Get the offsetParent and cache its position
|
||||
this.offsetParent = this.helper.offsetParent();
|
||||
var po = this.offsetParent.offset();
|
||||
|
||||
// This is a special case where we need to modify a offset calculated on start, since the following happened:
|
||||
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
|
||||
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
|
||||
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
|
||||
if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
|
||||
po.left += this.scrollParent.scrollLeft();
|
||||
po.top += this.scrollParent.scrollTop();
|
||||
}
|
||||
|
||||
//This needs to be actually done for all browsers, since pageX/pageY includes this information
|
||||
//Ugly IE fix
|
||||
if((this.offsetParent[0] === document.body) ||
|
||||
(this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
|
||||
po = { top: 0, left: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
|
||||
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
_getRelativeOffset: function() {
|
||||
|
||||
if(this.cssPosition === "relative") {
|
||||
var p = this.element.position();
|
||||
return {
|
||||
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
|
||||
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
|
||||
};
|
||||
} else {
|
||||
return { top: 0, left: 0 };
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
_cacheMargins: function() {
|
||||
this.margins = {
|
||||
left: (parseInt(this.element.css("marginLeft"),10) || 0),
|
||||
top: (parseInt(this.element.css("marginTop"),10) || 0),
|
||||
right: (parseInt(this.element.css("marginRight"),10) || 0),
|
||||
bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
|
||||
};
|
||||
},
|
||||
|
||||
_cacheHelperProportions: function() {
|
||||
this.helperProportions = {
|
||||
width: this.helper.outerWidth(),
|
||||
height: this.helper.outerHeight()
|
||||
};
|
||||
},
|
||||
|
||||
_setContainment: function() {
|
||||
|
||||
var over, c, ce,
|
||||
o = this.options;
|
||||
|
||||
if(o.containment === "parent") {
|
||||
o.containment = this.helper[0].parentNode;
|
||||
}
|
||||
if(o.containment === "document" || o.containment === "window") {
|
||||
this.containment = [
|
||||
o.containment === "document" ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
|
||||
o.containment === "document" ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
|
||||
(o.containment === "document" ? 0 : $(window).scrollLeft()) + $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
|
||||
(o.containment === "document" ? 0 : $(window).scrollTop()) + ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
|
||||
];
|
||||
}
|
||||
|
||||
if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor !== Array) {
|
||||
c = $(o.containment);
|
||||
ce = c[0];
|
||||
|
||||
if(!ce) {
|
||||
return;
|
||||
}
|
||||
|
||||
over = ($(ce).css("overflow") !== "hidden");
|
||||
|
||||
this.containment = [
|
||||
(parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
|
||||
(parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0),
|
||||
(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
|
||||
(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom
|
||||
];
|
||||
this.relative_container = c;
|
||||
|
||||
} else if(o.containment.constructor === Array) {
|
||||
this.containment = o.containment;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
_convertPositionTo: function(d, pos) {
|
||||
|
||||
if(!pos) {
|
||||
pos = this.position;
|
||||
}
|
||||
|
||||
var mod = d === "absolute" ? 1 : -1,
|
||||
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
|
||||
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
|
||||
|
||||
return {
|
||||
top: (
|
||||
pos.top + // The absolute mouse position
|
||||
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
|
||||
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
|
||||
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
|
||||
),
|
||||
left: (
|
||||
pos.left + // The absolute mouse position
|
||||
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
|
||||
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
|
||||
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
|
||||
)
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
_generatePosition: function(event) {
|
||||
|
||||
var containment, co, top, left,
|
||||
o = this.options,
|
||||
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
|
||||
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName),
|
||||
pageX = event.pageX,
|
||||
pageY = event.pageY;
|
||||
|
||||
/*
|
||||
* - Position constraining -
|
||||
* Constrain the position to a mix of grid, containment.
|
||||
*/
|
||||
|
||||
if(this.originalPosition) { //If we are not dragging yet, we won't check for options
|
||||
if(this.containment) {
|
||||
if (this.relative_container){
|
||||
co = this.relative_container.offset();
|
||||
containment = [ this.containment[0] + co.left,
|
||||
this.containment[1] + co.top,
|
||||
this.containment[2] + co.left,
|
||||
this.containment[3] + co.top ];
|
||||
}
|
||||
else {
|
||||
containment = this.containment;
|
||||
}
|
||||
|
||||
if(event.pageX - this.offset.click.left < containment[0]) {
|
||||
pageX = containment[0] + this.offset.click.left;
|
||||
}
|
||||
if(event.pageY - this.offset.click.top < containment[1]) {
|
||||
pageY = containment[1] + this.offset.click.top;
|
||||
}
|
||||
if(event.pageX - this.offset.click.left > containment[2]) {
|
||||
pageX = containment[2] + this.offset.click.left;
|
||||
}
|
||||
if(event.pageY - this.offset.click.top > containment[3]) {
|
||||
pageY = containment[3] + this.offset.click.top;
|
||||
}
|
||||
}
|
||||
|
||||
if(o.grid) {
|
||||
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
|
||||
top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
|
||||
pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
|
||||
|
||||
left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
|
||||
pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return {
|
||||
top: (
|
||||
pageY - // The absolute mouse position
|
||||
this.offset.click.top - // Click offset (relative to the element)
|
||||
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
|
||||
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
|
||||
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
|
||||
),
|
||||
left: (
|
||||
pageX - // The absolute mouse position
|
||||
this.offset.click.left - // Click offset (relative to the element)
|
||||
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
|
||||
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
|
||||
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
|
||||
)
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
_clear: function() {
|
||||
this.helper.removeClass("ui-draggable-dragging");
|
||||
if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
|
||||
this.helper.remove();
|
||||
}
|
||||
this.helper = null;
|
||||
this.cancelHelperRemoval = false;
|
||||
},
|
||||
|
||||
// From now on bulk stuff - mainly helpers
|
||||
|
||||
_trigger: function(type, event, ui) {
|
||||
ui = ui || this._uiHash();
|
||||
$.ui.plugin.call(this, type, [event, ui]);
|
||||
//The absolute position has to be recalculated after plugins
|
||||
if(type === "drag") {
|
||||
this.positionAbs = this._convertPositionTo("absolute");
|
||||
}
|
||||
return $.Widget.prototype._trigger.call(this, type, event, ui);
|
||||
},
|
||||
|
||||
plugins: {},
|
||||
|
||||
_uiHash: function() {
|
||||
return {
|
||||
helper: this.helper,
|
||||
position: this.position,
|
||||
originalPosition: this.originalPosition,
|
||||
offset: this.positionAbs
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "connectToSortable", {
|
||||
start: function(event, ui) {
|
||||
|
||||
var inst = $(this).data("ui-draggable"), o = inst.options,
|
||||
uiSortable = $.extend({}, ui, { item: inst.element });
|
||||
inst.sortables = [];
|
||||
$(o.connectToSortable).each(function() {
|
||||
var sortable = $.data(this, "ui-sortable");
|
||||
if (sortable && !sortable.options.disabled) {
|
||||
inst.sortables.push({
|
||||
instance: sortable,
|
||||
shouldRevert: sortable.options.revert
|
||||
});
|
||||
sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
|
||||
sortable._trigger("activate", event, uiSortable);
|
||||
}
|
||||
});
|
||||
|
||||
},
|
||||
stop: function(event, ui) {
|
||||
|
||||
//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
|
||||
var inst = $(this).data("ui-draggable"),
|
||||
uiSortable = $.extend({}, ui, { item: inst.element });
|
||||
|
||||
$.each(inst.sortables, function() {
|
||||
if(this.instance.isOver) {
|
||||
|
||||
this.instance.isOver = 0;
|
||||
|
||||
inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
|
||||
this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
|
||||
|
||||
//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
|
||||
if(this.shouldRevert) {
|
||||
this.instance.options.revert = true;
|
||||
}
|
||||
|
||||
//Trigger the stop of the sortable
|
||||
this.instance._mouseStop(event);
|
||||
|
||||
this.instance.options.helper = this.instance.options._helper;
|
||||
|
||||
//If the helper has been the original item, restore properties in the sortable
|
||||
if(inst.options.helper === "original") {
|
||||
this.instance.currentItem.css({ top: "auto", left: "auto" });
|
||||
}
|
||||
|
||||
} else {
|
||||
this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
|
||||
this.instance._trigger("deactivate", event, uiSortable);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
},
|
||||
drag: function(event, ui) {
|
||||
|
||||
var inst = $(this).data("ui-draggable"), that = this;
|
||||
|
||||
$.each(inst.sortables, function() {
|
||||
|
||||
var innermostIntersecting = false,
|
||||
thisSortable = this;
|
||||
|
||||
//Copy over some variables to allow calling the sortable's native _intersectsWith
|
||||
this.instance.positionAbs = inst.positionAbs;
|
||||
this.instance.helperProportions = inst.helperProportions;
|
||||
this.instance.offset.click = inst.offset.click;
|
||||
|
||||
if(this.instance._intersectsWith(this.instance.containerCache)) {
|
||||
innermostIntersecting = true;
|
||||
$.each(inst.sortables, function () {
|
||||
this.instance.positionAbs = inst.positionAbs;
|
||||
this.instance.helperProportions = inst.helperProportions;
|
||||
this.instance.offset.click = inst.offset.click;
|
||||
if (this !== thisSortable &&
|
||||
this.instance._intersectsWith(this.instance.containerCache) &&
|
||||
$.ui.contains(thisSortable.instance.element[0], this.instance.element[0])
|
||||
) {
|
||||
innermostIntersecting = false;
|
||||
}
|
||||
return innermostIntersecting;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if(innermostIntersecting) {
|
||||
//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
|
||||
if(!this.instance.isOver) {
|
||||
|
||||
this.instance.isOver = 1;
|
||||
//Now we fake the start of dragging for the sortable instance,
|
||||
//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
|
||||
//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
|
||||
this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
|
||||
this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
|
||||
this.instance.options.helper = function() { return ui.helper[0]; };
|
||||
|
||||
event.target = this.instance.currentItem[0];
|
||||
this.instance._mouseCapture(event, true);
|
||||
this.instance._mouseStart(event, true, true);
|
||||
|
||||
//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
|
||||
this.instance.offset.click.top = inst.offset.click.top;
|
||||
this.instance.offset.click.left = inst.offset.click.left;
|
||||
this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
|
||||
this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
|
||||
|
||||
inst._trigger("toSortable", event);
|
||||
inst.dropped = this.instance.element; //draggable revert needs that
|
||||
//hack so receive/update callbacks work (mostly)
|
||||
inst.currentItem = inst.element;
|
||||
this.instance.fromOutside = inst;
|
||||
|
||||
}
|
||||
|
||||
//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
|
||||
if(this.instance.currentItem) {
|
||||
this.instance._mouseDrag(event);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
//If it doesn't intersect with the sortable, and it intersected before,
|
||||
//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
|
||||
if(this.instance.isOver) {
|
||||
|
||||
this.instance.isOver = 0;
|
||||
this.instance.cancelHelperRemoval = true;
|
||||
|
||||
//Prevent reverting on this forced stop
|
||||
this.instance.options.revert = false;
|
||||
|
||||
// The out event needs to be triggered independently
|
||||
this.instance._trigger("out", event, this.instance._uiHash(this.instance));
|
||||
|
||||
this.instance._mouseStop(event, true);
|
||||
this.instance.options.helper = this.instance.options._helper;
|
||||
|
||||
//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
|
||||
this.instance.currentItem.remove();
|
||||
if(this.instance.placeholder) {
|
||||
this.instance.placeholder.remove();
|
||||
}
|
||||
|
||||
inst._trigger("fromSortable", event);
|
||||
inst.dropped = false; //draggable revert needs that
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "cursor", {
|
||||
start: function() {
|
||||
var t = $("body"), o = $(this).data("ui-draggable").options;
|
||||
if (t.css("cursor")) {
|
||||
o._cursor = t.css("cursor");
|
||||
}
|
||||
t.css("cursor", o.cursor);
|
||||
},
|
||||
stop: function() {
|
||||
var o = $(this).data("ui-draggable").options;
|
||||
if (o._cursor) {
|
||||
$("body").css("cursor", o._cursor);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "opacity", {
|
||||
start: function(event, ui) {
|
||||
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
|
||||
if(t.css("opacity")) {
|
||||
o._opacity = t.css("opacity");
|
||||
}
|
||||
t.css("opacity", o.opacity);
|
||||
},
|
||||
stop: function(event, ui) {
|
||||
var o = $(this).data("ui-draggable").options;
|
||||
if(o._opacity) {
|
||||
$(ui.helper).css("opacity", o._opacity);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "scroll", {
|
||||
start: function() {
|
||||
var i = $(this).data("ui-draggable");
|
||||
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
|
||||
i.overflowOffset = i.scrollParent.offset();
|
||||
}
|
||||
},
|
||||
drag: function( event ) {
|
||||
|
||||
var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
|
||||
|
||||
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
|
||||
|
||||
if(!o.axis || o.axis !== "x") {
|
||||
if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
|
||||
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
|
||||
} else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
|
||||
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
|
||||
}
|
||||
}
|
||||
|
||||
if(!o.axis || o.axis !== "y") {
|
||||
if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
|
||||
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
|
||||
} else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
|
||||
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
if(!o.axis || o.axis !== "x") {
|
||||
if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
|
||||
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
|
||||
} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
|
||||
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
if(!o.axis || o.axis !== "y") {
|
||||
if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
|
||||
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
|
||||
} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
|
||||
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
|
||||
$.ui.ddmanager.prepareOffsets(i, event);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "snap", {
|
||||
start: function() {
|
||||
|
||||
var i = $(this).data("ui-draggable"),
|
||||
o = i.options;
|
||||
|
||||
i.snapElements = [];
|
||||
|
||||
$(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
|
||||
var $t = $(this),
|
||||
$o = $t.offset();
|
||||
if(this !== i.element[0]) {
|
||||
i.snapElements.push({
|
||||
item: this,
|
||||
width: $t.outerWidth(), height: $t.outerHeight(),
|
||||
top: $o.top, left: $o.left
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
},
|
||||
drag: function(event, ui) {
|
||||
|
||||
var ts, bs, ls, rs, l, r, t, b, i, first,
|
||||
inst = $(this).data("ui-draggable"),
|
||||
o = inst.options,
|
||||
d = o.snapTolerance,
|
||||
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
|
||||
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
|
||||
|
||||
for (i = inst.snapElements.length - 1; i >= 0; i--){
|
||||
|
||||
l = inst.snapElements[i].left;
|
||||
r = l + inst.snapElements[i].width;
|
||||
t = inst.snapElements[i].top;
|
||||
b = t + inst.snapElements[i].height;
|
||||
|
||||
//Yes, I know, this is insane ;)
|
||||
if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
|
||||
if(inst.snapElements[i].snapping) {
|
||||
(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
|
||||
}
|
||||
inst.snapElements[i].snapping = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(o.snapMode !== "inner") {
|
||||
ts = Math.abs(t - y2) <= d;
|
||||
bs = Math.abs(b - y1) <= d;
|
||||
ls = Math.abs(l - x2) <= d;
|
||||
rs = Math.abs(r - x1) <= d;
|
||||
if(ts) {
|
||||
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
|
||||
}
|
||||
if(bs) {
|
||||
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
|
||||
}
|
||||
if(ls) {
|
||||
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
|
||||
}
|
||||
if(rs) {
|
||||
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
|
||||
}
|
||||
}
|
||||
|
||||
first = (ts || bs || ls || rs);
|
||||
|
||||
if(o.snapMode !== "outer") {
|
||||
ts = Math.abs(t - y1) <= d;
|
||||
bs = Math.abs(b - y2) <= d;
|
||||
ls = Math.abs(l - x1) <= d;
|
||||
rs = Math.abs(r - x2) <= d;
|
||||
if(ts) {
|
||||
ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
|
||||
}
|
||||
if(bs) {
|
||||
ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
|
||||
}
|
||||
if(ls) {
|
||||
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
|
||||
}
|
||||
if(rs) {
|
||||
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
|
||||
}
|
||||
}
|
||||
|
||||
if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
|
||||
(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
|
||||
}
|
||||
inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "stack", {
|
||||
start: function() {
|
||||
|
||||
var min,
|
||||
o = $(this).data("ui-draggable").options,
|
||||
group = $.makeArray($(o.stack)).sort(function(a,b) {
|
||||
return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
|
||||
});
|
||||
|
||||
if (!group.length) { return; }
|
||||
|
||||
min = parseInt(group[0].style.zIndex, 10) || 0;
|
||||
$(group).each(function(i) {
|
||||
this.style.zIndex = min + i;
|
||||
});
|
||||
|
||||
this[0].style.zIndex = min + group.length;
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
$.ui.plugin.add("draggable", "zIndex", {
|
||||
start: function(event, ui) {
|
||||
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
|
||||
if(t.css("zIndex")) {
|
||||
o._zIndex = t.css("zIndex");
|
||||
}
|
||||
t.css("zIndex", o.zIndex);
|
||||
},
|
||||
stop: function(event, ui) {
|
||||
var o = $(this).data("ui-draggable").options;
|
||||
if(o._zIndex) {
|
||||
$(ui.helper).css("zIndex", o._zIndex);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
})(jQuery);
|
||||
@@ -3,6 +3,7 @@
|
||||
<script type="text/javascript" src="${static.url('js/vendor/RequireJS.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/jquery.min.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/jquery-ui.min.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/jquery.ui.draggable.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/swfobject/swfobject.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/jquery.cookie.js')}"></script>
|
||||
<script type="text/javascript" src="${static.url('js/vendor/jquery.qtip.min.js')}"></script>
|
||||
|
||||
@@ -3,3 +3,4 @@
|
||||
-e git://github.com/MITx/django-pipeline.git#egg=django-pipeline
|
||||
-e git://github.com/MITx/django-wiki.git@e2e84558#egg=django-wiki
|
||||
-e git://github.com/dementrock/pystache_custom.git@776973740bdaad83a3b029f96e415a7d1e8bec2f#egg=pystache_custom-dev
|
||||
-e git://github.com/MITx/dogapi.git@003a4fc9#egg=dogapi
|
||||
|
||||
@@ -236,7 +236,7 @@ def index(request, course_id, chapter=None, section=None,
|
||||
# Load all descendents of the section, because we're going to display it's
|
||||
# html, which in general will need all of its children
|
||||
section_module = get_module(request.user, request, section_descriptor.location,
|
||||
student_module_cache, course.id, depth=None)
|
||||
student_module_cache, course.id, position=position, depth=None)
|
||||
if section_module is None:
|
||||
# User may be trying to be clever and access something
|
||||
# they don't have access to.
|
||||
|
||||
@@ -62,14 +62,3 @@ class Permission(models.Model):
|
||||
|
||||
def __unicode__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
@receiver(post_save, sender=CourseEnrollment)
|
||||
def assign_default_role(sender, instance, **kwargs):
|
||||
if instance.user.is_staff:
|
||||
role = Role.objects.get_or_create(course_id=instance.course_id, name="Moderator")[0]
|
||||
else:
|
||||
role = Role.objects.get_or_create(course_id=instance.course_id, name="Student")[0]
|
||||
|
||||
logging.info("assign_default_role: adding %s as %s" % (instance.user, role))
|
||||
instance.user.roles.add(role)
|
||||
|
||||
@@ -88,3 +88,9 @@ PEER_GRADING_INTERFACE = AUTH_TOKENS.get('PEER_GRADING_INTERFACE', PEER_GRADING_
|
||||
|
||||
PEARSON_TEST_USER = "pearsontest"
|
||||
PEARSON_TEST_PASSWORD = AUTH_TOKENS.get("PEARSON_TEST_PASSWORD")
|
||||
|
||||
# Pearson hash for import/export
|
||||
PEARSON = AUTH_TOKENS.get("PEARSON")
|
||||
|
||||
# Datadog for events!
|
||||
DATADOG_API = AUTH_TOKENS.get("DATADOG_API")
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
|
||||
<section class="bottom">
|
||||
<section class="copyright">
|
||||
## <p>© 2012 edX, <a href="${reverse('copyright')}">some rights reserved.</a></p> # TODO: (bridger) Update the copyright for edX, then re-enable the link.
|
||||
<p>© 2012 edX, some rights reserved.</p>
|
||||
## <p>© 2013 edX, <a href="${reverse('copyright')}">some rights reserved.</a></p> # TODO: (bridger) Update the copyright for edX, then re-enable the link.
|
||||
<p>© 2013 edX, some rights reserved.</p>
|
||||
</section>
|
||||
|
||||
<section class="secondary">
|
||||
|
||||
@@ -466,7 +466,7 @@
|
||||
<span class="label">Last Eligible Appointment Date:</span> <span class="value">${exam_info.last_eligible_appointment_date_text}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="label">Registration End Date:</span> <span class="value">${exam_info.registration_end_date_text}</span>
|
||||
<span class="label">Registration Ends:</span> <span class="value">${exam_info.registration_end_date_text}</span>
|
||||
</li>
|
||||
</ul>
|
||||
% endif
|
||||
|
||||
@@ -58,4 +58,4 @@ factory_boy
|
||||
Shapely==1.2.16
|
||||
ipython==0.13.1
|
||||
xmltodict==0.4.1
|
||||
|
||||
paramiko==1.9.0
|
||||
|
||||
Reference in New Issue
Block a user