virtualcommons-svn Mailing List for Virtual Commons Experiment Software (Page 29)
Status: Beta
Brought to you by:
alllee
You can subscribe to this list here.
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
(21) |
Aug
(31) |
Sep
(6) |
Oct
(15) |
Nov
(2) |
Dec
(9) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2009 |
Jan
(4) |
Feb
(6) |
Mar
(12) |
Apr
(52) |
May
(14) |
Jun
(19) |
Jul
(81) |
Aug
(115) |
Sep
(36) |
Oct
(88) |
Nov
(46) |
Dec
(58) |
2010 |
Jan
(52) |
Feb
(55) |
Mar
(48) |
Apr
(15) |
May
(5) |
Jun
(38) |
Jul
(27) |
Aug
(24) |
Sep
(28) |
Oct
(1) |
Nov
(2) |
Dec
(29) |
2011 |
Jan
(87) |
Feb
(39) |
Mar
(63) |
Apr
(42) |
May
(26) |
Jun
(53) |
Jul
(23) |
Aug
(43) |
Sep
(37) |
Oct
(25) |
Nov
(4) |
Dec
(7) |
2012 |
Jan
(73) |
Feb
(79) |
Mar
(62) |
Apr
(28) |
May
(12) |
Jun
(2) |
Jul
(9) |
Aug
(1) |
Sep
(8) |
Oct
|
Nov
(3) |
Dec
(3) |
2013 |
Jan
(8) |
Feb
(16) |
Mar
(38) |
Apr
(74) |
May
(62) |
Jun
(15) |
Jul
(49) |
Aug
(19) |
Sep
(9) |
Oct
|
Nov
|
Dec
|
2014 |
Jan
|
Feb
|
Mar
|
Apr
(2) |
May
(25) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Bitbucket <com...@bi...> - 2011-08-09 18:34:22
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/0a1e00ae63ea/ changeset: 0a1e00ae63ea user: alllee date: 2011-08-09 20:03:28 summary: fixes to activity availability time logic when performing activities affected #: 3 files (1.1 KB) --- a/vcweb/lighterprints/models.py Tue Aug 09 08:52:23 2011 -0700 +++ b/vcweb/lighterprints/models.py Tue Aug 09 11:03:28 2011 -0700 @@ -82,32 +82,48 @@ def available_activities(activity=None): current_time = datetime.datetime.now().time() - filter_dict = dict(available_start_time__lte=current_time, - available_end_time__gte=current_time) + available_time_slot = dict(available_start_time__lte=current_time, available_end_time__gte=current_time) + available_all_day = dict(activity__available_all_day=True) if activity is not None: - filter_dict['activity'] = activity - logger.debug("filtering with filter dict %s", filter_dict) - return ActivityAvailability.objects.select_related(depth=1).filter(Q(**filter_dict) | Q(activity__available_all_day=True)) + available_time_slot['activity'] = activity + available_all_day['activity'] = activity + return ActivityAvailability.objects.select_related(depth=1).filter(Q(**available_time_slot) | Q(**available_all_day)) -def is_activity_available(activity=None, participant_group_relationship=None, **kwargs): - if activity is None: - logger.debug("cannot check availability for non activity") - return False +def is_activity_available(activity, participant_group_relationship, **kwargs): # how often can a participant participate in an activity? # whenever it falls within the ActivityAvailability schedule and if the participant # hasn't already performed this activity during this cycle. - now = datetime.datetime.today() - current_time = now.time() - availabilities = ActivityAvailability.objects.filter(Q(activity=activity, activity__available_all_day=True) | Q(available_start_time__lte=current_time, available_end_time__gte=current_time)) -# FIXME: check if this participant has already participated in this activity within this particular interval (for all -# day, today, for time slots, during this particular time slot). - already_performed = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), - participant_group_relationship=participant_group_relationship, - submitted=True, - date_created__lte=now) - return (availabilities.count() > 0) and (already_performed.count() == 0) + logger.debug("checking if %s is available for %s", activity, participant_group_relationship) + if activity.available_all_day: + # check if they've done it already today, check if the combine is necessary + today = datetime.datetime.combine(datetime.date.today(), datetime.time()) + already_performed = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), + participant_group_relationship=participant_group_relationship, + int_value=activity.id, + date_created__gt=today) + logger.debug("activity is available all day, was it already performed? %s", already_performed) + return already_performed.count() == 0 + else: + logger.debug("XXX: wasn't available all day") + now = datetime.datetime.now() + current_time = now.time() + # FIXME: check if this participant has already participated in this activity within this particular interval (for all + # day, today, for time slots, during this particular time slot). There should only be one availability + try: + logger.debug("checking availability set %s", activity.availability_set.all()) + availabilities = activity.availability_set.filter(available_start_time__lte=current_time, available_end_time__gte=current_time) + earliest_start_time = datetime.datetime.combine(datetime.date.today(), availabilities[0].available_start_time) + logger.debug("earliest start time: %s", earliest_start_time) + already_performed = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), + participant_group_relationship=participant_group_relationship, + int_value=activity.pk, + date_created__lte=now, + date_created__gte=earliest_start_time) + return already_performed.count() == 0 + except: + return False -def do_activity(activity=None, participant_group_relationship=None): +def do_activity(activity, participant_group_relationship): if is_activity_available(activity, participant_group_relationship): logger.debug("activity %s was available", activity) round_data = participant_group_relationship.group.current_round_data --- a/vcweb/lighterprints/tests.py Tue Aug 09 08:52:23 2011 -0700 +++ b/vcweb/lighterprints/tests.py Tue Aug 09 11:03:28 2011 -0700 @@ -64,12 +64,11 @@ self.assertEqual(response.status_code, 200) # try to do the same activity again logger.debug("XXX: all activity performed parameters: %s", ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter())) - response = self.client.post('/lighterprints/api/do-activity', { 'participant_group_relationship_id': participant_group_relationship.id, - 'activity_id': activity.id + 'activity_id': activity.pk }) - self.assertEqual(response.status_code, 500) + self.assertEqual(response.status_code, 400) --- a/vcweb/lighterprints/views.py Tue Aug 09 08:52:23 2011 -0700 +++ b/vcweb/lighterprints/views.py Tue Aug 09 11:03:28 2011 -0700 @@ -75,6 +75,7 @@ @csrf_exempt def perform_activity(request): + logger.debug("performing activity") form = ActivityForm(request.POST or None) if form.is_valid(): activity_id = form.cleaned_data['activity_id'] @@ -82,7 +83,6 @@ participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) activity = get_object_or_404(Activity, pk=activity_id) performed_activity = do_activity(activity=activity, participant_group_relationship=participant_group_relationship) - logger.debug("performed activity %s", performed_activity) if performed_activity is not None: return HttpResponse(dumps(performed_activity), content_type='text/javascript') return HttpResponseBadRequest("Could not perform activity") Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-09 15:52:37
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/72f1cf82fd14/ changeset: 72f1cf82fd14 user: alllee date: 2011-08-09 17:52:23 summary: fixing test and adding a double post test that's currently failing, need to fix is_activity_available logic to properly check when activities have already been performed by a participant within the current time interval. affected #: 4 files (678 bytes) --- a/vcweb/core/models.py Mon Aug 08 16:28:36 2011 -0700 +++ b/vcweb/core/models.py Tue Aug 09 08:52:23 2011 -0700 @@ -397,7 +397,7 @@ u = User.objects.create_user(username=email, email=email, password=password) users.append(u) for user in users: - logger.debug("registering user %s", user) + #logger.debug("registering user %s", user) (p, created) = Participant.objects.get_or_create(user=user) # FIXME: instead of asking for the email suffix, perhaps we just append the institution URL to keep it simpler? if institution and p.institution != institution: --- a/vcweb/lighterprints/models.py Mon Aug 08 16:28:36 2011 -0700 +++ b/vcweb/lighterprints/models.py Tue Aug 09 08:52:23 2011 -0700 @@ -73,6 +73,9 @@ def get_carbon_footprint_level_parameter(): return Parameter.objects.get(name='carbon_footprint_level') +def get_carbon_footprint_level(group): + return GroupRoundDataValue.objects.get(group=group, parameter=get_carbon_footprint_level_parameter()) + def get_active_experiments(): return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) @@ -93,25 +96,27 @@ # how often can a participant participate in an activity? # whenever it falls within the ActivityAvailability schedule and if the participant # hasn't already performed this activity during this cycle. - now = datetime.datetime.now() + now = datetime.datetime.today() current_time = now.time() availabilities = ActivityAvailability.objects.filter(Q(activity=activity, activity__available_all_day=True) | Q(available_start_time__lte=current_time, available_end_time__gte=current_time)) -# FIXME: check if this participant has already participated in this activity - data_value_set = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), +# FIXME: check if this participant has already participated in this activity within this particular interval (for all +# day, today, for time slots, during this particular time slot). + already_performed = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), participant_group_relationship=participant_group_relationship, submitted=True, - date_created__lte=now, - date_created__gte=now) - return availabilities.count() > 0 and data_value_set.count() == 0 + date_created__lte=now) + return (availabilities.count() > 0) and (already_performed.count() == 0) def do_activity(activity=None, participant_group_relationship=None): if is_activity_available(activity, participant_group_relationship): + logger.debug("activity %s was available", activity) round_data = participant_group_relationship.group.current_round_data return ParticipantRoundDataValue.objects.create(parameter=get_activity_performed_parameter(), participant_group_relationship=participant_group_relationship, round_data=round_data, # FIXME: use activity unique name instead? - value=activity.pk + value=activity.pk, + submitted=True ) @receiver(signals.midnight_tick) @@ -131,16 +136,15 @@ logger.debug("received invalid signal from sender %s", sender) return # FIXME: See if we can push this logic up to core.. - logger.debug("initializing lighter prints") current_round_data = experiment.current_round_data carbon_footprint_level_parameter = get_carbon_footprint_level_parameter() +# only create the carbon footprint level parameter, the participant activity performed data values will be created each +# time. for group in experiment.group_set.all(): carbon_footprint_level_grdv = current_round_data.group_data_value_set.create(group=group, parameter=carbon_footprint_level_parameter) carbon_footprint_level_grdv.value = 1 carbon_footprint_level_grdv.save() - - def get_daily_carbon_savings(group): # grab all of yesterday's participant data values today = datetime.date.today() @@ -153,10 +157,6 @@ logger.debug("total carbon savings: %s", total_savings) return total_savings -def get_carbon_footprint_level(group): - return GroupRoundDataValue.objects.get(group=group, parameter=get_carbon_footprint_level_parameter()) - - def should_advance_level(group, level): if level < 3: daily_carbon_savings = get_daily_carbon_savings(group) --- a/vcweb/lighterprints/tests.py Mon Aug 08 16:28:36 2011 -0700 +++ b/vcweb/lighterprints/tests.py Tue Aug 09 08:52:23 2011 -0700 @@ -33,16 +33,14 @@ activity_performed_parameter = create_activity_performed_parameter() # initialize participant carbon savings for participant_group_relationship in ParticipantGroupRelationship.objects.filter(group__experiment=e): - for activity in available_activities(): + for activity in Activity.objects.filter(level=1): activity_performed = participant_group_relationship.participant_data_value_set.create(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) activity_performed.value = activity.id activity_performed.save() - logger.debug("all activities performed: %s", - participant_group_relationship.participant_data_value_set.all()) update_active_experiments(self) for group in e.group_set.all(): self.assertEqual(get_carbon_footprint_level(group).value, 2) - self.assertEqual(get_daily_carbon_savings(group), Decimal('19.15')) + self.assertEqual(get_daily_carbon_savings(group), Decimal('58.20')) class DoActivityTest(BaseTest): @@ -64,5 +62,15 @@ }) logger.debug("response %s", response) self.assertEqual(response.status_code, 200) +# try to do the same activity again + logger.debug("XXX: all activity performed parameters: %s", ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter())) + + response = self.client.post('/lighterprints/api/do-activity', { + 'participant_group_relationship_id': participant_group_relationship.id, + 'activity_id': activity.id + }) + self.assertEqual(response.status_code, 500) + + --- a/vcweb/lighterprints/views.py Mon Aug 08 16:28:36 2011 -0700 +++ b/vcweb/lighterprints/views.py Tue Aug 09 08:52:23 2011 -0700 @@ -83,8 +83,9 @@ activity = get_object_or_404(Activity, pk=activity_id) performed_activity = do_activity(activity=activity, participant_group_relationship=participant_group_relationship) logger.debug("performed activity %s", performed_activity) - return HttpResponse(dumps(performed_activity), content_type='text/javascript') - return HttpResponseBadRequest("Invalid activity post") + if performed_activity is not None: + return HttpResponse(dumps(performed_activity), content_type='text/javascript') + return HttpResponseBadRequest("Could not perform activity") @csrf_exempt Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-08 23:28:45
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/22309ab99f29/ changeset: 22309ab99f29 user: alllee date: 2011-08-09 01:28:36 summary: setting up initial carbon footprint level properly affected #: 3 files (762 bytes) --- a/vcweb/core/models.py Mon Aug 08 13:40:08 2011 -0700 +++ b/vcweb/core/models.py Mon Aug 08 16:28:36 2011 -0700 @@ -437,10 +437,11 @@ for parameter in group_parameters: group_data_value, created = current_round_data.group_data_value_set.get_or_create(group=group, parameter=parameter) logger.debug("%s (%s)", group_data_value, created) - for pgr in group.participant_group_relationship_set.all(): - for parameter in participant_parameters: - participant_data_value, created = current_round_data.participant_data_value_set.get_or_create(participant_group_relationship=pgr, parameter=parameter) - logger.debug("%s (%s)", participant_data_value, created) + if participant_parameters: + for pgr in group.participant_group_relationship_set.all(): + for parameter in participant_parameters: + participant_data_value, created = current_round_data.participant_data_value_set.get_or_create(participant_group_relationship=pgr, parameter=parameter) + logger.debug("%s (%s)", participant_data_value, created) def log(self, log_message): if log_message: --- a/vcweb/lighterprints/models.py Mon Aug 08 13:40:08 2011 -0700 +++ b/vcweb/lighterprints/models.py Mon Aug 08 16:28:36 2011 -0700 @@ -1,5 +1,5 @@ from django.db import models -from django.db.models import Sum, Q +from django.db.models import Q from vcweb.core import signals, simplecache from vcweb.core.models import (Experiment, ExperimentMetadata, Experimenter, GroupRoundDataValue, ParticipantRoundDataValue, Parameter) @@ -119,11 +119,11 @@ for experiment in get_active_experiments(): # calculate total carbon savings and decide if they move on to the next level for group in experiment.group_set.all(): - grdv = GroupRoundDataValue.objects.get(group=group, parameter__name='carbon_footprint_level') - if should_advance_level(group, grdv.value): + carbon_footprint_level_grdv = get_carbon_footprint_level(group) + if should_advance_level(group, carbon_footprint_level_grdv.value): # advance group level - grdv.value = min(grdv.value + 1, 3) - grdv.save() + carbon_footprint_level_grdv.value = min(carbon_footprint_level_grdv.value + 1, 3) + carbon_footprint_level_grdv.save() @receiver(signals.round_started) def round_started_handler(sender, experiment=None, **kwargs): @@ -132,10 +132,14 @@ return # FIXME: See if we can push this logic up to core.. logger.debug("initializing lighter prints") - experiment.initialize_parameters( - group_parameters = [get_carbon_footprint_level_parameter()], - participant_parameters = [get_activity_performed_parameter()] - ) + current_round_data = experiment.current_round_data + carbon_footprint_level_parameter = get_carbon_footprint_level_parameter() + for group in experiment.group_set.all(): + carbon_footprint_level_grdv = current_round_data.group_data_value_set.create(group=group, parameter=carbon_footprint_level_parameter) + carbon_footprint_level_grdv.value = 1 + carbon_footprint_level_grdv.save() + + def get_daily_carbon_savings(group): # grab all of yesterday's participant data values @@ -143,17 +147,21 @@ yesterday = today - datetime.timedelta(1) total_savings = Decimal(0.0) for activity_performed_dv in group.get_participant_data_values(parameter_name='activity_performed').filter(date_created__gte=yesterday): - logger.debug("%s", activity_performed_dv) activity = Activity.objects.get(pk=activity_performed_dv.value) total_savings += activity.savings #total = participant_data_values.aggregate(total=Sum('int_value'))['total'] logger.debug("total carbon savings: %s", total_savings) return total_savings +def get_carbon_footprint_level(group): + return GroupRoundDataValue.objects.get(group=group, parameter=get_carbon_footprint_level_parameter()) + def should_advance_level(group, level): if level < 3: daily_carbon_savings = get_daily_carbon_savings(group) + logger.debug("daily carbon savings were %s, but were they greater than level * 10? %s", daily_carbon_savings, + level * 10) return daily_carbon_savings > level * 10 return False --- a/vcweb/lighterprints/tests.py Mon Aug 08 13:40:08 2011 -0700 +++ b/vcweb/lighterprints/tests.py Mon Aug 08 16:28:36 2011 -0700 @@ -33,13 +33,16 @@ activity_performed_parameter = create_activity_performed_parameter() # initialize participant carbon savings for participant_group_relationship in ParticipantGroupRelationship.objects.filter(group__experiment=e): - for activity in Activity.objects.all(): - activity_performed = participant_group_relationship.participant_data_value_set.get(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) + for activity in available_activities(): + activity_performed = participant_group_relationship.participant_data_value_set.create(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) activity_performed.value = activity.id activity_performed.save() logger.debug("all activities performed: %s", participant_group_relationship.participant_data_value_set.all()) update_active_experiments(self) + for group in e.group_set.all(): + self.assertEqual(get_carbon_footprint_level(group).value, 2) + self.assertEqual(get_daily_carbon_savings(group), Decimal('19.15')) class DoActivityTest(BaseTest): Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-08 20:40:20
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/2a9f5b4fcc30/ changeset: 2a9f5b4fcc30 user: alllee date: 2011-08-08 22:40:08 summary: adding test coverage + fixing issues with get_daily_carbon_savings, wiring up round_started handler for lighterprints to be signaled when the experiment begins. affected #: 4 files (1.7 KB) --- a/vcweb/forestry/models.py Mon Aug 08 11:48:58 2011 -0700 +++ b/vcweb/forestry/models.py Mon Aug 08 13:40:08 2011 -0700 @@ -111,7 +111,8 @@ # initialize group and participant data values experiment.initialize_parameters( group_parameters=(regrowth_parameter, group_harvest_parameter, resource_level_parameter), - participant_parameters=[harvest_decision_parameter]) + participant_parameters=[harvest_decision_parameter] + ) ''' during a practice or regular round, set up resource levels and participant harvest decision parameters --- a/vcweb/lighterprints/fixtures/initial_data.json Mon Aug 08 11:48:58 2011 -0700 +++ b/vcweb/lighterprints/fixtures/initial_data.json Mon Aug 08 13:40:08 2011 -0700 @@ -37,7 +37,7 @@ "date_created": "2011-07-07 15:13:03", "duration": 0, "experiment_configuration": 4, - "instructions": "Welcome to the sanitation experiment.", + "instructions": "Welcome to the Lighter Footprints experiment.", "last_modified": "2011-07-07 15:13:03", "round_type": "REGULAR", "sequence_number": 1 @@ -46,6 +46,30 @@ "pk": 44 }, { + "fields": { + "name":"activity_performed", + "experiment_metadata": [ "lighterprints" ], + "creator": 1, + "type": "int", + "date_created": "2011-01-01 15:13:03", + "scope": "participant" + }, + "model": "core.parameter", + "pk": 9 + }, + { + "fields": { + "name":"carbon_footprint_level", + "experiment_metadata": [ "lighterprints" ], + "creator": 1, + "type": "int", + "date_created": "2011-01-01 15:13:07", + "scope": "group" + }, + "model": "core.parameter", + "pk": 10 + }, + { "pk": 4, "model": "lighterprints.activity", "fields": { --- a/vcweb/lighterprints/models.py Mon Aug 08 11:48:58 2011 -0700 +++ b/vcweb/lighterprints/models.py Mon Aug 08 13:40:08 2011 -0700 @@ -4,6 +4,7 @@ from vcweb.core.models import (Experiment, ExperimentMetadata, Experimenter, GroupRoundDataValue, ParticipantRoundDataValue, Parameter) from django.dispatch import receiver +from decimal import Decimal import datetime import logging @@ -56,7 +57,6 @@ def get_lighterprints_experiment_metadata(): return ExperimentMetadata.objects.get(namespace='lighterprints') -@simplecache def create_activity_performed_parameter(experimenter=None): if experimenter is None: experimenter = Experimenter.objects.get(pk=1) @@ -69,6 +69,10 @@ def get_activity_performed_parameter(): return Parameter.objects.get(name='activity_performed') +@simplecache +def get_carbon_footprint_level_parameter(): + return Parameter.objects.get(name='carbon_footprint_level') + def get_active_experiments(): return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) @@ -114,21 +118,37 @@ def update_active_experiments(sender, time=None, **kwargs): for experiment in get_active_experiments(): # calculate total carbon savings and decide if they move on to the next level - for group in experiment.groups.all(): - grdv = GroupRoundDataValue.objects.get(group=group, name='carbon_footprint_level') + for group in experiment.group_set.all(): + grdv = GroupRoundDataValue.objects.get(group=group, parameter__name='carbon_footprint_level') if should_advance_level(group, grdv.value): # advance group level grdv.value = min(grdv.value + 1, 3) grdv.save() +@receiver(signals.round_started) +def round_started_handler(sender, experiment=None, **kwargs): + if sender != get_lighterprints_experiment_metadata().pk: + logger.debug("received invalid signal from sender %s", sender) + return + # FIXME: See if we can push this logic up to core.. + logger.debug("initializing lighter prints") + experiment.initialize_parameters( + group_parameters = [get_carbon_footprint_level_parameter()], + participant_parameters = [get_activity_performed_parameter()] + ) def get_daily_carbon_savings(group): # grab all of yesterday's participant data values today = datetime.date.today() yesterday = today - datetime.timedelta(1) - participant_data_values = group.get_participant_data_values().filter(date_created__gte=yesterday) - participant_data_values.aggregate(total=Sum('value')) - return participant_data_values['total'] + total_savings = Decimal(0.0) + for activity_performed_dv in group.get_participant_data_values(parameter_name='activity_performed').filter(date_created__gte=yesterday): + logger.debug("%s", activity_performed_dv) + activity = Activity.objects.get(pk=activity_performed_dv.value) + total_savings += activity.savings + #total = participant_data_values.aggregate(total=Sum('int_value'))['total'] + logger.debug("total carbon savings: %s", total_savings) + return total_savings def should_advance_level(group, level): --- a/vcweb/lighterprints/tests.py Mon Aug 08 11:48:58 2011 -0700 +++ b/vcweb/lighterprints/tests.py Mon Aug 08 13:40:08 2011 -0700 @@ -31,13 +31,16 @@ e.start_round() current_round_data = e.current_round_data activity_performed_parameter = create_activity_performed_parameter() - logger.debug("activity performed parameter: %s", activity_performed_parameter) # initialize participant carbon savings for participant_group_relationship in ParticipantGroupRelationship.objects.filter(group__experiment=e): for activity in Activity.objects.all(): - activity_performed = participant_group_relationship.participant_data_value_set.create(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) + activity_performed = participant_group_relationship.participant_data_value_set.get(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) activity_performed.value = activity.id activity_performed.save() + logger.debug("all activities performed: %s", + participant_group_relationship.participant_data_value_set.all()) + update_active_experiments(self) + class DoActivityTest(BaseTest): def test_view(self): Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-08 18:49:12
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/158b11d740fd/ changeset: 158b11d740fd user: alllee date: 2011-08-08 20:48:58 summary: starting to add tests and fixing some exposed issues with previous activity availability logic (wasn't including activities that are available all day, etc.) affected #: 4 files (1.8 KB) --- a/vcweb/lighterprints/models.py Sun Aug 07 18:14:28 2011 -0700 +++ b/vcweb/lighterprints/models.py Mon Aug 08 11:48:58 2011 -0700 @@ -1,5 +1,5 @@ from django.db import models -from django.db.models import Sum +from django.db.models import Sum, Q from vcweb.core import signals, simplecache from vcweb.core.models import (Experiment, ExperimentMetadata, Experimenter, GroupRoundDataValue, ParticipantRoundDataValue, Parameter) @@ -62,6 +62,7 @@ experimenter = Experimenter.objects.get(pk=1) parameter, created = Parameter.objects.get_or_create(name='activity_performed', scope=Parameter.PARTICIPANT_SCOPE, type='int', creator=experimenter, experiment_metadata=get_lighterprints_experiment_metadata()) + if created: logger.debug("created activity performed parameter %s", parameter) return parameter @simplecache @@ -72,6 +73,15 @@ return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) +def available_activities(activity=None): + current_time = datetime.datetime.now().time() + filter_dict = dict(available_start_time__lte=current_time, + available_end_time__gte=current_time) + if activity is not None: + filter_dict['activity'] = activity + logger.debug("filtering with filter dict %s", filter_dict) + return ActivityAvailability.objects.select_related(depth=1).filter(Q(**filter_dict) | Q(activity__available_all_day=True)) + def is_activity_available(activity=None, participant_group_relationship=None, **kwargs): if activity is None: logger.debug("cannot check availability for non activity") @@ -81,7 +91,7 @@ # hasn't already performed this activity during this cycle. now = datetime.datetime.now() current_time = now.time() - availabilities = ActivityAvailability.objects.filter(activity=activity, available_start_time__lte=current_time, available_end_time__gte=current_time) + availabilities = ActivityAvailability.objects.filter(Q(activity=activity, activity__available_all_day=True) | Q(available_start_time__lte=current_time, available_end_time__gte=current_time)) # FIXME: check if this participant has already participated in this activity data_value_set = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), participant_group_relationship=participant_group_relationship, --- a/vcweb/lighterprints/tests.py Sun Aug 07 18:14:28 2011 -0700 +++ b/vcweb/lighterprints/tests.py Mon Aug 08 11:48:58 2011 -0700 @@ -30,11 +30,33 @@ e.activate() e.start_round() current_round_data = e.current_round_data - parameter = create_activity_performed_parameter() + activity_performed_parameter = create_activity_performed_parameter() + logger.debug("activity performed parameter: %s", activity_performed_parameter) # initialize participant carbon savings for participant_group_relationship in ParticipantGroupRelationship.objects.filter(group__experiment=e): for activity in Activity.objects.all(): - activity_performed, created = participant_group_relationship.participant_data_value_set.get_or_create(round_data=current_round_data, parameter=parameter) - activity_performed.value = activity.pk - logger.debug("activity performed %s (%s)", activity_performed, created) + activity_performed = participant_group_relationship.participant_data_value_set.create(round_data=current_round_data, parameter=activity_performed_parameter, experiment=e) + activity_performed.value = activity.id + activity_performed.save() +class DoActivityTest(BaseTest): + def test_view(self): + logger.debug("testing do activity view") + e = self.experiment + create_activity_performed_parameter() + e.activate() + e.start_round() + for participant_group_relationship in ParticipantGroupRelationship.objects.filter(group__experiment=e): + logger.debug("all available activities: %s", available_activities()) + for activity_availability in available_activities(): + logger.debug("available activity: %s", activity_availability) + activity = activity_availability.activity + logger.debug("participant %s performing activity %s", participant_group_relationship.participant, activity) + response = self.client.post('/lighterprints/api/do-activity', { + 'participant_group_relationship_id': participant_group_relationship.id, + 'activity_id': activity.id + }) + logger.debug("response %s", response) + self.assertEqual(response.status_code, 200) + + --- a/vcweb/lighterprints/urls.py Sun Aug 07 18:14:28 2011 -0700 +++ b/vcweb/lighterprints/urls.py Mon Aug 08 11:48:58 2011 -0700 @@ -1,15 +1,15 @@ from django.conf.urls.defaults import url, patterns from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, MobileView, - post_chat_message, do_activity, DiscussionBoardView) + post_chat_message, perform_activity, DiscussionBoardView) urlpatterns = patterns('vcweb.lighterprints.views', url(r'^mobile$', MobileView.as_view(), name='mobile'), url(r'^(?P<experiment_id>\d+)/configure$', 'configure', name='configure'), url(r'^activity/list/?$', ActivityListView.as_view()), url(r'^activity/(?P<activity_id>\d+)$', ActivityDetailView.as_view()), - url(r'^activity/(?P<activity_id>\d+)/do$', do_activity), url(r'^discussion/(?P<experiment_id>\d+)/(?P<participant_id>\d+)', DiscussionBoardView.as_view()), url(r'^discussion/(?P<experiment_id>\d+)/', DiscussionBoardView.as_view()), - url(r'^discussion/(?P<experiment_id>\d+)/post', post_chat_message), + url(r'^api/do-activity$', perform_activity), + url(r'^api/post-chat', post_chat_message), ) --- a/vcweb/lighterprints/views.py Sun Aug 07 18:14:28 2011 -0700 +++ b/vcweb/lighterprints/views.py Mon Aug 08 11:48:58 2011 -0700 @@ -74,7 +74,7 @@ pass @csrf_exempt -def perform_activity_view(request, activity_id): +def perform_activity(request): form = ActivityForm(request.POST or None) if form.is_valid(): activity_id = form.cleaned_data['activity_id'] Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-08 01:14:39
|
2 new changesets in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/d67839ef489a/ changeset: d67839ef489a user: alllee date: 2011-08-08 03:06:43 summary: adding activity availability check affected #: 1 file (962 bytes) --- a/vcweb/lighterprints/models.py Fri Aug 05 15:20:41 2011 -0700 +++ b/vcweb/lighterprints/models.py Sun Aug 07 18:06:43 2011 -0700 @@ -1,10 +1,14 @@ from django.db import models from django.db.models import Sum from vcweb.core import signals, simplecache -from vcweb.core.models import Experiment, ExperimentMetadata, Experimenter, GroupRoundDataValue, Parameter +from vcweb.core.models import (Experiment, ExperimentMetadata, Experimenter, + GroupRoundDataValue, ParticipantRoundDataValue, Parameter) from django.dispatch import receiver import datetime +import logging +logger = logging.getLogger(__name__) + class Activity(models.Model): name = models.CharField(max_length=32, unique=True) display_name = models.CharField(max_length=64, null=True, blank=True) @@ -68,8 +72,22 @@ return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) -def is_activity_available(participant=None, experiment=None, activity=None, **kwargs): - return True +def is_activity_available(participant_group_relationship=None, activity=None, **kwargs): + if activity is None: + logger.debug("cannot check availability for non activity") + return False +# how often can a participant participate in an activity? For the time being, just +# whenever its schedule is available and + now = datetime.datetime.now() + current_time = now.time() + availabilities = ActivityAvailability.objects.filter(activity=activity, available_start_time__lte=current_time, available_end_time__gte=current_time) +# FIXME: check if this participant has already participated in this activity + data_value_set = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), + participant_group_relationship=participant_group_relationship, + submitted=True, + date_created__lte=now, + date_created__gte=now) + return availabilities.count() > 0 and data_value_set.count() == 0 @receiver(signals.midnight_tick) def update_active_experiments(sender, time=None, **kwargs): http://bitbucket.org/virtualcommons/vcweb/changeset/3223f6bd7cb5/ changeset: 3223f6bd7cb5 user: alllee date: 2011-08-08 03:14:28 summary: logic for performing activity affected #: 2 files (858 bytes) --- a/vcweb/lighterprints/models.py Sun Aug 07 18:06:43 2011 -0700 +++ b/vcweb/lighterprints/models.py Sun Aug 07 18:14:28 2011 -0700 @@ -72,23 +72,34 @@ return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) -def is_activity_available(participant_group_relationship=None, activity=None, **kwargs): +def is_activity_available(activity=None, participant_group_relationship=None, **kwargs): if activity is None: logger.debug("cannot check availability for non activity") return False -# how often can a participant participate in an activity? For the time being, just -# whenever its schedule is available and +# how often can a participant participate in an activity? +# whenever it falls within the ActivityAvailability schedule and if the participant +# hasn't already performed this activity during this cycle. now = datetime.datetime.now() current_time = now.time() availabilities = ActivityAvailability.objects.filter(activity=activity, available_start_time__lte=current_time, available_end_time__gte=current_time) # FIXME: check if this participant has already participated in this activity - data_value_set = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), + data_value_set = ParticipantRoundDataValue.objects.filter(parameter=get_activity_performed_parameter(), participant_group_relationship=participant_group_relationship, submitted=True, date_created__lte=now, date_created__gte=now) return availabilities.count() > 0 and data_value_set.count() == 0 +def do_activity(activity=None, participant_group_relationship=None): + if is_activity_available(activity, participant_group_relationship): + round_data = participant_group_relationship.group.current_round_data + return ParticipantRoundDataValue.objects.create(parameter=get_activity_performed_parameter(), + participant_group_relationship=participant_group_relationship, + round_data=round_data, + # FIXME: use activity unique name instead? + value=activity.pk + ) + @receiver(signals.midnight_tick) def update_active_experiments(sender, time=None, **kwargs): for experiment in get_active_experiments(): --- a/vcweb/lighterprints/views.py Sun Aug 07 18:06:43 2011 -0700 +++ b/vcweb/lighterprints/views.py Sun Aug 07 18:14:28 2011 -0700 @@ -9,7 +9,7 @@ from vcweb.core.views import JSONResponseMixin, dumps # FIXME: move to core? from vcweb.lighterprints.forms import ActivityForm, ChatForm -from vcweb.lighterprints.models import Activity, is_activity_available +from vcweb.lighterprints.models import Activity, is_activity_available, do_activity import collections import logging @@ -74,16 +74,16 @@ pass @csrf_exempt -def do_activity(request, activity_id): +def perform_activity_view(request, activity_id): form = ActivityForm(request.POST or None) if form.is_valid(): activity_id = form.cleaned_data['activity_id'] participant_group_pk = form.cleaned_data['participant_group_relationship_id'] participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) activity = get_object_or_404(Activity, pk=activity_id) - - - return HttpResponse('', content_type='text/javascript') + performed_activity = do_activity(activity=activity, participant_group_relationship=participant_group_relationship) + logger.debug("performed activity %s", performed_activity) + return HttpResponse(dumps(performed_activity), content_type='text/javascript') return HttpResponseBadRequest("Invalid activity post") Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-05 22:20:54
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/98aac8a8db97/ changeset: 98aac8a8db97 user: alllee date: 2011-08-06 00:20:41 summary: adding activity availability to json activity list affected #: 2 files (576 bytes) --- a/vcweb/lighterprints/models.py Fri Aug 05 14:48:24 2011 -0700 +++ b/vcweb/lighterprints/models.py Fri Aug 05 15:20:41 2011 -0700 @@ -68,6 +68,9 @@ return Experiment.objects.filter(experiment_metadata=get_lighterprints_experiment_metadata(), status__in=('ACTIVE', 'ROUND_IN_PROGRESS')) +def is_activity_available(participant=None, experiment=None, activity=None, **kwargs): + return True + @receiver(signals.midnight_tick) def update_active_experiments(sender, time=None, **kwargs): for experiment in get_active_experiments(): --- a/vcweb/lighterprints/views.py Fri Aug 05 14:48:24 2011 -0700 +++ b/vcweb/lighterprints/views.py Fri Aug 05 15:20:41 2011 -0700 @@ -9,7 +9,7 @@ from vcweb.core.views import JSONResponseMixin, dumps # FIXME: move to core? from vcweb.lighterprints.forms import ActivityForm, ChatForm -from vcweb.lighterprints.models import Activity +from vcweb.lighterprints.models import Activity, is_activity_available import collections import logging @@ -17,7 +17,6 @@ class ActivityListView(JSONResponseMixin, MultipleObjectTemplateResponseMixin, BaseListView): -# FIXME: replace with dynamic set model = Activity def get_context_data(self, **kwargs): @@ -31,6 +30,12 @@ activity_as_dict = {} for attr_name in ('pk', 'name', 'summary', 'display_name', 'description', 'savings', 'url', 'available_all_day', 'level', 'group_activity', 'icon_url', 'time_remaining'): activity_as_dict[attr_name] = getattr(activity, attr_name, None) + if self.request.user.is_authenticated(): + # authenticated request, figure out if this activity is available + experiment_id = self.request.GET.get('experiment_id') + participant = self.request.user.participant + experiment = get_object_or_404(Experiment, pk=experiment_id) + activity_as_dict['availability'] = is_activity_available(participant=participant, experiment=experiment, activity=activity) flattened_activities.append(activity_as_dict) context['activity_by_level'] = dict(activity_by_level) @@ -77,6 +82,7 @@ participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) activity = get_object_or_404(Activity, pk=activity_id) + return HttpResponse('', content_type='text/javascript') return HttpResponseBadRequest("Invalid activity post") Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-05 21:48:38
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/5cdd3a8930a8/ changeset: 5cdd3a8930a8 user: alllee date: 2011-08-05 23:48:24 summary: minor tweak to experimenter dashboard affected #: 2 files (556 bytes) --- a/vcweb/core/fixtures/test_users_participants.json Fri Aug 05 13:46:29 2011 -0700 +++ b/vcweb/core/fixtures/test_users_participants.json Fri Aug 05 14:48:24 2011 -0700 @@ -1,12 +1,29 @@ [ { - "pk": 1, - "model": "sites.site", + "pk": 15, + "model": "auth.user", "fields": { - "domain": "example.com", - "name": "example.com" + "username": "sr...@as...", + "first_name": "Steven", + "last_name": "Elias", + "is_active": true, + "is_superuser": false, + "is_staff": true, + "last_login": "2011-07-21 11:26:11", + "groups": [], + "user_permissions": [ + 85, + 86, + 87, + 88, + 89, + 90 + ], + "password": "sha1$b6803$fdf4e561936dcf4d4986ee2820bcb4dbf08501d7", + "email": "sr...@as...", + "date_joined": "2011-07-08 16:23:27" } - }, + }, { "pk": 1, "model": "core.participant", --- a/vcweb/core/templates/experimenter/dashboard.html Fri Aug 05 13:46:29 2011 -0700 +++ b/vcweb/core/templates/experimenter/dashboard.html Fri Aug 05 14:48:24 2011 -0700 @@ -55,12 +55,12 @@ href='{{e.clone_url}}'><img src='{{STATIC_URL}}images/famfamfam/page_copy.png' alt='Clone experiment'/> clone</a></li> {% if e.participant_set.count == 0 %} <li> - <a title='Register participants for this experiment with actual email addresses' href='{{e.controller_url}}/register-email-list'><img src='{{STATIC_URL}}images/famfamfam/group_add.png' alt='register'/> register participants by email</a> + <a title='Register participants for this experiment with actual email addresses' href='{{e.controller_url}}/register-email-list'><img src='{{STATIC_URL}}images/famfamfam/group_add.png' alt='register'/> register participants</a></li><li><a title='Register participants for this experiment with fake email addresses by providing an email suffix and the number of participants.' href='{{e.controller_url}}/register-simple'> - <img src='{{STATIC_URL}}images/famfamfam/group_add.png' alt='register'/> register participants</a> + <img src='{{STATIC_URL}}images/famfamfam/group_add.png' alt='register'/> test participants</a></li> {% else %} <li><a title='clear all participants' href='{{e.controller_url}}/clear-participants' class='confirm-experiment-action'><img src='{{STATIC_URL}}images/famfamfam/group_delete.png' alt=''/> clear all participants</a></li> Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-05 20:46:40
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/5b877f51e341/ changeset: 5b877f51e341 user: alllee date: 2011-08-05 22:46:29 summary: fixing pks in initial data fixtures.. this is painful, need to come up with a better scheme for this affected #: 6 files (1.3 KB) --- a/vcweb/core/models.py Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/core/models.py Fri Aug 05 13:46:29 2011 -0700 @@ -165,6 +165,7 @@ # check each experiment's total_elapsed_time against the total allotted time and # issue round_stopped signals to experiments that need to be stopped. for experiment in es.all(): + logger.debug("checking elapsed time on experiment %s", experiment) experiment.check_elapsed_time() class Experiment(models.Model): --- a/vcweb/core/tests.py Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/core/tests.py Fri Aug 05 13:46:29 2011 -0700 @@ -91,19 +91,6 @@ class Meta: abstract = True -class QueueTest(BaseVcwebTest): - def test_simple(self): - from kombu.connection import BrokerConnection - connection = BrokerConnection(transport="djkombu.transport.DatabaseTransport") - q = connection.SimpleQueue("chat") - for test_string in ('testing', '1-2-3', 'good gravy'): - q.put(test_string) - self.assertEqual(test_string, q.get().body) - - def test_publish(self): - pass - - class ExperimentMetadataTest(BaseVcwebTest): namespace_regex = ExperimentMetadata.namespace_regex @@ -306,7 +293,7 @@ e = self.experiment # current_round is instructions, with no available parameters. round_configuration = e.current_round - name = 'initial.resource_level' + name = 'initial_resource_level' round_configuration.set_parameter(name=name, value=501) self.assertEqual(round_configuration.get_parameter_value(name), 501) self.assertEqual(round_configuration.get_parameter(name).value, round_configuration.get_parameter_value(name)) --- a/vcweb/forestry/fixtures/initial_data.json Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/forestry/fixtures/initial_data.json Fri Aug 05 13:46:29 2011 -0700 @@ -189,7 +189,7 @@ }, { "fields": { - "name":"reset.resource_level", + "name":"reset_resource_level", "experiment_metadata": 1, "creator": 1, "type": "boolean", @@ -201,7 +201,7 @@ }, { "fields": { - "name":"initial.resource_level", + "name":"initial_resource_level", "experiment_metadata": 1, "creator": 1, "type": "int", @@ -249,7 +249,7 @@ { "fields": { "round_configuration": 2, - "parameter": [ "reset.resource_level" ], + "parameter": [ "reset_resource_level" ], "boolean_value": "True" }, "model": "core.roundparametervalue", @@ -258,7 +258,7 @@ { "fields": { "round_configuration": 2, - "parameter": [ "initial.resource_level" ], + "parameter": [ "initial_resource_level" ], "int_value": 100 }, "model": "core.roundparametervalue", @@ -267,7 +267,7 @@ { "fields": { "round_configuration": 3, - "parameter": [ "reset.resource_level" ], + "parameter": [ "reset_resource_level" ], "boolean_value": "True" }, "model": "core.roundparametervalue", @@ -276,7 +276,7 @@ { "fields": { "round_configuration": 3, - "parameter": [ "initial.resource_level" ], + "parameter": [ "initial_resource_level" ], "int_value": 100 }, "model": "core.roundparametervalue", @@ -285,7 +285,7 @@ { "fields": { "round_configuration": 5, - "parameter": [ "reset.resource_level" ], + "parameter": [ "reset_resource_level" ], "boolean_value": "False" }, "model": "core.roundparametervalue", --- a/vcweb/forestry/models.py Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/forestry/models.py Fri Aug 05 13:46:29 2011 -0700 @@ -45,10 +45,10 @@ group.set_data_value(parameter=get_group_harvest_parameter(), value=value) def should_reset_resource_level(round_configuration): - return round_configuration.get_parameter_value('reset.resource_level', default=False) + return round_configuration.get_parameter_value('reset_resource_level', default=False) def get_initial_resource_level(round_configuration): - return round_configuration.get_parameter_value('initial.resource_level', default=100) + return round_configuration.get_parameter_value('initial_resource_level', default=100) def get_max_harvest_decision(resource_level): if resource_level >= 25: --- a/vcweb/lighterprints/fixtures/initial_data.json Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/lighterprints/fixtures/initial_data.json Fri Aug 05 13:46:29 2011 -0700 @@ -33,6 +33,19 @@ "pk": 4 }, { + "fields": { + "date_created": "2011-07-07 15:13:03", + "duration": 0, + "experiment_configuration": 4, + "instructions": "Welcome to the sanitation experiment.", + "last_modified": "2011-07-07 15:13:03", + "round_type": "REGULAR", + "sequence_number": 1 + }, + "model": "core.roundconfiguration", + "pk": 44 + }, + { "pk": 4, "model": "lighterprints.activity", "fields": { --- a/vcweb/sanitation/fixtures/initial_data.json Fri Aug 05 13:17:18 2011 -0700 +++ b/vcweb/sanitation/fixtures/initial_data.json Fri Aug 05 13:46:29 2011 -0700 @@ -44,6 +44,19 @@ }, { "fields": { + "date_created": "2011-07-07 15:13:03", + "duration": 0, + "experiment_configuration": 3, + "instructions": "Welcome to the sanitation experiment.", + "last_modified": "2011-07-07 15:13:03", + "round_type": "REGULAR", + "sequence_number": 1 + }, + "model": "core.roundconfiguration", + "pk": 43 + }, + { + "fields": { "authentication_code": "TEST_SANITATION", "current_round_elapsed_time": 0, "current_round_sequence_number": 1, @@ -75,7 +88,7 @@ "description": "The integer values for this parameter represent locations in a text corpus (i.e., single coordinates OK)" }, "model": "core.parameter", - "pk": 6 + "pk": 7 }, { "fields": { @@ -90,6 +103,6 @@ "description": "The integer values for this parameter are informal foreign keys to the sanitation.pollution location data value pks" }, "model": "core.parameter", - "pk": 7 + "pk": 8 } ] Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-05 20:18:47
|
2 new changesets in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/c0605acbbedc/ changeset: c0605acbbedc user: alllee date: 2011-08-04 19:32:30 summary: first attempt at posting chat messages to the discussion board affected #: 2 files (734 bytes) --- a/vcweb/lighterprints/urls.py Tue Jul 12 19:38:43 2011 -0700 +++ b/vcweb/lighterprints/urls.py Thu Aug 04 10:32:30 2011 -0700 @@ -1,7 +1,7 @@ from django.conf.urls.defaults import url, patterns from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, DoActivityView, MobileView, - DiscussionBoardView) + post_chat_message, DiscussionBoardView) urlpatterns = patterns('vcweb.lighterprints.views', url(r'^mobile$', MobileView.as_view(), name='mobile'), @@ -10,4 +10,5 @@ url(r'^activity/(?P<activity_id>\d+)$', ActivityDetailView.as_view()), url(r'^activity/(?P<activity_id>\d+)/do$', DoActivityView.as_view()), url(r'^discussion/(?P<experiment_id>\d+)/(?P<participant_id>\d+)', DiscussionBoardView.as_view()), + url(r'^discussion/(?P<experiment_id>\d+)/post', post_chat_message), ) --- a/vcweb/lighterprints/views.py Tue Jul 12 19:38:43 2011 -0700 +++ b/vcweb/lighterprints/views.py Thu Aug 04 10:32:30 2011 -0700 @@ -1,10 +1,12 @@ +from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import get_object_or_404 +from django.views.decorators.csrf import csrf_exempt from django.views.generic.detail import BaseDetailView from django.views.generic.edit import FormView from django.views.generic.list import BaseListView, MultipleObjectTemplateResponseMixin from vcweb.core.models import ParticipantGroupRelationship, ChatMessage -from vcweb.core.views import JSONResponseMixin +from vcweb.core.views import JSONResponseMixin, dumps # FIXME: move to core? from vcweb.lighterprints.forms import ChatForm from vcweb.lighterprints.models import Activity @@ -66,9 +68,17 @@ class DoActivityView(FormView): pass -class PostChatMessageView(FormView): - form_class = ChatForm - pass + +@csrf_exempt +def post_chat_message(request): + if request.method == 'POST': + form = ChatForm(request.POST) + if form.is_valid(): + participant_group_pk = form.cleaned_data['participant_group_relationship_id'] + participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) + content = dumps(ChatMessage.objects.filter(participant_group_relationship__group=participant_group_relationship.group)) + return HttpResponse(content, content_type='text/javascript') + return HttpResponseBadRequest() class DiscussionBoardView(JSONResponseMixin, MultipleObjectTemplateResponseMixin, BaseListView): model = ChatMessage http://bitbucket.org/virtualcommons/vcweb/changeset/b3de89732f29/ changeset: b3de89732f29 user: alllee date: 2011-08-05 22:17:18 summary: adding lighter footprints fixture data - experiment, experimenter, default configuration and starting to implement server endpoints. Should look into django-piston to implement this sort of thing in the future.. affected #: 8 files (2.6 KB) --- a/vcweb/core/views.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/core/views.py Fri Aug 05 13:17:18 2011 -0700 @@ -145,8 +145,8 @@ experimenter = Experimenter.objects.create(user=user, institution=institution) logger.debug("creating new experimenter: %s, adding default forestry experiment", experimenter) - # FIXME: add a default experiment for all ExperimentMetadata types - # FIXME: hard coded slovakia experiment, get rid of this! + # FIXME: add a default experiment for all ExperimentMetadata types instead of a hard coded experiment + # configuration experiment = Experiment.objects.get(pk=1) experiment.clone(experimenter=experimenter) else: --- a/vcweb/lighterprints/fixtures/initial_data.json Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/lighterprints/fixtures/initial_data.json Fri Aug 05 13:17:18 2011 -0700 @@ -1,5 +1,38 @@ [ { + "fields": { + "authentication_code": "TEST_LIGHTERPRINTS", + "current_round_elapsed_time": 0, + "current_round_sequence_number": 1, + "duration": "1h", + "experiment_configuration": 4, + "experiment_metadata": [ + "lighterprints" + ], + "experimenter": 1, + "is_experimenter_driven": false, + "start_date_time": null, + "status": "INACTIVE", + "tick_duration": "10s", + "total_elapsed_time": 0 + }, + "model": "core.experiment", + "pk": 4 + }, + { + "fields": { + "creator": 1, + "experiment_metadata": [ + "lighterprints" + ], + "is_public": true, + "max_group_size": 20, + "name": "Lighter Footprints Default Configuration" + }, + "model": "core.experimentconfiguration", + "pk": 4 + }, + { "pk": 4, "model": "lighterprints.activity", "fields": { @@ -63,7 +96,7 @@ "summary": "Recycling processes used materials into new products to prevent waste of potentially useful materials.", "savings": "0.31", "cooldown": 1, - "icon": "", + "icon": "lighterprints/activity-icons/recycle-2-icon.png", "name": "recycle" } }, @@ -317,4 +350,4 @@ "activity": 6 } } -] \ No newline at end of file +] --- a/vcweb/lighterprints/forms.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/lighterprints/forms.py Fri Aug 05 13:17:18 2011 -0700 @@ -2,5 +2,10 @@ class ChatForm(forms.Form): - chat_message = forms.CharField(required=True, max_length=512) - participant_group_relationship = forms.IntegerField(required=True, widget=forms.HiddenInput) + message = forms.CharField(required=True, max_length=512) + participant_group_relationship_id = forms.IntegerField(required=True, widget=forms.HiddenInput) + +class ActivityForm(forms.Form): + activity_id = forms.IntegerField(required=True, widget=forms.HiddenInput) + participant_group_relationship_id = forms.IntegerField(required=True, widget=forms.HiddenInput) + --- a/vcweb/lighterprints/management.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/lighterprints/management.py Fri Aug 05 13:17:18 2011 -0700 @@ -9,14 +9,6 @@ @receiver(post_syncdb, sender=vcweb.core.models, dispatch_uid='lighterprints_metadata_creator') def post_syncdb_handler(sender, **kwargs): - ''' - creates the forestry ExperimentMetadata record if not already created. - FIXME: what are pros/cons for doing it this way vs adding it to initial_data.json - pros: - 1. don't have to hard-code pks and pk references.. - cons: - 1. have to invoke syncdb in order to get this to run - ''' experiment_metadata_dict = { "about_url": "http://commons.asu.edu", "description": "A mobile-ready HTML5 experiment / game that educates and examines how groups of people coordinate to reach carbon emission targets.", --- a/vcweb/lighterprints/urls.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/lighterprints/urls.py Fri Aug 05 13:17:18 2011 -0700 @@ -1,14 +1,15 @@ from django.conf.urls.defaults import url, patterns -from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, DoActivityView, MobileView, - post_chat_message, DiscussionBoardView) +from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, MobileView, + post_chat_message, do_activity, DiscussionBoardView) urlpatterns = patterns('vcweb.lighterprints.views', url(r'^mobile$', MobileView.as_view(), name='mobile'), url(r'^(?P<experiment_id>\d+)/configure$', 'configure', name='configure'), url(r'^activity/list/?$', ActivityListView.as_view()), url(r'^activity/(?P<activity_id>\d+)$', ActivityDetailView.as_view()), - url(r'^activity/(?P<activity_id>\d+)/do$', DoActivityView.as_view()), + url(r'^activity/(?P<activity_id>\d+)/do$', do_activity), url(r'^discussion/(?P<experiment_id>\d+)/(?P<participant_id>\d+)', DiscussionBoardView.as_view()), + url(r'^discussion/(?P<experiment_id>\d+)/', DiscussionBoardView.as_view()), url(r'^discussion/(?P<experiment_id>\d+)/post', post_chat_message), ) --- a/vcweb/lighterprints/views.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/lighterprints/views.py Fri Aug 05 13:17:18 2011 -0700 @@ -5,10 +5,10 @@ from django.views.generic.edit import FormView from django.views.generic.list import BaseListView, MultipleObjectTemplateResponseMixin -from vcweb.core.models import ParticipantGroupRelationship, ChatMessage +from vcweb.core.models import (ChatMessage, Experiment, ParticipantGroupRelationship) from vcweb.core.views import JSONResponseMixin, dumps # FIXME: move to core? -from vcweb.lighterprints.forms import ChatForm +from vcweb.lighterprints.forms import ActivityForm, ChatForm from vcweb.lighterprints.models import Activity import collections @@ -68,20 +68,37 @@ class DoActivityView(FormView): pass +@csrf_exempt +def do_activity(request, activity_id): + form = ActivityForm(request.POST or None) + if form.is_valid(): + activity_id = form.cleaned_data['activity_id'] + participant_group_pk = form.cleaned_data['participant_group_relationship_id'] + participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) + activity = get_object_or_404(Activity, pk=activity_id) + + return HttpResponse('', content_type='text/javascript') + return HttpResponseBadRequest("Invalid activity post") + @csrf_exempt -def post_chat_message(request): - if request.method == 'POST': - form = ChatForm(request.POST) - if form.is_valid(): - participant_group_pk = form.cleaned_data['participant_group_relationship_id'] - participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) - content = dumps(ChatMessage.objects.filter(participant_group_relationship__group=participant_group_relationship.group)) - return HttpResponse(content, content_type='text/javascript') - return HttpResponseBadRequest() +def post_chat_message(request, experiment_id): + experiment = get_object_or_404(Experiment, pk=experiment_id) + form = ChatForm(request.POST or None) + if form.is_valid(): + participant_group_pk = form.cleaned_data['participant_group_relationship_id'] + message = form.cleaned_data['message'] + participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, pk=participant_group_pk) + chat_message = ChatMessage.objects.create(participant_group_relationship=participant_group_relationship, + message=message, round_data=experiment.current_round_data) + logger.debug("Participant %s created chat message %s", request.user.participant, chat_message) + content = dumps(ChatMessage.objects.filter(participant_group_relationship__group=participant_group_relationship.group)) + return HttpResponse(content, content_type='text/javascript') + return HttpResponseBadRequest("Invalid chat message post") class DiscussionBoardView(JSONResponseMixin, MultipleObjectTemplateResponseMixin, BaseListView): model = ChatMessage + template_name = 'discussion_board.html' def get_queryset(self): # FIXME: stubbed out for now, passing in the participant id for the time # being --- a/vcweb/requirements.pip Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/requirements.pip Fri Aug 05 13:17:18 2011 -0700 @@ -9,6 +9,7 @@ django-dajaxice django-autocomplete PIL +django-piston #django-unittest-depth #redis #beanstalkc --- a/vcweb/sanitation/management.py Thu Aug 04 10:32:30 2011 -0700 +++ b/vcweb/sanitation/management.py Fri Aug 05 13:17:18 2011 -0700 @@ -9,16 +9,16 @@ logger = logging.getLogger(__name__) ''' -creates the forestry ExperimentMetadata record if not already created. +creates the sanitation ExperimentMetadata record if not already created. -XXX: also create forestry parameters here? +pros/cons for doing it this way vs adding it to initial_data.json -FIXME: what are pros/cons for doing it this way vs adding it to initial_data.json pros: -1. don't have to hard-code pks and pk references.. +1. don't have to hard-code pks and pk references cons: -1. have to invoke syncdb in order to get this to run +1. have to invoke syncdb in order to get this to run, which is unacceptable once we +start having persistent data ''' Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-04 00:14:13
|
1 new changeset in foraging: http://bitbucket.org/virtualcommons/foraging/changeset/4f98ac374e0a/ changeset: 4f98ac374e0a user: alllee date: 2011-08-04 02:13:58 summary: setting preferred size on chat panel, still needs visual work. Might shift from BorderLayout to a different layout manager. affected #: 4 files (1.3 KB) --- a/.hgignore Tue Aug 02 16:08:46 2011 -0700 +++ b/.hgignore Wed Aug 03 17:13:58 2011 -0700 @@ -6,6 +6,6 @@ experiment-data/* build.properties *.log -*.log.lck +*.log.* .classpath .project --- a/src/main/java/edu/asu/commons/foraging/client/ChatPanel.java Tue Aug 02 16:08:46 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/ChatPanel.java Wed Aug 03 17:13:58 2011 -0700 @@ -95,8 +95,7 @@ } }); JPanel targetHandlePanel = new JPanel(); - targetHandlePanel.setLayout(new BoxLayout(targetHandlePanel, - BoxLayout.LINE_AXIS)); + targetHandlePanel.setLayout(new BoxLayout(targetHandlePanel, BoxLayout.LINE_AXIS)); targetHandleLabel = new JLabel("everyone"); targetHandleLabel.setFont(new Font("Arial", Font.BOLD, 14)); targetHandleLabel.setForeground(new Color(0x0000dd)); @@ -121,14 +120,11 @@ } RoundConfiguration roundConfiguration = client.getCurrentRoundConfiguration(); if (roundConfiguration.isCensoredChat()) { - // FIXME: perform extra checks to see if we are able to send this message + // FIXME: get rid of duplication, add a censored boolean to ChatRequest instead? client.transmit(new CensoredChatRequest(clientId, message, targetIdentifier)); } else { client.transmit(new ChatRequest(clientId, message, targetIdentifier)); -// displayMessage(getChatHandle(clientId) -//// + " -> " + getChatHandle(targetIdentifier) -// , message); } chatField.requestFocusInWindow(); chatField.setText(""); @@ -149,19 +145,6 @@ private static String[] HANDLES; -// public static void main(String[] args) { -// JFrame frame = new JFrame(); -// ChatPanel chatPanel = new ChatPanel(); -// Identifier selfId = new Identifier.Base(); -// chatPanel.setClientId(selfId); -// chatPanel.initialize(Arrays.asList(new Identifier[] { -// new Identifier.Base(), new Identifier.Base(), -// new Identifier.Base(), selfId })); -// frame.add(chatPanel); -// frame.setSize(new Dimension(400, 400)); -// frame.setVisible(true); -// } - private Identifier clientId; private JScrollPane messageScrollPane; @@ -270,6 +253,14 @@ add(textEntryPanel, BorderLayout.SOUTH); textEntryPanel.setChatFieldFocus(); } + + public TextEntryPanel getTextEntryPanel() { + return textEntryPanel; + } + + public JScrollPane getMessageScrollPane() { + return messageScrollPane; + } public void clear() { participants.clear(); @@ -311,9 +302,6 @@ HANDLES[i] = client.getDataModel().getAssignedNumber(participants.get(i)) + ""; } } - -// Collections.shuffle(Arrays.asList(HANDLES)); -// System.err.println("handles: " + HANDLES); initGuiComponents(); } --- a/src/main/java/edu/asu/commons/foraging/client/GameWindow2D.java Tue Aug 02 16:08:46 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/GameWindow2D.java Wed Aug 03 17:13:58 2011 -0700 @@ -627,12 +627,20 @@ // by the server no new clients can connect because the round // has begun. update(configuration.getRoundDuration().getTimeLeft()); - add(messagePanel, BorderLayout.SOUTH); if (configuration.isInRoundChatEnabled()) { ChatPanel chatPanel = getChatPanel(); chatPanel.initialize(); +// Dimension subjectWindowSize = subjectView.getSize(); +// Dimension totalSize = getParent().getSize(); +// System.err.println("subject window size: " + subjectWindowSize); +// System.err.println("total size: " + totalSize); +// Dimension chatPanelSize = new Dimension((totalSize.width - subjectWindowSize.width) / 2, (totalSize.height - subjectWindowSize.height) / 2); +// System.err.println("chat panel size: " + chatPanelSize); + Dimension chatPanelSize = new Dimension(100, getSize().height); + chatPanel.setPreferredSize(chatPanelSize); add(chatPanel, BorderLayout.EAST); } + add(messagePanel, BorderLayout.SOUTH); addCenterComponent(subjectWindow); requestFocusInWindow(); @@ -738,7 +746,6 @@ private ChatPanel getChatPanel() { if (chatPanel == null) { - //System.out.println("Chat panel is null"); chatPanel = new ChatPanel(client); } return chatPanel; --- a/src/main/java/edu/asu/commons/foraging/facilitator/FacilitatorChatPanel.java Tue Aug 02 16:08:46 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/facilitator/FacilitatorChatPanel.java Wed Aug 03 17:13:58 2011 -0700 @@ -7,6 +7,7 @@ import java.awt.event.ActionListener; import javax.swing.GroupLayout; +import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; @@ -15,7 +16,6 @@ import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; -import javax.swing.GroupLayout.Alignment; import edu.asu.commons.event.EventTypeProcessor; import edu.asu.commons.foraging.event.CensoredChatRequest; @@ -114,8 +114,6 @@ */ public class CensoredChatRequestView { - private static final long serialVersionUID = -5819416143717776775L; - private JButton approveButton; private JButton denyButton; private JLabel statusLabel; Repository URL: https://bitbucket.org/virtualcommons/foraging/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-08-02 23:09:01
|
2 new changesets in foraging: http://bitbucket.org/virtualcommons/foraging/changeset/5eb26ee59de2/ changeset: 5eb26ee59de2 user: alllee date: 2011-08-03 00:15:38 summary: fixing field of vision offsets via hacky trial & error affected #: 5 files (501 bytes) --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Tue Aug 02 15:15:38 2011 -0700 @@ -0,0 +1,11 @@ +syntax:glob + +*~ +target +*.jar +experiment-data/* +build.properties +*.log +*.log.lck +.classpath +.project --- a/pom.xml Tue Aug 02 13:19:15 2011 -0700 +++ b/pom.xml Tue Aug 02 15:15:38 2011 -0700 @@ -114,6 +114,7 @@ </plugin><plugin><artifactId>maven-compiler-plugin</artifactId> + <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target> --- a/src/main/java/edu/asu/commons/foraging/client/GridView.java Tue Aug 02 13:19:15 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/GridView.java Tue Aug 02 15:15:38 2011 -0700 @@ -73,11 +73,15 @@ dw = (availableWidth / boardSize.getWidth()); dh = (availableHeight / boardSize.getHeight()); // ensure square proportions - dw = Math.floor(Math.min(dw, dh)); - dh = dw; + dh = dw = Math.min(dw, dh); +// dh = dw; xoffset = (int) Math.floor((availableWidth - (dw * boardSize.getWidth())) / 2); yoffset = (int) Math.floor((availableHeight - (dh * boardSize.getHeight())) / 2); +// System.err.println("x offset: " + xoffset); +// System.err.println("y offset: " + yoffset); +// System.err.println("dw : " + dw); +// System.err.println("dh: " + dh); fontSize = (int)(0.85 * dh); font = new Font("sansserif", Font.BOLD, fontSize); @@ -165,6 +169,7 @@ // this super call to let the UI delegate some paintage as well. // super.paintComponent(graphics); Graphics2D graphics2D = (Graphics2D) graphics; +// graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // FIXME: can be made more efficient. // Could just update the parts that have changed (tokens removed, subjects moved) // paint the background @@ -182,8 +187,8 @@ protected void paintCollection(Collection<Point> collection, Graphics2D graphics2D, Image image, ImageObserver observer) { synchronized (collection) { for (Point point: collection) { - int x = scaleX(point.getX()); - int y = scaleY(point.getY()); + int x = scaleX(point.x); + int y = scaleY(point.y); graphics2D.drawImage(image, x, y, observer); } } @@ -193,8 +198,8 @@ synchronized (collection) { for (Point point: collection) { if (fieldOfView.contains(point)) { - int x = scaleX(point.getX()); - int y = scaleY(point.getY()); + int x = scaleX(point.x); + int y = scaleY(point.y); graphics2D.drawImage(image, x, y, observer); } } @@ -208,22 +213,22 @@ return (int) dh; } - // FIXME: both scaleX and scaleY are called quite often in the course of - // running, should see if we can optimize them further. + // FIXME: profiling shows that both scaleX and scaleY are called a lot at runtime, + // should see if we can optimize them further. protected int scaleX(int x) { return (int) ((dw * x) + xoffset); } - protected int scaleX(double x) { - return (int) ((dw * x) + xoffset); + protected double scaleXDouble(double x) { + return ((dw * x) + xoffset); } protected int scaleY(int y) { return (int) ((dh * y) + yoffset); } - protected int scaleY(double y) { - return (int) ((dh * y) + yoffset); + protected double scaleYDouble(double y) { + return ((dh * y) + yoffset); } --- a/src/main/java/edu/asu/commons/foraging/client/SubjectView.java Tue Aug 02 13:19:15 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/SubjectView.java Tue Aug 02 15:15:38 2011 -0700 @@ -3,7 +3,6 @@ import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; -import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Point; @@ -127,20 +126,20 @@ Point currentPosition = dataModel.getCurrentPosition(); RoundConfiguration roundConfiguration = dataModel.getRoundConfiguration(); if (roundConfiguration.isSubjectsFieldOfVisionEnabled()) { - double radius = roundConfiguration.getViewSubjectsRadius(); + // paint a transparent circle centered on the current position of the subject. + int radius = roundConfiguration.getViewSubjectsRadius(); fieldOfVision = new Circle(currentPosition, radius); - // paint field of vision - Paint originalPaint = graphics2D.getPaint(); - graphics2D.setPaint(FIELD_OF_VISION_COLOR); - Point topLeftCorner = new Point(currentPosition.x - (int) radius, currentPosition.y - (int) radius); - int x = scaleX(topLeftCorner.x); - int y = scaleY(topLeftCorner.y); - int diameter = (int) radius * 2; - diameter = Math.min(scaleX(diameter), scaleY(diameter)); - Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); + Point topLeftCorner = new Point(currentPosition.x - radius, currentPosition.y - radius); + double x = scaleXDouble(topLeftCorner.x) + (dw / 3); + double y = scaleYDouble(topLeftCorner.y) + (dh / 3); + double diameter = radius * 2.0d; + diameter = Math.min(scaleXDouble(diameter), scaleYDouble(diameter)) + (dw / 2); + Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); //graphics2D.fillOval(x, y, diameter, diameter); // clip the rendered part of the Field of vision circle that crosses the playing boundary graphics2D.setClip(circle); + Paint originalPaint = graphics2D.getPaint(); + graphics2D.setPaint(FIELD_OF_VISION_COLOR); graphics2D.fill(circle); graphics2D.setPaint(originalPaint); } --- a/src/main/java/edu/asu/commons/foraging/conf/RoundConfiguration.java Tue Aug 02 13:19:15 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/conf/RoundConfiguration.java Tue Aug 02 15:15:38 2011 -0700 @@ -122,7 +122,7 @@ return ( isPracticeRound() && isPrivateProperty() ) || getBooleanProperty("randomize-group", false); } - + /** * Returns the number of seconds that the flashing visualization of * sanctioning should occur. @@ -149,9 +149,9 @@ return getBooleanProperty("subjects-field-of-vision", false); } - public double getViewSubjectsRadius() { + public int getViewSubjectsRadius() { if (isSubjectsFieldOfVisionEnabled()) { - return getDoubleProperty("view-subjects-radius", 6.0d); + return getIntProperty("view-subjects-radius", 6); } throw new UnsupportedOperationException("subject field of vision is not enabled."); } http://bitbucket.org/virtualcommons/foraging/changeset/9c77588de0dd/ changeset: 9c77588de0dd user: alllee date: 2011-08-03 01:08:46 summary: ripping out most of the unused regulation / enforcement mechanism code, will need to reimplement voting again later in a cleaner way. starting to add chat panel logic to GameWindow2D when in round chat is enabled. affected #: 15 files (11.2 KB) --- a/src/main/java/edu/asu/commons/foraging/client/EnforcementPanel.java Tue Aug 02 15:15:38 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,362 +0,0 @@ -package edu.asu.commons.foraging.client; - - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import edu.asu.commons.foraging.event.EnforcementRankingRequest; -import edu.asu.commons.foraging.model.EnforcementMechanism; -import edu.asu.commons.net.Identifier; - -/** - * $Id: EnforcementPanel.java 529 2010-08-17 00:08:01Z alllee $ - * - * Enforcement panel is used to vote enforcement mechanism - * - * @author dbarge - * @version $Revision: 529 $ - */ - -@SuppressWarnings("serial") -public class EnforcementPanel extends JPanel { - - private ForagingClient client; - - - private String[] votes = { "1", "2", "3","4"}; - private EnforcementMechanism[] enforcementOptions = EnforcementMechanism.values(); - // private String[] enforcementOptions = { - // "No Enforcement - Click here for more info ", - // "Everyone sanctions - Click here for more info ", - // "Randomly picked monitering - Click here for more info", - // "Random sanctioning - Click here for more info " - // }; - - private String[] enforcementText = { - "Everybody can harvest. Nobody can subtract tokens<br>" + - "from others<br>", - - "Each participant can reduce the token amount of<br>" + - "another participant by two tokens at a cost of <br>" + - "one by pressing the numeric key that identifies<br>" + - "the other participant.<br>", - - "Randomly one of the participants is selected to<br>" + - "be the monitoring participant. This participant<br>" + - "can not harvest, but can force another particip<br>" + - "ant to pay a token to the monitoring participan<br>" + - "by pressing the responding numeric key. At the <br>" + - "end of the round each participant who could har<br>" + - "vest pays 25% of the earning to the monitoring <br>" + - "participant.<br>", - - "Same as two, but now each participant takes turns<br>" + - "of 48 seconds randomly assigned by the computer.<br>" - }; - - public EnforcementPanel (ForagingClient client) { - this(); - this.client = client; - this.clientId = client.getId(); - } - - private Identifier clientId; - private JPanel votingPanel; -// private JButton reset; -// private JButton sendMyVotes; - private JPanel instructionsPanel; - private SixChoicePanel[] newPanel; - - private int noOfEnforcements = EnforcementMechanism.values().length; - - private int currentRankingInformation[]; - - private JPanel buttonPanel; - - public EnforcementPanel () - { - newPanel = new SixChoicePanel[4]; - } - - public String getVotedEnforcementOptions(int index){ - return this.enforcementText[index]; - } - - private JPanel getInstructionPanel() - { - JPanel instructionPanel = new JPanel(); - - //instructionPanel.setBackground(color); - instructionPanel.setLayout(new BoxLayout(instructionPanel, BoxLayout.X_AXIS)); - instructionPanel.setBorder(BorderFactory.createTitledBorder("Enforcement Instructions")); - - //create Text area and JSCroll pane for it - String instructions = client.getDataModel().getRoundConfiguration().getVotingInstructions(); - - JTextArea instructionText = new JTextArea(instructions,3,50); - instructionText.setWrapStyleWord(true); - JScrollPane scrollForRegulationText = new JScrollPane(instructionText); - instructionPanel.add(scrollForRegulationText); - - return instructionPanel; - - } - - private Color getColor(int i) - { - Color color = null; - if(i==0) color = new Color(153,153,204); - if(i==1) color = new Color(204,153,153); - if(i==2) color = new Color(153,204,102); - if(i==3) color = new Color(204,204,102); - if(i==4) color = new Color(255,255,153); - return color; - } - - // FIXME: this is extremely inefficient, reimplement later - private void updateVotingPanel(int currentActive){ - int r,c,i; - SixChoicePanel temp = null; -// boolean enableSendButton = true; - - - for(r = 0; r < noOfEnforcements; r++) - { - -// if(newPanel[r].currentRanking == -1)enableSendButton = false; - - if((newPanel[currentActive].currentRanking == newPanel[r].currentRanking) && (r != currentActive)) - { - newPanel[r].currentRanking = -1; - newPanel[r].group.clearSelection(); - } - } - - - for(r = 0; r < noOfEnforcements-1; r++) - { - for(c = 0; c < noOfEnforcements-1; c++) - { - if((newPanel[c].currentRanking > newPanel[c+1].currentRanking)&&(newPanel[c+1].currentRanking != -1)) - { - temp = newPanel[c]; - newPanel[c] = newPanel[c+1]; - newPanel[c+1] = temp; - } - if((newPanel[c].currentRanking < newPanel[c+1].currentRanking)&&(newPanel[c].currentRanking == -1)) - { - temp = newPanel[c]; - newPanel[c] = newPanel[c+1]; - newPanel[c+1] = temp; - } - } - } - for(c = 0; c < noOfEnforcements; c++) - { - // System.out.print(newPanel[c].getCurrentRanking() +" "); - } - - votingPanel.setVisible(false); - remove(votingPanel); - votingPanel = new JPanel(); - votingPanel.setLayout(new BoxLayout(votingPanel, BoxLayout.Y_AXIS)); - - votingPanel.add(getInstructionPanel()); - - - for(i=0; i < noOfEnforcements; i++) { - votingPanel.add(newPanel[i].enforcementPanel); - } - - votingPanel.setVisible(true); - add(votingPanel, BorderLayout.CENTER); - -// if(enableSendButton) { -// sendMyVotes.setEnabled(true); -// buttonPanel.setVisible(true); -// add(buttonPanel, BorderLayout.SOUTH); -// } - revalidate(); - } - - private String getVoteString(){ - - StringBuilder sb = new StringBuilder(); - - for(int c = 0; c < noOfEnforcements; c++) - { - sb.append("\nEnforcement "+(newPanel[c].getCurrentRanking()+1)); - } - return(sb.toString()); - } - - public void sendEnforcementVotes() { - int i; - for(i=0; i < noOfEnforcements; i++) { - if(newPanel[i].currentRanking == -1) - this.currentRankingInformation[i] = -1; - else - this.currentRankingInformation[i] = newPanel[i].getCurrentRanking(); - } - client.transmit(new EnforcementRankingRequest(clientId, currentRankingInformation)); - } - - public void initGuiComponents(){ - - // remove(enforcementInstructionsScrollPane); - // remove(messageScrollPane); - this.currentRankingInformation = new int[4]; - this.newPanel = new SixChoicePanel[4]; - setBackground(Color.lightGray); - setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - votingPanel = new JPanel(); - votingPanel.setLayout(new BoxLayout(votingPanel, BoxLayout.Y_AXIS)); - - //add the instruction panel as the first panel in voting panel. - instructionsPanel = getInstructionPanel(); - votingPanel.add(instructionsPanel); - - - - - for(int i=0; i<noOfEnforcements; i++) { - - //newPanel[i] = new SixChoicePanel(s, votes, enforcementData.getEnforcementID(), getColor(i)); - //newPanel[i] = new SixChoicePanel(s, votes, client.getEnforcementID(), getColor(i)); - newPanel[i] = new SixChoicePanel(enforcementOptions[i], votes, i, getColor(i)); - votingPanel.add(newPanel[i].getEnforcementPanel(i)); - } - - add(votingPanel, BorderLayout.CENTER); -// reset = new JButton("Reset All Ranks"); -// reset.setAlignmentX(Component.CENTER_ALIGNMENT); -// reset.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent e) { -// for(int i=0; i<noOfEnforcements; i++) { -// for(int j=0; j<noOfEnforcements; j++) { -// newPanel[i].option[j].setEnabled(true); -// newPanel[i].group.clearSelection(); -// newPanel[i].currentRanking = -1; -// } -// } -// } -// }); -// sendMyVotes = new JButton("Send votes"); -// sendMyVotes.setAlignmentX(Component.CENTER_ALIGNMENT); -// sendMyVotes.setEnabled(false); -// sendMyVotes.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent e) { -// -// int n = JOptionPane.showConfirmDialog( -// null, "Are you sure to submit your votes ?"+ -// "\nBelow is order of your voting" + -// getVoteString(), -// "Confirm and send votes", -// JOptionPane.YES_NO_OPTION); -// -// if (n == JOptionPane.YES_OPTION) { -// GameWindow2D.duration.expire(); -// } -// if (n == JOptionPane.NO_OPTION) { -// -// } -// -// } -// }); -// buttonPanel = new JPanel(); -// //buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); -// buttonPanel.setLayout(new GridLayout(1,2)); -// buttonPanel.add(reset); -// buttonPanel.add(sendMyVotes); -// buttonPanel.setVisible(true); -// buttonPanel.repaint(); -// add(buttonPanel, BorderLayout.SOUTH); - } - - public void initialize() { - initGuiComponents(); - } - - private class SixChoicePanel implements ActionListener{ - String title; - String description; - String [] buttonLabels; - int enforcementID; - int currentRanking; - JPanel enforcementPanel; - JPanel rankPanel; - ButtonGroup group; - JRadioButton option []; - Color color; - - - public SixChoicePanel(EnforcementMechanism enforcementMechanism, String[] buttonLabels, int enforcementID, Color color ) { - this.title = enforcementMechanism.getTitle(); - this.description = enforcementMechanism.getDescription(); - this.buttonLabels = buttonLabels; - this.enforcementID = enforcementID; - this.color = color; - this.currentRanking = -1; - this.option = new JRadioButton[4]; - } - public int getCurrentRanking(){ - return enforcementID; - } - - public void actionPerformed(ActionEvent e) { - String choice = group.getSelection().getActionCommand(); - int buttonNo = Integer.parseInt(choice); - System.out.println("ACTION Choice Selected: " + choice); - System.out.println("Bno: " + buttonNo); - System.out.println("CurrentActive : "+this.enforcementID); - this.currentRanking = buttonNo; - updateVotingPanel(this.enforcementID); - } - - - public JPanel getEnforcementPanel(int i){ - enforcementPanel = new JPanel(); - enforcementPanel.setBackground(color); - enforcementPanel.setLayout(new BoxLayout(enforcementPanel, BoxLayout.Y_AXIS)); - enforcementPanel.setBorder(BorderFactory.createTitledBorder(title)); - - //create Text area and JSCroll pane for it - - JTextArea regulationText = new JTextArea(title,3,50); - regulationText.setText(description); - regulationText.setWrapStyleWord(true); - JScrollPane scrollForRegulationText = new JScrollPane(regulationText); - enforcementPanel.add(scrollForRegulationText); - - rankPanel = new JPanel(); - rankPanel.setBackground(color); - rankPanel.setLayout(new BoxLayout(rankPanel, BoxLayout.X_AXIS)); - rankPanel.setBorder(BorderFactory.createTitledBorder("Rank")); - group = new ButtonGroup(); - int length = buttonLabels.length; // Assumes even length - - for(int j=0; j<length; j++) { - option[j] = new JRadioButton(buttonLabels[j]); - option[j].setActionCommand(buttonLabels[j]); - group.add(option[j]); - option[j].addActionListener(this); - rankPanel.add(option[j]); - } - enforcementPanel.add(rankPanel); - return enforcementPanel; - } - - } - -} --- a/src/main/java/edu/asu/commons/foraging/client/ForagingClient.java Tue Aug 02 15:15:38 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/ForagingClient.java Tue Aug 02 16:08:46 2011 -0700 @@ -25,16 +25,12 @@ import edu.asu.commons.foraging.event.ClientPositionUpdateEvent; import edu.asu.commons.foraging.event.CollectTokenRequest; import edu.asu.commons.foraging.event.EndRoundEvent; -import edu.asu.commons.foraging.event.EnforcementMechanismUpdateEvent; import edu.asu.commons.foraging.event.LockResourceEvent; import edu.asu.commons.foraging.event.PostRoundSanctionRequest; import edu.asu.commons.foraging.event.PostRoundSanctionUpdateEvent; import edu.asu.commons.foraging.event.RealTimeSanctionRequest; -import edu.asu.commons.foraging.event.RegulationSubmissionUpdateEvent; -import edu.asu.commons.foraging.event.RegulationUpdateEvent; import edu.asu.commons.foraging.event.ResetTokenDistributionRequest; import edu.asu.commons.foraging.event.RoundStartedEvent; -import edu.asu.commons.foraging.event.SanctionUpdateEvent; import edu.asu.commons.foraging.event.ShowInstructionsRequest; import edu.asu.commons.foraging.event.SynchronizeClientEvent; import edu.asu.commons.net.SocketIdentifier; @@ -181,7 +177,6 @@ if (state == ClientState.RUNNING) { dataModel.setGroupDataModel(event.getGroupDataModel()); getGameWindow().endRound(event); - getGameWindow().resetPanels(); if (dataModel.is2dExperiment()) { messageQueue.stop(); } @@ -237,31 +232,31 @@ gameWindow2D.displayMessage(event.toString()); } }); - addEventProcessor(new EventTypeProcessor<EnforcementMechanismUpdateEvent>(EnforcementMechanismUpdateEvent.class) { - public void handle(final EnforcementMechanismUpdateEvent event) { - dataModel.setGroupDataModel(event.getGroupDataModel()); - gameWindow2D.displayActiveEnforcementMechanism(); - } - }); - addEventProcessor(new EventTypeProcessor<RegulationSubmissionUpdateEvent>(RegulationSubmissionUpdateEvent.class) { - public void handle(final RegulationSubmissionUpdateEvent event) { - dataModel.setGroupDataModel(event.getGroupDataModel()); - gameWindow2D.initializeRegulationVotingPanel(); - } - }); - addEventProcessor(new EventTypeProcessor<RegulationUpdateEvent>(RegulationUpdateEvent.class) { - public void handle(final RegulationUpdateEvent event) { - dataModel.setActiveRegulation(event.getRegulationData()); - gameWindow2D.displayActiveRegulation(); - } - }); - - addEventProcessor(new EventTypeProcessor<SanctionUpdateEvent>(SanctionUpdateEvent.class) { - public void handle(final SanctionUpdateEvent event) { - dataModel.setGroupDataModel(event.getGroupDataModel()); - gameWindow2D.displaySanctionMechanism(); - } - }); +// addEventProcessor(new EventTypeProcessor<EnforcementMechanismUpdateEvent>(EnforcementMechanismUpdateEvent.class) { +// public void handle(final EnforcementMechanismUpdateEvent event) { +// dataModel.setGroupDataModel(event.getGroupDataModel()); +// gameWindow2D.displayActiveEnforcementMechanism(); +// } +// }); +// addEventProcessor(new EventTypeProcessor<RegulationSubmissionUpdateEvent>(RegulationSubmissionUpdateEvent.class) { +// public void handle(final RegulationSubmissionUpdateEvent event) { +// dataModel.setGroupDataModel(event.getGroupDataModel()); +// gameWindow2D.initializeRegulationVotingPanel(); +// } +// }); +// addEventProcessor(new EventTypeProcessor<RegulationUpdateEvent>(RegulationUpdateEvent.class) { +// public void handle(final RegulationUpdateEvent event) { +// dataModel.setActiveRegulation(event.getRegulationData()); +// gameWindow2D.displayActiveRegulation(); +// } +// }); +// +// addEventProcessor(new EventTypeProcessor<SanctionUpdateEvent>(SanctionUpdateEvent.class) { +// public void handle(final SanctionUpdateEvent event) { +// dataModel.setGroupDataModel(event.getGroupDataModel()); +// gameWindow2D.displaySanctionMechanism(); +// } +// }); } public boolean canPerformRealTimeSanction() { @@ -292,9 +287,6 @@ private int messagesPerSecond = DEFAULT_MESSAGES_PER_SECOND; private int messagesSent; - // samples are collected over 3 seconds. -// private final static int SAMPLE_TIME = 3; - private int totalMessagesPerSample; private int averageMessagesPerSecond; private Duration secondTick = Duration.create(1); @@ -362,7 +354,7 @@ // moveClient(request); transmit(request); } - Utils.sleep(50); + Utils.sleep(30); } } @@ -383,7 +375,6 @@ private void tick() { if (secondTick.hasExpired()) { secondTick.restart(); - totalMessagesPerSample += messagesSent; messagesSent = 0; } } --- a/src/main/java/edu/asu/commons/foraging/client/GameWindow.java Tue Aug 02 15:15:38 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/GameWindow.java Tue Aug 02 16:08:46 2011 -0700 @@ -17,6 +17,5 @@ public void init(); public void update(long millisecondsLeft); public void showInstructions(); - public void resetPanels(); } --- a/src/main/java/edu/asu/commons/foraging/client/GameWindow2D.java Tue Aug 02 15:15:38 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/GameWindow2D.java Tue Aug 02 16:08:46 2011 -0700 @@ -18,19 +18,15 @@ import java.awt.event.MouseEvent; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; -import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; -import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.SwingUtilities; @@ -49,7 +45,6 @@ import edu.asu.commons.foraging.event.ClientMovementRequest; import edu.asu.commons.foraging.event.CollectTokenRequest; import edu.asu.commons.foraging.event.EndRoundEvent; -import edu.asu.commons.foraging.event.EnforcementRankingRequest; import edu.asu.commons.foraging.event.PostRoundSanctionUpdateEvent; import edu.asu.commons.foraging.event.QuizCompletedEvent; import edu.asu.commons.foraging.event.QuizResponseEvent; @@ -73,7 +68,7 @@ * @author <a href='mailto:All...@as...'>Allen Lee</a> * @version $Revision: 529 $ */ -public class GameWindow2D extends JPanel implements GameWindow, ActionListener { +public class GameWindow2D extends JPanel implements GameWindow { private static final long serialVersionUID = -7733523846114902166L; @@ -89,8 +84,8 @@ private HtmlEditorPane instructionsEditorPane; private JPanel messagePanel; - private JScrollPane errorMessageScrollPane; - private JTextPane errorMessageTextPane; + private JScrollPane messageScrollPane; + private JTextPane messageTextPane; private JPanel labelPanel; @@ -99,10 +94,6 @@ private ChatPanel chatPanel; - private RegulationPanel regulationPanel; - - private EnforcementPanel enforcementPanel; - private JLabel informationLabel; private JLabel timeLeftLabel; @@ -119,6 +110,7 @@ private EventChannel channel; + // FIXME: replace switchXXXPanel with CardLayout switching. private CardLayout cardLayout; // private EnergyLevel energyLevel; @@ -133,10 +125,6 @@ Dimension subjectViewSize = new Dimension((int) Math.floor(size.getWidth()), (int) Math.floor(size.getHeight() * 0.85)); subjectView = new SubjectView(subjectViewSize, dataModel); - // subjectView.addKeyListener(this); - this.currentRankingInformation = new int [2]; - Arrays.fill(currentRankingInformation, -1); -// this.currentRankingInformation[0] = this.currentRankingInformation[1] = -1; initGuiComponents(); } @@ -151,22 +139,11 @@ timeLeftLabel.setText(getTimeLeftLabelText(roundTimeLeft)); // FIXME: subjectView.repaint() causes graphical glitches here // only when we transition from 3D -> 2D experiment. Find out why. - informationLabel.repaint(); - timeLeftLabel.repaint(); subjectView.repaint(); } }); } - public void resetSanctionRanks() { - Arrays.fill(currentRankingInformation, -1); - } - - public void sendSanctionDecisionVotes() { - client.transmit(new EnforcementRankingRequest(client.getId(), currentRankingInformation)); - resetSanctionRanks(); - } - /** * In certain cases, init() _can_ be called before endRound() is finished. Need to lock * access! @@ -195,11 +172,6 @@ } } - private String createStyleString(String questionNumber, String color) { - return String.format(".%s { color: %s; }", questionNumber, color); - } - - private ActionListener createQuizListener(final RoundConfiguration configuration) { return new ActionListener() { public void actionPerformed(ActionEvent e) { @@ -281,98 +253,78 @@ subjectView.collectToken(position); } - private void startRegulationDisplayTimer(){ - if (timer == null) { - final Duration duration = Duration.create(dataModel.getRoundConfiguration().getRegulationDisplayDuration()); - timer = new Timer(1000, new ActionListener() { - public void actionPerformed(ActionEvent event) { - if (duration.hasExpired()) { - timeLeftLabel.setText("Regulation voting will start soon."); - timer.stop(); - timer = null; - initializeEnforcementVotingPanel(); - } - else { - timeLeftLabel.setText( String.format("Voting for the enforcement mechanism will start in %d seconds.", duration.getTimeLeft() / 1000L) ); - } - } - }); - timer.start(); - } - } +// private void startEnforcementVotingTimer() { +// if (timer == null) { +// //FIXME: Need to fetch this value from the round4.xml +// duration = Duration.create(dataModel.getRoundConfiguration().getEnforcementVotingDuration()); +// timer = new Timer(1000, new ActionListener() { +// public void actionPerformed(ActionEvent event) { +// if (duration.hasExpired()) { +// timeLeftLabel.setText("Voting is now disabled."); +// timer.stop(); +// timer = null; +// getEnforcementPanel().sendEnforcementVotes(); +// displayVotingWaitMessage(); +// } +// else { +// timeLeftLabel.setText( String.format("Voting period will end in %d seconds.", duration.getTimeLeft() / 1000L) ); +// } +// } +// }); +// timer.start(); +// } +// } - private void startEnforcementVotingTimer() { - if (timer == null) { - //FIXME: Need to fetch this value from the round4.xml - duration = Duration.create(dataModel.getRoundConfiguration().getEnforcementVotingDuration()); - timer = new Timer(1000, new ActionListener() { - public void actionPerformed(ActionEvent event) { - if (duration.hasExpired()) { - timeLeftLabel.setText("Voting is now disabled."); - timer.stop(); - timer = null; - getEnforcementPanel().sendEnforcementVotes(); - displayVotingWaitMessage(); - } - else { - timeLeftLabel.setText( String.format("Voting period will end in %d seconds.", duration.getTimeLeft() / 1000L) ); - } - } - }); - timer.start(); - } - } - - private void startRegulationVotingTimer() { - - if (timer == null) { - duration = Duration.create(dataModel.getRoundConfiguration().getRegulationVotingDuration()); - - timer = new Timer(1000, new ActionListener() { - public void actionPerformed(ActionEvent event) { - if (duration.hasExpired()) { - timeLeftLabel.setText("Voting is now disabled. Next round begins shortly."); - - //new code - //Need to add the enforcementVotingPane over here - //instead of the instructionsScrollPane - timer.stop(); - timer = null; - //remove(sanctioningPanel); - //getSanctioningPanel().stopTimer(); - getRegulationPanel().sendRegulationVotes(); - displayVotingWaitMessage(); - } - else { - timeLeftLabel.setText( String.format("Voting period will end in %d seconds.", duration.getTimeLeft() / 1000L) ); - } - } - }); - timer.start(); - } - } - - private void startSanctionVotingTimer() { - if (timer == null) { - duration = Duration.create(dataModel.getRoundConfiguration().getSanctionVotingDuration()); - timer = new Timer(1000, new ActionListener() { - public void actionPerformed(ActionEvent event) { - if (duration.hasExpired()) { - timeLeftLabel.setText("Voting is now disabled. Next round begins shortly."); - timer.stop(); - timer = null; - sendSanctionDecisionVotes(); - displayVotingWaitMessage(); - } - else { - timeLeftLabel.setText( String.format("Voting period will now end in %d seconds.", duration.getTimeLeft() / 1000L) ); - } - } - }); - timer.start(); - } - } +// private void startRegulationVotingTimer() { +// +// if (timer == null) { +// duration = Duration.create(dataModel.getRoundConfiguration().getRegulationVotingDuration()); +// +// timer = new Timer(1000, new ActionListener() { +// public void actionPerformed(ActionEvent event) { +// if (duration.hasExpired()) { +// timeLeftLabel.setText("Voting is now disabled. Next round begins shortly."); +// +// //new code +// //Need to add the enforcementVotingPane over here +// //instead of the instructionsScrollPane +// timer.stop(); +// timer = null; +// //remove(sanctioningPanel); +// //getSanctioningPanel().stopTimer(); +// getRegulationPanel().sendRegulationVotes(); +// displayVotingWaitMessage(); +// } +// else { +// timeLeftLabel.setText( String.format("Voting period will end in %d seconds.", duration.getTimeLeft() / 1000L) ); +// } +// } +// }); +// timer.start(); +// } +// } +// +// private void startSanctionVotingTimer() { +// if (timer == null) { +// duration = Duration.create(dataModel.getRoundConfiguration().getSanctionVotingDuration()); +// timer = new Timer(1000, new ActionListener() { +// public void actionPerformed(ActionEvent event) { +// if (duration.hasExpired()) { +// timeLeftLabel.setText("Voting is now disabled. Next round begins shortly."); +// timer.stop(); +// timer = null; +// sendSanctionDecisionVotes(); +// displayVotingWaitMessage(); +// } +// else { +// timeLeftLabel.setText( String.format("Voting period will now end in %d seconds.", duration.getTimeLeft() / 1000L) ); +// } +// } +// }); +// timer.start(); +// } +// } private void startChatTimer() { if (timer == null) { @@ -384,9 +336,9 @@ timeLeftLabel.setText("Chat is now disabled."); timer.stop(); timer = null; - if (roundConfiguration.isVotingAndRegulationEnabled()) { - initializeSanctionDecisionPanel(); - } +// if (roundConfiguration.isVotingAndRegulationEnabled()) { +// initializeSanctionDecisionPanel(); +// } } else { timeLeftLabel.setText( String.format("Chat will end in %d seconds.", duration.getTimeLeft() / 1000L) ); @@ -467,12 +419,6 @@ return htmlPane; } - private RegulationPanel updateRegulationVotingPanel(){ - RegulationPanel regulationPanel = getRegulationPanel(); - regulationPanel.initRegulationVotingComponents(); - return regulationPanel; - } - private void initGuiComponents() { // FIXME: replace with CardLayout for easier switching between panels // cardLayout = new CardLayout(); @@ -507,23 +453,22 @@ // add message window. messagePanel = new JPanel(new BorderLayout()); // messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS)); - messagePanel.add(new JLabel("System Messages"), BorderLayout.NORTH); - errorMessageTextPane = new JTextPane(); - errorMessageTextPane.setEditable(false); - errorMessageTextPane.setFont(new Font("arial", Font.BOLD, 12)); - errorMessageTextPane.setBackground(Color.WHITE); + messagePanel.add(new JLabel("Messages"), BorderLayout.NORTH); + messageTextPane = new JTextPane(); + messageTextPane.setEditable(false); + messageTextPane.setFont(new Font("arial", Font.BOLD, 12)); + messageTextPane.setBackground(Color.WHITE); - addStyles(errorMessageTextPane.getStyledDocument()); - errorMessageScrollPane = new JScrollPane(errorMessageTextPane); + addStyles(messageTextPane.getStyledDocument()); + messageScrollPane = new JScrollPane(messageTextPane); Dimension scrollPaneSize = new Dimension(getPreferredSize().width, 50); - errorMessageScrollPane.setMinimumSize(scrollPaneSize); - errorMessageScrollPane.setPreferredSize(scrollPaneSize); - errorMessageScrollPane.setMaximumSize(scrollPaneSize); - messagePanel.add(errorMessageScrollPane, BorderLayout.CENTER); + messageScrollPane.setMinimumSize(scrollPaneSize); + messageScrollPane.setPreferredSize(scrollPaneSize); + messageScrollPane.setMaximumSize(scrollPaneSize); + messagePanel.add(messageScrollPane, BorderLayout.CENTER); add(messagePanel, BorderLayout.SOUTH); - - + addKeyListener( createGameWindowKeyListener() ); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { @@ -535,7 +480,8 @@ addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent event) { Component component = event.getComponent(); - int subjectViewHeight = component.getHeight() - (errorMessageScrollPane.getHeight() + 35); + // offset by 35 to allow for chat message box + int subjectViewHeight = component.getHeight() - 35; Dimension size = new Dimension(component.getWidth(), subjectViewHeight); subjectView.setScreenSize(size); subjectView.setImageSizes(); @@ -682,7 +628,13 @@ // has begun. update(configuration.getRoundDuration().getTimeLeft()); add(messagePanel, BorderLayout.SOUTH); + if (configuration.isInRoundChatEnabled()) { + ChatPanel chatPanel = getChatPanel(); + chatPanel.initialize(); + add(chatPanel, BorderLayout.EAST); + } addCenterComponent(subjectWindow); + requestFocusInWindow(); } }; @@ -699,11 +651,11 @@ public void displayMessage(String errorMessage, Color color) { // String chatHandle = getChatHandle(source); - errorMessageTextPane.setForeground(color); - StyledDocument document = errorMessageTextPane.getStyledDocument(); + messageTextPane.setForeground(color); + StyledDocument document = messageTextPane.getStyledDocument(); try { document.insertString(document.getLength(), errorMessage + "\n", document.getStyle("bold")); - errorMessageTextPane.setCaretPosition(document.getLength()); + messageTextPane.setCaretPosition(document.getLength()); } catch (BadLocationException e) { e.printStackTrace(); @@ -791,20 +743,7 @@ } return chatPanel; } - private RegulationPanel getRegulationPanel() { - if (regulationPanel == null) { - //System.out.println("Sanc panel is null"); - regulationPanel = new RegulationPanel(client); - } - return regulationPanel; - } - private EnforcementPanel getEnforcementPanel() { - if (enforcementPanel == null) { - //System.out.println("enf panel is null"); - enforcementPanel = new EnforcementPanel(client); - } - return enforcementPanel; - } + public void showInstructions() { RoundConfiguration roundConfiguration = dataModel.getRoundConfiguration(); instructionsBuilder.delete(0, instructionsBuilder.length()); @@ -865,20 +804,20 @@ addCenterComponent(instructionsScrollPane); } - public void displayActiveRegulation() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - String activeRegulation = dataModel.getActiveRegulation().getText(); - if (activeRegulation == null || activeRegulation.trim().isEmpty()) { - activeRegulation = "No regulation specified."; - } - setInstructions( - "<h3>The following regulation received the most votes:</h3><p>" + activeRegulation + "</p>"); - addCenterComponent(instructionsScrollPane); - startRegulationDisplayTimer(); - } - }); - } +// public void displayActiveRegulation() { +// SwingUtilities.invokeLater(new Runnable() { +// public void run() { +// String activeRegulation = dataModel.getActiveRegulation().getText(); +// if (activeRegulation == null || activeRegulation.trim().isEmpty()) { +// activeRegulation = "No regulation specified."; +// } +// setInstructions( +// "<h3>The following regulation received the most votes:</h3><p>" + activeRegulation + "</p>"); +// addCenterComponent(instructionsScrollPane); +// startRegulationDisplayTimer(); +// } +// }); +// } public void updateDebriefing(final PostRoundSanctionUpdateEvent event) { Runnable runnable = new Runnable() { @@ -890,12 +829,6 @@ SwingUtilities.invokeLater(runnable); } - public void resetPanels() { - regulationPanel = null; - enforcementPanel = null; - } - - public void endRound(final EndRoundEvent event) { Runnable runnable = new Runnable() { public void run() { @@ -910,7 +843,7 @@ } // generate debriefing text from data culled from the Event addDebriefingText(event); - errorMessageTextPane.setText(""); + messageTextPane.setText(""); } }; try { @@ -922,106 +855,9 @@ } } - public void initializeEnforcementVotingPanel() { - // TODO: revisit + public void initializeChatPanel() { SwingUtilities.invokeLater(new Runnable() { public void run() { - EnforcementPanel enforcementPanel = getEnforcementPanel(); - enforcementPanel.initialize(); - addCenterComponent(enforcementPanel); - startEnforcementVotingTimer(); - } - }); - } - - - public void initializeRegulationVotingPanel() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - RegulationPanel regulationPanel = updateRegulationVotingPanel(); - addCenterComponent( regulationPanel ); - //sanctioningPanel.startTimer(); - startRegulationVotingTimer(); - } - }); - } - - public void actionPerformed (ActionEvent e) { - String choice = group.getSelection().getActionCommand(); - int buttonNo = Integer.parseInt(choice); - System.out.println("Choice : "+choice); - System.out.println("Button : "+buttonNo); - //currentRankingInformation[buttonNo] = 1; - currentRankingInformation[0] = buttonNo; - - } - - private JPanel getDecisionPanel() { - - if (decisionPanel == null) { - decisionPanel = new JPanel(new BorderLayout()); - decisionPanel.setBackground(Color.GRAY); - - HtmlEditorPane editorPane = createInstructionsEditorPane(); - JScrollPane scrollPane = new JScrollPane(editorPane); - editorPane.setText(dataModel.getRoundConfiguration().getSanctionInstructions()); - decisionPanel.add(scrollPane, BorderLayout.PAGE_START); - - group = new ButtonGroup(); - - JPanel rankPanel = new JPanel(); - rankPanel.setBackground(Color.WHITE); - rankPanel.setLayout(new BoxLayout (rankPanel, BoxLayout.Y_AXIS)); - rankPanel.setBorder(BorderFactory.createTitledBorder("Voting")); - - JLabel sanctionText = new JLabel("Please select one of the options below: "); - - rankPanel.add(Box.createVerticalStrut(5)); - - rankPanel.add(sanctionText); - - rankPanel.add(Box.createVerticalStrut(8)); - - noSanction = new JRadioButton("No penalties [No one can subtract tokens from anyone]"); - noSanction.setActionCommand("0"); - group.add(noSanction); - noSanction.addActionListener(this); - rankPanel.add(noSanction); - - rankPanel.add(Box.createVerticalStrut(8)); - - sanction = new JRadioButton("Allow penalties [Everyone can subtract tokens from each other]"); - sanction.setActionCommand("1"); - group.add(sanction); - sanction.addActionListener(this); - rankPanel.add(sanction); - - decisionPanel.add(rankPanel); - } - group.clearSelection(); - return decisionPanel; - } - - public void initializeSanctionDecisionPanel() { - addCenterComponent(getDecisionPanel()); - startSanctionVotingTimer(); - } - - private JPanel decisionPanel; - private ButtonGroup group; - private JRadioButton sanction; - private JRadioButton noSanction; - private int currentRankingInformation[]; - - - - public void initializeChatPanel() { - //new code - // System.out.println("*****Inside initialize chatPanel()"); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - //new code - // System.out.println("*****Inside thread initialize chatPanel()"); ChatPanel chatPanel = getChatPanel(); chatPanel.initialize(); remove( messagePanel ); --- a/src/main/java/edu/asu/commons/foraging/client/GameWindow3D.java Tue Aug 02 15:15:38 2011 -0700 +++ b/src/main/java/edu/asu/commons/foraging/client/GameWindow3D.java Tue Aug 02 16:08:46 2011 -0700 @@ -117,10 +117,6 @@ } - public void resetPanels() { - - } - private void initializeChatPanel() { getChatPanel().initialize(); } --- a/src/main/java/edu/asu/commons/foraging/client/RegulationPanel.java Tue Aug 02 15:15:38 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,473 +0,0 @@ -package edu.asu.commons.foraging.client; - - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JEditorPane; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.text.Style; -import javax.swing.text.StyleConstants; -import javax.swing.text.StyleContext; -import javax.swing.text.StyledDocument; -import javax.swing.text.html.HTMLEditorKit; - -import edu.asu.commons.foraging.event.RegulationRankingRequest; -import edu.asu.commons.foraging.event.SubmitRegulationRequest; -import edu.asu.commons.foraging.model.RegulationData; -import edu.asu.commons.net.Identifier; - - - -/** - * $Id: RegulationPanel.java 522 2010-06-30 19:17:48Z alllee $ - * - * Sanctioning panel is used to create regulations and - * enforcement mechanism - * - * FIXME: split this functionality out into two different panels, one for submission and the other for voting. - * - * @author dbarge - * @version $Revision: 522 $ - */ - -@SuppressWarnings("serial") -public class RegulationPanel extends JPanel { - - private ForagingClient client; - - public RegulationPanel (ForagingClient client) { - this(); - this.client = client; -// client.getEventChannel().add(this, new EventTypeProcessor<RegulationEvent>(RegulationEvent.class) { -// public void handle(final RegulationEvent regulationEvent) { -// boolean votingFlag=false; -// RegulationData regulationData = null; -// regulations = regulationEvent.getAllRegulations(); -// // System.out.println("Regulation received : "+regulations.size()); -// noOfRegulations = regulations.size(); -// for (Identifier targetId : regulations.keySet()) { -// regulationData = regulations.get(targetId); -// if(regulationData.isVoting())votingFlag = true; -// break; -// } -// if(votingFlag) -// { -// votedRegulation = regulationData; -// Utils.notify(GameWindow2D.regulationVotesSignal); -// } -// else -// { -// //System.out.println("Finding my ID"); -// findAndSetMyRegulationID(); -// Utils.notify(GameWindow2D.regulationSignal); -// } -// } -// }); - } - - public RegulationPanel() { -// regulations = new ArrayList<RegulationData>(); - // FIXME: get rid of hardcoded constants, this should be dynamic based on the size of the group. - newPanel = new SixChoicePanel[5]; - noOfRegulations = 5; - } - - private int noOfRegulations; - - private int[] currentRankingInformation; - - private SixChoicePanel[] newPanel; - - private JPanel votingPanel; - private JPanel instructionsPanel; -// private JPanel buttonPanel; -// private JButton sendMyVotes; -// private JButton reset; - - private String[] votes = { "1", "2", "3","4", "5"}; - - private JScrollPane messageScrollPane; - - private JScrollPane regulationsInstructionsScrollPane; - - private JTextPane messageWindow; - - private List<Identifier> participants; - - private JEditorPane regulationsInstructionsPane; - -// private void findAndSetMyRegulationID() -// { -// for (Identifier targetId : regulations.keySet()) { -// if(regulations.get(targetId).getRegulationText().compareTo(message) == 0){ -// client.setRegulationID(regulations.get(targetId).getRegulationID()); -// //client.setEnforcementID(regulations.get(targetId).getToken()); -// client.setToken(regulations.get(targetId).getToken()); -// //System.out.println("My RegID:"+client.getRegulationID()); -// //System.out.println("Token:"+client.getEnforcementID()); -// return; -// } -// } -// } - private void addStylesToMessageWindow() { - StyledDocument styledDocument = messageWindow.getStyledDocument(); - // and why not have something like... StyleContext.getDefaultStyle() to - // replace this junk - Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle( - StyleContext.DEFAULT_STYLE); - // Style regularStyle = styledDocument.addStyle("regular", - // defaultStyle); - StyleConstants.setFontFamily(defaultStyle, "Helvetica"); - StyleConstants.setBold(styledDocument.addStyle("bold", defaultStyle), - true); - StyleConstants.setItalic(styledDocument - .addStyle("italic", defaultStyle), true); - } - - // FIXME: messy, refactor after experiment. - private void updateVotingPanel(int currentActive){ - int r,c,i; - SixChoicePanel temp = null; -// boolean enableSendButton = true; - - // System.out.println("Active panel: "+SixChoicePanel.currentActive); - // The below for loop is used to clear off radio button of the panel whose ranking conflicts - // with the new panel's radio button - - - for(r = 0; r < noOfRegulations; r++) - { - System.out.print(newPanel[r].currentRanking+" "); -// if(newPanel[r].currentRanking == -1) enableSendButton = false; - - if((newPanel[currentActive].currentRanking == newPanel[r].currentRanking) && (r != currentActive)) - { - newPanel[r].currentRanking = -1; - newPanel[r].group.clearSelection(); - } - } - - //The below for loops are used for sorting the panels when the ranks are - //changed - - for(r = 0; r < noOfRegulations-1; r++) - { - for(c = 0; c < noOfRegulations-1; c++) - { - if((newPanel[c].currentRanking > newPanel[c+1].currentRanking)&&(newPanel[c+1].currentRanking != -1)) - { - temp = newPanel[c]; - newPanel[c] = newPanel[c+1]; - newPanel[c+1] = temp; - } - if((newPanel[c].currentRanking < newPanel[c+1].currentRanking)&&(newPanel[c].currentRanking == -1)) - { - temp = newPanel[c]; - newPanel[c] = newPanel[c+1]; - newPanel[c+1] = temp; - } - } - } - - votingPanel.setVisible(false); - remove(votingPanel); - votingPanel = new JPanel(); - votingPanel.setLayout(new BoxLayout(votingPanel, BoxLayout.Y_AXIS)); - - votingPanel.add(getInstructionPanel()); - - - for(i=0; i < noOfRegulations; i++) { - votingPanel.add(newPanel[i].regulationPanel); - } - - votingPanel.setVisible(true); - add(votingPanel, BorderLayout.CENTER); - -// if(enableSendButton) { -// sendMyVotes.setEnabled(true); -// buttonPanel.setVisible(true); -// add(buttonPanel, BorderLayout.SOUTH); -// } - revalidate(); - } - - public void sendRegulation() { - client.transmit(new SubmitRegulationRequest(client.getId(), messageWindow.getText())); - } - - public void sendRegulationVotes() { - System.out.println("Regulation votes ready to be sent"); - // System.err.println("message: " + message); - int i; - for(i=0; i < noOfRegulations; i++) { - if(newPanel[i].currentRanking == -1) - this.currentRankingInformation[i] = -1; - else - this.currentRankingInformation[i] = newPanel[i].getCurrentRanking(); - } - - client.transmit(new RegulationRankingRequest(client.getId(), currentRankingInformation)); - } - - private Color getColor(int i) - { - Color color = null; - if(i==0) color = new Color(153,153,204); - if(i==1) color = new Color(204,153,153); - if(i==2) color = new Color(153,204,102); - if(i==3) color = new Color(204,204,102); - if(i==4) color = new Color(255,255,153); - return color; - } - - private String getVoteString(){ - - StringBuilder sb = new StringBuilder(); - - for(int c = 0; c < noOfRegulations; c++) - { - sb.append("\nRegulation "+(newPanel[c].getCurrentRanking()+1)); - } - return(sb.toString()); - } - - public void initRegulationVotingComponents(){ - - if (regulationsInstructionsScrollPane != null) { - remove(regulationsInstructionsScrollPane); - } - if (messageScrollPane != null) { - remove(messageScrollPane); - } - this.currentRankingInformation = new int[5]; - this.newPanel = new SixChoicePanel[5]; - setBackground(Color.lightGray); - setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - votingPanel = new JPanel(); - votingPanel.setLayout(new BoxLayout(votingPanel, BoxLayout.Y_AXIS)); - - //add the instruction panel as the first panel in voting panel. - instructionsPanel = getInstructionPanel(); - votingPanel.add(instructionsPanel); - - // this is for dummy regulation data for testing - // start -// for(int i=0; i<5; i++) { -// RegulationData regulationData1 = new RegulationData(); -// regulationData1.setRegulationID(i); -// regulationData1.setRegulationText("Test Regulation " + i); -// Identifier temp = new Identifier.Base (){}; -// System.out.println("Idn : " + temp); -// regulations.put(temp, regulationData1); -// } -// System.out.println(regulations.size()); - // end - - //for(int i=0; i<5; i++) { - List<RegulationData> submittedRegulations = client.getDataModel().getSubmittedRegulations(); -// List<RegulationData> submittedRegulations = -// Arrays.asList(new RegulationData(new Identifier.Base(), "Regulation 1", 0), -// new RegulationData(new Identifier.Base(), "Regulation 2", 1), -// new RegulationData(new Identifier.Base(), "Regulation 3", 2), -// new RegulationData(new Identifier.Base(), "Regulation 4", 3), -// new RegulationData(new Identifier.Base(), "Regulation 5", 4)); - - for (RegulationData regulationData : submittedRegulations) { - System.err.println("creating six choice panel from regulation data: " + regulationData); - // FIXME: are you aware that th... [truncated message content] |
From: Bitbucket <com...@bi...> - 2011-08-02 20:19:42
|
1 new changeset in foraging: http://bitbucket.org/virtualcommons/foraging/changeset/78873f479f96/ changeset: 78873f479f96 user: alllee date: 2011-08-02 22:19:15 summary: updating ant + ivy initialization - should consider consolidating deployment to one build tool instead of having ant + maven + ivy affected #: 3 files (578 bytes) --- a/build.xml Sun Jun 05 06:55:34 2011 +0200 +++ b/build.xml Tue Aug 02 13:19:15 2011 -0700 @@ -1,95 +1,72 @@ +<?xml version="1.0"?><!-- $Id: build.xml 330 2008-02-13 05:31:26Z alllee $ vim:sts=2:sw=2: Version: $Revision: 330 $ --> -<project xmlns:ivy='antlib:org.apache.ivy.ant' name="foraging" default="build-all" basedir="."> - +<project xmlns:ivy="antlib:org.apache.ivy.ant" name="foraging" default="build-all" basedir="."><!-- ensure ivy availability --> - <!-- - <path id='ivy.lib.path'> - <fileset dir='lib/ivy' includes='*.jar'/> - </path> - <taskdef resource='org/apache/ivy/ant/antlib.xml' - uri='antlib:org.apache.ivy.ant' - classpathref='ivy.lib.path'/> - --> - <property name="ivy.install.version" value="2.1.0" /> - <condition property="ivy.home" value="${env.IVY_HOME}"> - <isset property="env.IVY_HOME" /> - </condition> - <property name="ivy.home" value="${user.home}/.ant" /> - <property name="ivy.jar.dir" value="${ivy.home}/lib" /> - <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" /> - - <target name="download-ivy" unless="offline"> - <mkdir dir="${ivy.jar.dir}"/> - <!-- download Ivy from web site so that it can be used even without any special installation --> - <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" - dest="${ivy.jar.file}" usetimestamp="true"/> - </target> - - <target name="init-ivy" depends="download-ivy"> - <!-- try to load ivy here from ivy home, in case the user has not already dropped + <property name="ivy.install.version" value="2.2.0"/> + <condition property="ivy.home" value="${env.IVY_HOME}"> + <isset property="env.IVY_HOME"/> + </condition> + <property name="ivy.home" value="${user.home}/.ant"/> + <property name="ivy.jar.dir" value="${ivy.home}/lib"/> + <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar"/> + <target name="download-ivy" unless="offline"> + <mkdir dir="${ivy.jar.dir}"/> + <!-- download Ivy from web site so that it can be used even without any special installation --> + <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" dest="${ivy.jar.file}" usetimestamp="true"/> + </target> + <target name="init-ivy" depends="download-ivy"> + <!-- try to load ivy here from ivy home, in case the user has not already dropped it into ant's lib dir (note that the latter copy will always take precedence). We will not fail as long as local lib dir exists (it may be empty) and ivy is in at least one of ant's lib dir or the local lib dir. --> - <path id="ivy.lib.path"> - <fileset dir="${ivy.jar.dir}" includes="*.jar"/> - </path> - <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> - </target> - - <target name='resolve' depends='init-ivy' description='--> retrieve dependencies with ivy'> - <ivy:retrieve pattern='${lib.dir}/[artifact].[ext]'/> - </target> - + <path id="ivy.lib.path"> + <fileset dir="${ivy.jar.dir}" includes="*.jar"/> + </path> + <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> + </target><!-- Load all properties from the build.properties file, then try to define defaults for all the properties. The property definitions in the build.properties file will have precedence. - --> - <property file="build.properties" /> + --> + <property file="build.properties"/><!-- default compilation properties --> - <property name='src.dir' value='src/main/java'/> - <property name='build.dir' value='target/classes'/> - + <property name="src.dir" value="src/main/java"/> + <property name="build.dir" value="target/classes"/><!-- default web & deployment properties --> - <property name='web.dir' value='src/main/webapp'/> - <property name='server.port' value='16001'/> - <property name='server.xml' value='server.xml'/> - <property name='codebase.url' value='http://${server.address}/${ant.project.name}'/> - <property name='client.class' value='edu.asu.commons.foraging.client.ForagingClient'/> - <property name='facilitator.class' value='edu.asu.commons.foraging.facilitator.Facilitator'/> - <property name='server.class' value='edu.asu.commons.foraging.server.ForagingServer'/> - <property name='framework.jar' value='csidex.jar'/> - - <property name='dist.dir' value='.' /> - - <property name='resources.dir' value='src/main/resources'/> - <property name='conf.dir' value='${resources.dir}/configuration'/> - + <property name="web.dir" value="src/main/webapp"/> + <property name="server.port" value="16001"/> + <property name="server.xml" value="server.xml"/> + <property name="codebase.url" value="http://${server.address}/${ant.project.name}"/> + <property name="client.class" value="edu.asu.commons.foraging.client.ForagingClient"/> + <property name="facilitator.class" value="edu.asu.commons.foraging.facilitator.Facilitator"/> + <property name="server.class" value="edu.asu.commons.foraging.server.ForagingServer"/> + <property name="framework.jar" value="csidex.jar"/> + <property name="dist.dir" value="."/> + <property name="resources.dir" value="src/main/resources"/> + <property name="conf.dir" value="${resources.dir}/configuration"/><!-- test properties --><property name="test.src.dir" value="src/test/java"/><property name="test.build.dir" value="target/test-classes"/> - <property name="test.results.dir" value="target/surefire-reports" /> - + <property name="test.results.dir" value="target/surefire-reports"/><property name="javadoc.dir" value="docs/javadoc"/><property name="javadoc.private.dir" value="docs/private"/> - <property name='lib.dir' value='lib'/> - + <property name="lib.dir" value="lib"/><!-- Set up the CLASSPATH, includes all jars in the lib directory and all built files for both the main project and the tests --><path id="project.classpath"> - <pathelement location="." /> + <pathelement location="."/><fileset dir="${lib.dir}"> - <include name="**/*.jar" /> + <include name="**/*.jar"/></fileset> - <pathelement location="${build.dir}" /> - <pathelement location="${test.build.dir}" /> - <pathelement location='${resources.dir}' /> + <pathelement location="${build.dir}"/> + <pathelement location="${test.build.dir}"/> + <pathelement location="${resources.dir}"/></path> - <target name="help"><echo> NOTE: At minimum you will need to modify the default web.dir and @@ -110,249 +87,209 @@ convert - invokes the ForagingSaveFileConverter to process the savefiles in the raw-data directory or as specified by -Dsavefile.dir=foo </echo></target> - - <target name='build-all' depends='facilitator-jar, client-jar, server-jar, compile'/> - -<!-- deploys the client + facilitator + csidex jarfiles to the appropriate + <target name="build-all" depends="facilitator-jar, client-jar, server-jar, compile"/> + <!-- deploys the client + facilitator + csidex jarfiles to the appropriate webapps directory. --> - <target name='deploy-to' depends='build-all'> - <mkdir dir='${deploy.dir}'/> + <target name="deploy-to" depends="build-all"> + <mkdir dir="${deploy.dir}"/><!-- copy client jar, facilitator jar, and csidex.jar to web deployment directory --> - <copy todir='${deploy.dir}' overwrite='true'> - <fileset dir='${dist.dir}'> - <include name='client.jar'/> - <include name='facilitator.jar'/> + <copy todir="${deploy.dir}" overwrite="true"> + <fileset dir="${dist.dir}"> + <include name="client.jar"/> + <include name="facilitator.jar"/></fileset> - <fileset dir='${lib.dir}'> - <include name='${framework.jar}'/> + <fileset dir="${lib.dir}"> + <include name="${framework.jar}"/></fileset> - <fileset dir='${resources.dir}/web'> - <include name='index.html'/> - <include name='WEB-INF/**'/> + <fileset dir="${resources.dir}/web"> + <include name="index.html"/> + <include name="WEB-INF/**"/></fileset></copy><!-- copy images --> - <copy todir='${deploy.dir}/images' overwrite='true'> - <fileset dir='${resources.dir}/images'/> + <copy todir="${deploy.dir}/images" overwrite="true"> + <fileset dir="${resources.dir}/images"/></copy><!-- copy client and facilitator JNLP descriptor files, replacing url/main class tokens. --> - <copy file='${resources.dir}/web/client.jnlp' todir='${deploy.dir}' overwrite='true'> + <copy file="${resources.dir}/web/client.jnlp" todir="${deploy.dir}" overwrite="true"><filterset> - <filter token='CODEBASE_URL' value='${codebase.url}'/> - <filter token='MAIN_CLASS' value='${client.class}'/> - <filter token='FRAMEWORK_JAR' value='${framework.jar}'/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> + <filter token="MAIN_CLASS" value="${client.class}"/> + <filter token="FRAMEWORK_JAR" value="${framework.jar}"/></filterset></copy> - <copy file='${resources.dir}/web/facilitator.jnlp' todir='${deploy.dir}' overwrite='true'> + <copy file="${resources.dir}/web/facilitator.jnlp" todir="${deploy.dir}" overwrite="true"><filterset> - <filter token='CODEBASE_URL' value='${codebase.url}'/> - <filter token='MAIN_CLASS' value='${facilitator.class}'/> - <filter token='FRAMEWORK_JAR' value='${framework.jar}'/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> + <filter token="MAIN_CLASS" value="${facilitator.class}"/> + <filter token="FRAMEWORK_JAR" value="${framework.jar}"/></filterset></copy> - <chmod dir='${deploy.dir}' perm='664' type='file' includes='**'/> - <chmod dir='${deploy.dir}' perm='775' type='dir' includes='**'/> + <chmod dir="${deploy.dir}" perm="664" type="file" includes="**"/> + <chmod dir="${deploy.dir}" perm="775" type="dir" includes="**"/></target> - - <target name='deploy'> - <antcall target='deploy-to'> - <param name='deploy.dir' value='${web.dir}'/> + <target name="deploy"> + <antcall target="deploy-to"> + <param name="deploy.dir" value="${web.dir}"/></antcall></target> - - <target name='client-jar' depends='server-jar'> - <antcall target='build-jar'> - <param name='main.class' value='${client.class}'/> - <param name='jar.name' value='client.jar'/> + <target name="client-jar" depends="server-jar"> + <antcall target="build-jar"> + <param name="main.class" value="${client.class}"/> + <param name="jar.name" value="client.jar"/></antcall></target> - - <target name='facilitator-jar' depends='client-jar'> - <antcall target='build-jar'> - <param name='main.class' value='${facilitator.class}'/> - <param name='jar.name' value='facilitator.jar'/> + <target name="facilitator-jar" depends="client-jar"> + <antcall target="build-jar"> + <param name="main.class" value="${facilitator.class}"/> + <param name="jar.name" value="facilitator.jar"/></antcall></target> - - - <target name='server-jar' depends='compile, configure'> - <antcall target='build-jar'> - <param name='main.class' value='${server.class}'/> - <param name='jar.name' value='server.jar'/> + <target name="server-jar" depends="compile, configure"> + <antcall target="build-jar"> + <param name="main.class" value="${server.class}"/> + <param name="jar.name" value="server.jar"/></antcall> - <move file='${dist.dir}/server.jar' tofile='server.jar'/> + <move file="${dist.dir}/server.jar" tofile="server.jar"/></target> - - <target name='build-jar'> - <manifestclasspath property='manifest.classpath' jarfile='${jar.name}'> - <classpath refid='project.classpath'/> + <target name="build-jar"> + <manifestclasspath property="manifest.classpath" jarfile="${jar.name}"> + <classpath refid="project.classpath"/></manifestclasspath> - <chmod dir='${build.dir}' perm='a+rx' type='dir' includes='**'/> - <chmod dir='${build.dir}' perm='a+r' type='file' includes='**'/> - <manifest file='manifest.mf'> + <chmod dir="${build.dir}" perm="a+rx" type="dir" includes="**"/> + <chmod dir="${build.dir}" perm="a+r" type="file" includes="**"/> + <manifest file="manifest.mf"><attribute name="Main-Class" value="${main.class}"/> - <attribute name='Class-Path' value='${manifest.classpath}'/> + <attribute name="Class-Path" value="${manifest.classpath}"/></manifest> - <jar destfile='${dist.dir}/${jar.name}' manifest='manifest.mf'> - <fileset dir='${build.dir}'> - <include name='edu/asu/commons/**'/> - <include name='data/**'/> - <include name='conf/**'/> - <include name='images/**'/> + <jar destfile="${dist.dir}/${jar.name}" manifest="manifest.mf"> + <fileset dir="${build.dir}"> + <include name="edu/asu/commons/**"/> + <include name="data/**"/> + <include name="conf/**"/> + <include name="images/**"/></fileset></jar> - <chmod file='${dist.dir}/${jar.name}' perm='664'/> + <chmod file="${dist.dir}/${jar.name}" perm="664"/></target><!-- Prepare for a build by creating appropriate directories --> - <target name="prepare" depends='resolve'> + <target name="prepare" depends="init-ivy"><mkdir dir="${build.dir}"/><mkdir dir="${test.build.dir}"/> - <mkdir dir='${dist.dir}'/> + <mkdir dir="${dist.dir}"/> + <mkdir dir='${lib.dir}'/></target> - + <target name='resolve' depends='init-ivy' description='--> retrieve dependencies with ivy'> + <ivy:retrieve pattern='${lib.dir}/[artifact].[ext]'/> + </target><!-- Clean up build by deleting build directories --><target name="clean"><delete dir="${build.dir}"/><delete dir="${test.build.dir}"/> - <delete dir='${lib.dir}'/> - <delete file='server.jar'/> - <delete file='client.jar'/> - <delete file='facilitator.jar'/> + <delete dir="${lib.dir}"/> + <delete file="server.jar"/> + <delete file="client.jar"/> + <delete file="facilitator.jar"/></target> - <!-- Compile project source files --> - <target name='compile' depends="prepare"> - <javac srcdir="${src.dir}" - destdir="${build.dir}" - debug="on" - optimize="off" - deprecation="on" - source="1.6" - includeAntRuntime="false" - > - <compilerarg value='-Xlint:unchecked'/> - <classpath refid="project.classpath" /> + <target name="compile" depends="prepare, resolve"> + <javac srcdir="${src.dir}" destdir="${build.dir}" debug="on" optimize="off" deprecation="on" source="1.6" includeAntRuntime="false"> + <compilerarg value="-Xlint:unchecked"/> + <classpath refid="project.classpath"/></javac> - <copy todir='${build.dir}/data'> - <fileset dir='${resources.dir}/data'/> + <copy todir="${build.dir}/data"> + <fileset dir="${resources.dir}/data"/></copy> - <copy todir='${build.dir}/images'> - <fileset dir='${resources.dir}/images'/> + <copy todir="${build.dir}/images"> + <fileset dir="${resources.dir}/images"/></copy></target> - - <target name='configure'> - <copy todir='${build.dir}/conf'> - <fileset dir='${conf.dir}'/> + <target name="configure"> + <copy todir="${build.dir}/conf"> + <fileset dir="${conf.dir}"/><filterset> - <filter token='SERVER_ADDRESS' value='${server.address}'/> - <filter token='PORT_NUMBER' value='${server.port}'/> - <filter token='CODEBASE_URL' value='${codebase.url}'/> + <filter token="SERVER_ADDRESS" value="${server.address}"/> + <filter token="PORT_NUMBER" value="${server.port}"/> + <filter token="CODEBASE_URL" value="${codebase.url}"/></filterset></copy></target> - - <target name='profile' depends='test'> - <java jar='${project.profiler}' classpathref='project.classpath' fork='true'> - <arg value='${hprof.file}'/> + <target name="profile" depends="test"> + <java jar="${project.profiler}" classpathref="project.classpath" fork="true"> + <arg value="${hprof.file}"/></java><!-- do something like java -jar PerfAnal.jar <hprof.txt> --></target> - <!-- Build project documentation --><target name="docs"> - <javadoc sourcepath="${src.dir}" - destdir="${javadoc.dir}" - packagenames="*" - source="1.6" - classpathref='project.classpath' - link='http://java.sun.com/javase/6/docs/api/ - http://commons.asu.edu/src/csidex/api' - overview="${src.dir}/overview.html" /> + <javadoc sourcepath="${src.dir}" destdir="${javadoc.dir}" packagenames="*" source="1.6" classpathref="project.classpath" link="http://java.sun.com/javase/6/docs/api/ http://commons.asu.edu/src/csidex/api" overview="${src.dir}/overview.html"/></target> - <!-- RUN TARGETS --> - <target name='client' depends='compile'> - <java classname='${client.class}' - classpathref='project.classpath' - fork='yes'/> + <target name="client" depends="compile"> + <java classname="${client.class}" classpathref="project.classpath" fork="yes"/></target> - - <target name='fac' depends='compile'> - <java classname='${facilitator.class}' - classpathref='project.classpath' - fork='yes'/> + <target name="fac" depends="compile"> + <java classname="${facilitator.class}" classpathref="project.classpath" fork="yes"/></target> - - <target name='deploy-server' depends='deploy, server' /> - - <target name='server' depends='compile'> + <target name="deploy-server" depends="deploy, server"/> + <target name="server" depends="compile"><!-- make sure we update the configuration --> - <copy todir='${build.dir}/conf' overwrite='true'> - <fileset dir='${conf.dir}'/> + <copy todir="${build.dir}/conf" overwrite="true"> + <fileset dir="${conf.dir}"/><filterset> - <filter token='SERVER_ADDRESS' value='${server.address}'/> - <filter token='PORT_NUMBER' value='${server.port}'/> - <filter token='CODEBASE_URL' value='${codebase.url}'/> + <filter token="SERVER_ADDRESS" value="${server.address}"/> + <filter token="PORT_NUMBER" value="${server.port}"/> + <filter token="CODEBASE_URL" value="${codebase.url}"/></filterset></copy> - <java classname='${server.class}' classpathref='project.classpath' fork='yes'> + <java classname="${server.class}" classpathref="project.classpath" fork="yes"><jvmarg value="-server"/></java></target> - - <!-- Compile Tests --><target name="compile-tests" depends="compile"> - <javac srcdir="${test.src.dir}" - destdir="${test.build.dir}" - source="1.6" - debug="on"> + <javac srcdir="${test.src.dir}" destdir="${test.build.dir}" source="1.6" debug="on"><!-- <compilerarg value='-Xlint:unchecked'/> --> - <classpath refid="project.classpath" /> + <classpath refid="project.classpath"/></javac></target> - <!-- Run Tests --> - <target name="test" depends="compile-tests"> - <delete dir="${test.results.dir}"/> - <mkdir dir="${test.results.dir}"/> - <junit fork="yes" haltonfailure="yes" printsummary="yes"> - <classpath refid="project.classpath" /> - <batchtest todir="${test.results.dir}" > - <formatter usefile="no" type="plain" /> - <formatter type="xml" /> - <fileset dir="${test.build.dir}"> - <include name="**/*Test.class" /> - </fileset> - </batchtest> - </junit> - </target> - - <property name='savefile.converter.class' value='edu.asu.commons.foraging.data.ForagingSaveFileConverter'/> + <target name="test" depends="compile-tests"> + <delete dir="${test.results.dir}"/> + <mkdir dir="${test.results.dir}"/> + <junit fork="yes" haltonfailure="yes" printsummary="yes"> + <classpath refid="project.classpath"/> + <batchtest todir="${test.results.dir}"> + <formatter usefile="no" type="plain"/> + <formatter type="xml"/> + <fileset dir="${test.build.dir}"> + <include name="**/*Test.class"/> + </fileset> + </batchtest> + </junit> + </target> + <property name="savefile.converter.class" value="edu.asu.commons.foraging.data.ForagingSaveFileConverter"/><!-- default savefile directory is the raw-data directory --> - <property name='savefile.dir' value='raw-data'/> - <target name='convert' depends='compile'> - <java classname='${savefile.converter.class}' classpathref='project.classpath' fork='yes'> - <arg value='${savefile.dir}'/> + <property name="savefile.dir" value="raw-data"/> + <target name="convert" depends="compile"> + <java classname="${savefile.converter.class}" classpathref="project.classpath" fork="yes"> + <arg value="${savefile.dir}"/></java></target> - <!-- Run Test on GUI --><target name="guitest" depends="compile-tests"><java fork="yes" classname="junit.swingui.TestRunner" taskname="JUnit" failonerror="true" dir="${basedir}"> - <jvmarg value="-Djunit.test.path=${test.build.dir}" /> - <sysproperty key="basedir" value="${basedir}" /> - <classpath> - <path refid="project.classpath" /> - </classpath> + <jvmarg value="-Djunit.test.path=${test.build.dir}"/> + <sysproperty key="basedir" value="${basedir}"/> + <classpath> + <path refid="project.classpath"/> + </classpath></java></target> - </project> --- a/deploy.bat Sun Jun 05 06:55:34 2011 +0200 +++ b/deploy.bat Tue Aug 02 13:19:15 2011 -0700 @@ -2,6 +2,6 @@ REM directory should be bin and lib directories containing the Ant REM executables and library dependencies. set ANT_HOME=C:\tools\ant -set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_10 +set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_26 set PATH=%ANT_HOME%\bin;%JAVA_HOME%\bin;%PATH% ant deploy --- a/pom.xml Sun Jun 05 06:55:34 2011 +0200 +++ b/pom.xml Tue Aug 02 13:19:15 2011 -0700 @@ -42,11 +42,11 @@ </license></licenses><scm> - <url>https://virtualcommons.svn.sourceforge.net/svnroot/virtualcommons/foraging</url> + <url>https://bitbucket.org/virtualcommons/foraging</url></scm><issueManagement> - <system>JIRA</system> - <url>http://opensource.asu.edu/jira/browse/COMMONS</url> + <system>Bitbucket</system> + <url>https://bitbucket.org/virtualcommons/foraging/issues</url></issueManagement><repositories><repository> Repository URL: https://bitbucket.org/virtualcommons/foraging/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: <al...@us...> - 2011-07-15 16:07:01
|
Revision: 535 http://virtualcommons.svn.sourceforge.net/virtualcommons/?rev=535&view=rev Author: alllee Date: 2011-07-15 16:06:50 +0000 (Fri, 15 Jul 2011) Log Message: ----------- fixing ivy dependency management Modified Paths: -------------- foraging/trunk/build.xml Modified: foraging/trunk/build.xml =================================================================== --- foraging/trunk/build.xml 2011-05-08 02:02:39 UTC (rev 534) +++ foraging/trunk/build.xml 2011-07-15 16:06:50 UTC (rev 535) @@ -1,3 +1,4 @@ +<?xml version="1.0"?> <!-- $Id: build.xml 330 2008-02-13 05:31:26Z alllee $ vim:sts=2:sw=2: Version: $Revision: 330 $ @@ -2,90 +3,66 @@ --> -<project xmlns:ivy='antlib:org.apache.ivy.ant' name="foraging" default="build-all" basedir="."> - +<project xmlns:ivy="antlib:org.apache.ivy.ant" name="foraging" default="build-all" basedir="."> <!-- ensure ivy availability --> - <!-- - <path id='ivy.lib.path'> - <fileset dir='lib/ivy' includes='*.jar'/> - </path> - <taskdef resource='org/apache/ivy/ant/antlib.xml' - uri='antlib:org.apache.ivy.ant' - classpathref='ivy.lib.path'/> - --> - <property name="ivy.install.version" value="2.1.0" /> - <condition property="ivy.home" value="${env.IVY_HOME}"> - <isset property="env.IVY_HOME" /> - </condition> - <property name="ivy.home" value="${user.home}/.ant" /> - <property name="ivy.jar.dir" value="${ivy.home}/lib" /> - <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" /> - - <target name="download-ivy" unless="offline"> - <mkdir dir="${ivy.jar.dir}"/> - <!-- download Ivy from web site so that it can be used even without any special installation --> - <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" - dest="${ivy.jar.file}" usetimestamp="true"/> - </target> - - <target name="init-ivy" depends="download-ivy"> - <!-- try to load ivy here from ivy home, in case the user has not already dropped + <property name="ivy.install.version" value="2.2.0"/> + <condition property="ivy.home" value="${env.IVY_HOME}"> + <isset property="env.IVY_HOME"/> + </condition> + <property name="ivy.home" value="${user.home}/.ant"/> + <property name="ivy.jar.dir" value="${ivy.home}/lib"/> + <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar"/> + <target name="download-ivy" unless="offline"> + <mkdir dir="${ivy.jar.dir}"/> + <!-- download Ivy from web site so that it can be used even without any special installation --> + <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" dest="${ivy.jar.file}" usetimestamp="true"/> + </target> + <target name="init-ivy" depends="download-ivy"> + <!-- try to load ivy here from ivy home, in case the user has not already dropped it into ant's lib dir (note that the latter copy will always take precedence). We will not fail as long as local lib dir exists (it may be empty) and ivy is in at least one of ant's lib dir or the local lib dir. --> - <path id="ivy.lib.path"> - <fileset dir="${ivy.jar.dir}" includes="*.jar"/> - </path> - <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> - </target> - - <target name='resolve' depends='init-ivy' description='--> retrieve dependencies with ivy'> - <ivy:retrieve pattern='${lib.dir}/[artifact].[ext]'/> - </target> - + <path id="ivy.lib.path"> + <fileset dir="${ivy.jar.dir}" includes="*.jar"/> + </path> + <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/> + </target> <!-- Load all properties from the build.properties file, then try to define defaults for all the properties. The property definitions in the build.properties file will have precedence. - --> - <property file="build.properties" /> + --> + <property file="build.properties"/> <!-- default compilation properties --> - <property name='src.dir' value='src/main/java'/> - <property name='build.dir' value='target/classes'/> - + <property name="src.dir" value="src/main/java"/> + <property name="build.dir" value="target/classes"/> <!-- default web & deployment properties --> - <property name='web.dir' value='src/main/webapp'/> - <property name='server.port' value='16001'/> - <property name='server.xml' value='server.xml'/> - <property name='codebase.url' value='http://${server.address}/${ant.project.name}'/> - <property name='client.class' value='edu.asu.commons.foraging.client.ForagingClient'/> - <property name='facilitator.class' value='edu.asu.commons.foraging.facilitator.Facilitator'/> - <property name='server.class' value='edu.asu.commons.foraging.server.ForagingServer'/> - <property name='framework.jar' value='csidex.jar'/> - - <property name='dist.dir' value='.' /> - - <property name='resources.dir' value='src/main/resources'/> - <property name='conf.dir' value='${resources.dir}/configuration'/> - + <property name="web.dir" value="src/main/webapp"/> + <property name="server.port" value="16001"/> + <property name="server.xml" value="server.xml"/> + <property name="codebase.url" value="http://${server.address}/${ant.project.name}"/> + <property name="client.class" value="edu.asu.commons.foraging.client.ForagingClient"/> + <property name="facilitator.class" value="edu.asu.commons.foraging.facilitator.Facilitator"/> + <property name="server.class" value="edu.asu.commons.foraging.server.ForagingServer"/> + <property name="framework.jar" value="csidex.jar"/> + <property name="dist.dir" value="."/> + <property name="resources.dir" value="src/main/resources"/> + <property name="conf.dir" value="${resources.dir}/configuration"/> <!-- test properties --> <property name="test.src.dir" value="src/test/java"/> <property name="test.build.dir" value="target/test-classes"/> - <property name="test.results.dir" value="target/surefire-reports" /> - + <property name="test.results.dir" value="target/surefire-reports"/> <property name="javadoc.dir" value="docs/javadoc"/> <property name="javadoc.private.dir" value="docs/private"/> - <property name='lib.dir' value='lib'/> - + <property name="lib.dir" value="lib"/> <!-- Set up the CLASSPATH, includes all jars in the lib directory and all built files for both the main project and the tests --> <path id="project.classpath"> - <pathelement location="." /> + <pathelement location="."/> <fileset dir="${lib.dir}"> - <include name="**/*.jar" /> + <include name="**/*.jar"/> </fileset> - <pathelement location="${build.dir}" /> - <pathelement location="${test.build.dir}" /> - <pathelement location='${resources.dir}' /> + <pathelement location="${build.dir}"/> + <pathelement location="${test.build.dir}"/> + <pathelement location="${resources.dir}"/> </path> - <target name="help"> @@ -110,249 +87,209 @@ convert - invokes the ForagingSaveFileConverter to process the savefiles in the raw-data directory or as specified by -Dsavefile.dir=foo </echo> </target> - - <target name='build-all' depends='facilitator-jar, client-jar, server-jar, compile'/> - -<!-- deploys the client + facilitator + csidex jarfiles to the appropriate + <target name="build-all" depends="facilitator-jar, client-jar, server-jar, compile"/> + <!-- deploys the client + facilitator + csidex jarfiles to the appropriate webapps directory. --> - <target name='deploy-to' depends='build-all'> - <mkdir dir='${deploy.dir}'/> + <target name="deploy-to" depends="build-all"> + <mkdir dir="${deploy.dir}"/> <!-- copy client jar, facilitator jar, and csidex.jar to web deployment directory --> - <copy todir='${deploy.dir}' overwrite='true'> - <fileset dir='${dist.dir}'> - <include name='client.jar'/> - <include name='facilitator.jar'/> + <copy todir="${deploy.dir}" overwrite="true"> + <fileset dir="${dist.dir}"> + <include name="client.jar"/> + <include name="facilitator.jar"/> </fileset> - <fileset dir='${lib.dir}'> - <include name='${framework.jar}'/> + <fileset dir="${lib.dir}"> + <include name="${framework.jar}"/> </fileset> - <fileset dir='${resources.dir}/web'> - <include name='index.html'/> - <include name='WEB-INF/**'/> + <fileset dir="${resources.dir}/web"> + <include name="index.html"/> + <include name="WEB-INF/**"/> </fileset> </copy> <!-- copy images --> - <copy todir='${deploy.dir}/images' overwrite='true'> - <fileset dir='${resources.dir}/images'/> + <copy todir="${deploy.dir}/images" overwrite="true"> + <fileset dir="${resources.dir}/images"/> </copy> <!-- copy client and facilitator JNLP descriptor files, replacing url/main class tokens. --> - <copy file='${resources.dir}/web/client.jnlp' todir='${deploy.dir}' overwrite='true'> + <copy file="${resources.dir}/web/client.jnlp" todir="${deploy.dir}" overwrite="true"> <filterset> - <filter token='CODEBASE_URL' value='${codebase.url}'/> - <filter token='MAIN_CLASS' value='${client.class}'/> - <filter token='FRAMEWORK_JAR' value='${framework.jar}'/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> + <filter token="MAIN_CLASS" value="${client.class}"/> + <filter token="FRAMEWORK_JAR" value="${framework.jar}"/> </filterset> </copy> - <copy file='${resources.dir}/web/facilitator.jnlp' todir='${deploy.dir}' overwrite='true'> + <copy file="${resources.dir}/web/facilitator.jnlp" todir="${deploy.dir}" overwrite="true"> <filterset> - <filter token='CODEBASE_URL' value='${codebase.url}'/> - <filter token='MAIN_CLASS' value='${facilitator.class}'/> - <filter token='FRAMEWORK_JAR' value='${framework.jar}'/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> + <filter token="MAIN_CLASS" value="${facilitator.class}"/> + <filter token="FRAMEWORK_JAR" value="${framework.jar}"/> </filterset> </copy> - <chmod dir='${deploy.dir}' perm='664' type='file' includes='**'/> - <chmod dir='${deploy.dir}' perm='775' type='dir' includes='**'/> + <chmod dir="${deploy.dir}" perm="664" type="file" includes="**"/> + <chmod dir="${deploy.dir}" perm="775" type="dir" includes="**"/> </target> - - <target name='deploy'> - <antcall target='deploy-to'> - <param name='deploy.dir' value='${web.dir}'/> + <target name="deploy"> + <antcall target="deploy-to"> + <param name="deploy.dir" value="${web.dir}"/> </antcall> </target> - - <target name='client-jar' depends='server-jar'> - <antcall target='build-jar'> - <param name='main.class' value='${client.class}'/> - <param name='jar.name' value='client.jar'/> + <target name="client-jar" depends="server-jar"> + <antcall target="build-jar"> + <param name="main.class" value="${client.class}"/> + <param name="jar.name" value="client.jar"/> </antcall> </target> - - <target name='facilitator-jar' depends='client-jar'> - <antcall target='build-jar'> - <param name='main.class' value='${facilitator.class}'/> - <param name='jar.name' value='facilitator.jar'/> + <target name="facilitator-jar" depends="client-jar"> + <antcall target="build-jar"> + <param name="main.class" value="${facilitator.class}"/> + <param name="jar.name" value="facilitator.jar"/> </antcall> </target> - - - <target name='server-jar' depends='compile, configure'> - <antcall target='build-jar'> - <param name='main.class' value='${server.class}'/> - <param name='jar.name' value='server.jar'/> + <target name="server-jar" depends="compile, configure"> + <antcall target="build-jar"> + <param name="main.class" value="${server.class}"/> + <param name="jar.name" value="server.jar"/> </antcall> - <move file='${dist.dir}/server.jar' tofile='server.jar'/> + <move file="${dist.dir}/server.jar" tofile="server.jar"/> </target> - - <target name='build-jar'> - <manifestclasspath property='manifest.classpath' jarfile='${jar.name}'> - <classpath refid='project.classpath'/> + <target name="build-jar"> + <manifestclasspath property="manifest.classpath" jarfile="${jar.name}"> + <classpath refid="project.classpath"/> </manifestclasspath> - <chmod dir='${build.dir}' perm='a+rx' type='dir' includes='**'/> - <chmod dir='${build.dir}' perm='a+r' type='file' includes='**'/> - <manifest file='manifest.mf'> + <chmod dir="${build.dir}" perm="a+rx" type="dir" includes="**"/> + <chmod dir="${build.dir}" perm="a+r" type="file" includes="**"/> + <manifest file="manifest.mf"> <attribute name="Main-Class" value="${main.class}"/> - <attribute name='Class-Path' value='${manifest.classpath}'/> + <attribute name="Class-Path" value="${manifest.classpath}"/> </manifest> - <jar destfile='${dist.dir}/${jar.name}' manifest='manifest.mf'> - <fileset dir='${build.dir}'> - <include name='edu/asu/commons/**'/> - <include name='data/**'/> - <include name='conf/**'/> - <include name='images/**'/> + <jar destfile="${dist.dir}/${jar.name}" manifest="manifest.mf"> + <fileset dir="${build.dir}"> + <include name="edu/asu/commons/**"/> + <include name="data/**"/> + <include name="conf/**"/> + <include name="images/**"/> </fileset> </jar> - <chmod file='${dist.dir}/${jar.name}' perm='664'/> + <chmod file="${dist.dir}/${jar.name}" perm="664"/> </target> <!-- Prepare for a build by creating appropriate directories --> - <target name="prepare" depends='resolve'> + <target name="prepare" depends="init-ivy"> <mkdir dir="${build.dir}"/> <mkdir dir="${test.build.dir}"/> - <mkdir dir='${dist.dir}'/> + <mkdir dir="${dist.dir}"/> + <mkdir dir='${lib.dir}'/> </target> - + <target name='resolve' depends='init-ivy' description='--> retrieve dependencies with ivy'> + <ivy:retrieve pattern='${lib.dir}/[artifact].[ext]'/> + </target> <!-- Clean up build by deleting build directories --> <target name="clean"> <delete dir="${build.dir}"/> <delete dir="${test.build.dir}"/> - <delete dir='${lib.dir}'/> - <delete file='server.jar'/> - <delete file='client.jar'/> - <delete file='facilitator.jar'/> + <delete dir="${lib.dir}"/> + <delete file="server.jar"/> + <delete file="client.jar"/> + <delete file="facilitator.jar"/> </target> - <!-- Compile project source files --> - <target name='compile' depends="prepare"> - <javac srcdir="${src.dir}" - destdir="${build.dir}" - debug="on" - optimize="off" - deprecation="on" - source="1.6" - includeAntRuntime="false" - > - <compilerarg value='-Xlint:unchecked'/> - <classpath refid="project.classpath" /> + <target name="compile" depends="prepare, resolve"> + <javac srcdir="${src.dir}" destdir="${build.dir}" debug="on" optimize="off" deprecation="on" source="1.6" includeAntRuntime="false"> + <compilerarg value="-Xlint:unchecked"/> + <classpath refid="project.classpath"/> </javac> - <copy todir='${build.dir}/data'> - <fileset dir='${resources.dir}/data'/> + <copy todir="${build.dir}/data"> + <fileset dir="${resources.dir}/data"/> </copy> - <copy todir='${build.dir}/images'> - <fileset dir='${resources.dir}/images'/> + <copy todir="${build.dir}/images"> + <fileset dir="${resources.dir}/images"/> </copy> </target> - - <target name='configure'> - <copy todir='${build.dir}/conf'> - <fileset dir='${conf.dir}'/> + <target name="configure"> + <copy todir="${build.dir}/conf"> + <fileset dir="${conf.dir}"/> <filterset> - <filter token='SERVER_ADDRESS' value='${server.address}'/> - <filter token='PORT_NUMBER' value='${server.port}'/> - <filter token='CODEBASE_URL' value='${codebase.url}'/> + <filter token="SERVER_ADDRESS" value="${server.address}"/> + <filter token="PORT_NUMBER" value="${server.port}"/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> </filterset> </copy> </target> - - <target name='profile' depends='test'> - <java jar='${project.profiler}' classpathref='project.classpath' fork='true'> - <arg value='${hprof.file}'/> + <target name="profile" depends="test"> + <java jar="${project.profiler}" classpathref="project.classpath" fork="true"> + <arg value="${hprof.file}"/> </java> <!-- do something like java -jar PerfAnal.jar <hprof.txt> --> </target> - <!-- Build project documentation --> <target name="docs"> - <javadoc sourcepath="${src.dir}" - destdir="${javadoc.dir}" - packagenames="*" - source="1.6" - classpathref='project.classpath' - link='http://java.sun.com/javase/6/docs/api/ - http://commons.asu.edu/src/csidex/api' - overview="${src.dir}/overview.html" /> + <javadoc sourcepath="${src.dir}" destdir="${javadoc.dir}" packagenames="*" source="1.6" classpathref="project.classpath" link="http://java.sun.com/javase/6/docs/api/ http://commons.asu.edu/src/csidex/api" overview="${src.dir}/overview.html"/> </target> - <!-- RUN TARGETS --> - <target name='client' depends='compile'> - <java classname='${client.class}' - classpathref='project.classpath' - fork='yes'/> + <target name="client" depends="compile"> + <java classname="${client.class}" classpathref="project.classpath" fork="yes"/> </target> - - <target name='fac' depends='compile'> - <java classname='${facilitator.class}' - classpathref='project.classpath' - fork='yes'/> + <target name="fac" depends="compile"> + <java classname="${facilitator.class}" classpathref="project.classpath" fork="yes"/> </target> - - <target name='deploy-server' depends='deploy, server' /> - - <target name='server' depends='compile'> + <target name="deploy-server" depends="deploy, server"/> + <target name="server" depends="compile"> <!-- make sure we update the configuration --> - <copy todir='${build.dir}/conf' overwrite='true'> - <fileset dir='${conf.dir}'/> + <copy todir="${build.dir}/conf" overwrite="true"> + <fileset dir="${conf.dir}"/> <filterset> - <filter token='SERVER_ADDRESS' value='${server.address}'/> - <filter token='PORT_NUMBER' value='${server.port}'/> - <filter token='CODEBASE_URL' value='${codebase.url}'/> + <filter token="SERVER_ADDRESS" value="${server.address}"/> + <filter token="PORT_NUMBER" value="${server.port}"/> + <filter token="CODEBASE_URL" value="${codebase.url}"/> </filterset> </copy> - <java classname='${server.class}' classpathref='project.classpath' fork='yes'> + <java classname="${server.class}" classpathref="project.classpath" fork="yes"> <jvmarg value="-server"/> </java> </target> - - <!-- Compile Tests --> <target name="compile-tests" depends="compile"> - <javac srcdir="${test.src.dir}" - destdir="${test.build.dir}" - source="1.6" - debug="on"> + <javac srcdir="${test.src.dir}" destdir="${test.build.dir}" source="1.6" debug="on"> <!-- <compilerarg value='-Xlint:unchecked'/> --> - <classpath refid="project.classpath" /> + <classpath refid="project.classpath"/> </javac> </target> - <!-- Run Tests --> - <target name="test" depends="compile-tests"> - <delete dir="${test.results.dir}"/> - <mkdir dir="${test.results.dir}"/> - <junit fork="yes" haltonfailure="yes" printsummary="yes"> - <classpath refid="project.classpath" /> - <batchtest todir="${test.results.dir}" > - <formatter usefile="no" type="plain" /> - <formatter type="xml" /> - <fileset dir="${test.build.dir}"> - <include name="**/*Test.class" /> - </fileset> - </batchtest> - </junit> - </target> - - <property name='savefile.converter.class' value='edu.asu.commons.foraging.data.ForagingSaveFileConverter'/> + <target name="test" depends="compile-tests"> + <delete dir="${test.results.dir}"/> + <mkdir dir="${test.results.dir}"/> + <junit fork="yes" haltonfailure="yes" printsummary="yes"> + <classpath refid="project.classpath"/> + <batchtest todir="${test.results.dir}"> + <formatter usefile="no" type="plain"/> + <formatter type="xml"/> + <fileset dir="${test.build.dir}"> + <include name="**/*Test.class"/> + </fileset> + </batchtest> + </junit> + </target> + <property name="savefile.converter.class" value="edu.asu.commons.foraging.data.ForagingSaveFileConverter"/> <!-- default savefile directory is the raw-data directory --> - <property name='savefile.dir' value='raw-data'/> - <target name='convert' depends='compile'> - <java classname='${savefile.converter.class}' classpathref='project.classpath' fork='yes'> - <arg value='${savefile.dir}'/> + <property name="savefile.dir" value="raw-data"/> + <target name="convert" depends="compile"> + <java classname="${savefile.converter.class}" classpathref="project.classpath" fork="yes"> + <arg value="${savefile.dir}"/> </java> </target> - <!-- Run Test on GUI --> <target name="guitest" depends="compile-tests"> <java fork="yes" classname="junit.swingui.TestRunner" taskname="JUnit" failonerror="true" dir="${basedir}"> - <jvmarg value="-Djunit.test.path=${test.build.dir}" /> - <sysproperty key="basedir" value="${basedir}" /> - <classpath> - <path refid="project.classpath" /> - </classpath> + <jvmarg value="-Djunit.test.path=${test.build.dir}"/> + <sysproperty key="basedir" value="${basedir}"/> + <classpath> + <path refid="project.classpath"/> + </classpath> </java> </target> - </project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Bitbucket <com...@bi...> - 2011-07-13 02:39:01
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/b8f3cd495b7c/ changeset: b8f3cd495b7c user: alllee date: 2011-07-13 04:38:43 summary: starting to work on server endpoints for lighterprints, some complications though: 1. figure out how to deal with django csrf appropriately from sencha touch (or bypass it by using GET instead of POST 2. still need to wire up participant + sample experiment for a lighterprints experiment. affected #: 4 files (1.7 KB) --- a/vcweb/lighterprints/urls.py Mon Jul 11 15:55:25 2011 -0700 +++ b/vcweb/lighterprints/urls.py Tue Jul 12 19:38:43 2011 -0700 @@ -1,6 +1,7 @@ from django.conf.urls.defaults import url, patterns -from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, DoActivityView, MobileView) +from vcweb.lighterprints.views import (ActivityDetailView, ActivityListView, DoActivityView, MobileView, + DiscussionBoardView) urlpatterns = patterns('vcweb.lighterprints.views', url(r'^mobile$', MobileView.as_view(), name='mobile'), @@ -8,4 +9,5 @@ url(r'^activity/list/?$', ActivityListView.as_view()), url(r'^activity/(?P<activity_id>\d+)$', ActivityDetailView.as_view()), url(r'^activity/(?P<activity_id>\d+)/do$', DoActivityView.as_view()), + url(r'^discussion/(?P<experiment_id>\d+)/(?P<participant_id>\d+)', DiscussionBoardView.as_view()), ) --- a/vcweb/lighterprints/views.py Mon Jul 11 15:55:25 2011 -0700 +++ b/vcweb/lighterprints/views.py Tue Jul 12 19:38:43 2011 -0700 @@ -1,8 +1,12 @@ +from django.shortcuts import get_object_or_404 from django.views.generic.detail import BaseDetailView from django.views.generic.edit import FormView from django.views.generic.list import BaseListView, MultipleObjectTemplateResponseMixin +from vcweb.core.models import ParticipantGroupRelationship, ChatMessage from vcweb.core.views import JSONResponseMixin +# FIXME: move to core? +from vcweb.lighterprints.forms import ChatForm from vcweb.lighterprints.models import Activity import collections @@ -15,7 +19,7 @@ model = Activity def get_context_data(self, **kwargs): - context = super(BaseListView, self).get_context_data(**kwargs) + context = super(ActivityListView, self).get_context_data(**kwargs) all_activities = context['activity_list'] activity_by_level = collections.defaultdict(list) flattened_activities = [] @@ -62,6 +66,29 @@ class DoActivityView(FormView): pass +class PostChatMessageView(FormView): + form_class = ChatForm + pass + +class DiscussionBoardView(JSONResponseMixin, MultipleObjectTemplateResponseMixin, BaseListView): + model = ChatMessage + def get_queryset(self): + # FIXME: stubbed out for now, passing in the participant id for the time + # being + # participant = self.request.user.participant + participant_id = self.kwargs['participant_id'] + experiment_id = self.kwargs['experiment_id'] +# FIXME: will change once we have proper auth set up + self.participant_group_relationship = get_object_or_404(ParticipantGroupRelationship, participant__pk=participant_id, group__experiment__pk=experiment_id) + self.group = self.participant_group_relationship.group + return ChatMessage.objects.filter(participant_group_relationship__group = self.group) + + def get_context_data(self, **kwargs): + context = super(DiscussionBoardView, self).get_context_data(**kwargs) + context['group'] = self.group + context['participant_group_relationship'] = self.participant_group_relationship + return context + def get_available_activities(request): # FIXME: currently stubbed out to return all activities. should move this to # models.py and have it take a Participant? --- a/vcweb/sanitation/fixtures/initial_data.json Mon Jul 11 15:55:25 2011 -0700 +++ b/vcweb/sanitation/fixtures/initial_data.json Tue Jul 12 19:38:43 2011 -0700 @@ -65,7 +65,9 @@ { "fields": { "name":"sanitation.pollution", - "experiment_metadata": 3, + "experiment_metadata": [ + "sanitation" + ], "creator": 4, "type": "int", "date_created": "2011-01-01 15:13:07", @@ -78,7 +80,9 @@ { "fields": { "name":"sanitation.collectedpollution", - "experiment_metadata": 3, + "experiment_metadata": [ + "sanitation" + ], "creator": 4, "type": "int", "date_created": "2011-01-01 15:13:07", Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-11 22:55:41
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/d60d5771e1ae/ changeset: d60d5771e1ae user: alllee date: 2011-07-12 00:55:25 summary: updated sanitation model code for pollutifying an experiment (periodically, will eventually be invoked via celery and with the appropriate pollution_amount) and generating a pollutified string. Also fixed some incorrect pk linkages with the sanitation initial_data affected #: 4 files (2.5 KB) --- a/vcweb/core/models.py Sat Jul 09 01:05:12 2011 -0700 +++ b/vcweb/core/models.py Mon Jul 11 15:55:25 2011 -0700 @@ -396,6 +396,7 @@ u = User.objects.create_user(username=email, email=email, password=password) users.append(u) for user in users: + logger.debug("registering user %s", user) (p, created) = Participant.objects.get_or_create(user=user) # FIXME: instead of asking for the email suffix, perhaps we just append the institution URL to keep it simpler? if institution and p.institution != institution: @@ -464,7 +465,9 @@ # FIXME: record previous mappings in activity log. self.group_set.all().delete() # seed the initial group. - current_group = self.group_set.create(number=1, max_size=self.experiment_configuration.max_group_size) + max_group_size = self.experiment_configuration.max_group_size + logger.debug("creating group with max size %d", max_group_size) + current_group = self.group_set.create(number=1, max_size=max_group_size) participants = list(self.participant_set.all()) if randomize: random.shuffle(participants) --- a/vcweb/sanitation/fixtures/initial_data.json Sat Jul 09 01:05:12 2011 -0700 +++ b/vcweb/sanitation/fixtures/initial_data.json Mon Jul 11 15:55:25 2011 -0700 @@ -48,7 +48,7 @@ "current_round_elapsed_time": 0, "current_round_sequence_number": 1, "duration": "1h", - "experiment_configuration": 1, + "experiment_configuration": 3, "experiment_metadata": [ "sanitation" ], @@ -61,5 +61,31 @@ }, "model": "core.experiment", "pk": 3 + }, + { + "fields": { + "name":"sanitation.pollution", + "experiment_metadata": 3, + "creator": 4, + "type": "int", + "date_created": "2011-01-01 15:13:07", + "scope": "group", + "description": "The integer values for this parameter represent locations in a text corpus (i.e., single coordinates OK)" + }, + "model": "core.parameter", + "pk": 6 + }, + { + "fields": { + "name":"sanitation.collectedpollution", + "experiment_metadata": 3, + "creator": 4, + "type": "int", + "date_created": "2011-01-01 15:13:07", + "scope": "participant", + "description": "The integer values for this parameter are informal foreign keys to the sanitation.pollution location data value pks" + }, + "model": "core.parameter", + "pk": 7 } ] --- a/vcweb/sanitation/models.py Sat Jul 09 01:05:12 2011 -0700 +++ b/vcweb/sanitation/models.py Mon Jul 11 15:55:25 2011 -0700 @@ -1,21 +1,42 @@ -from django.db import models - +from vcweb.core.models import * import random -def pollutify(resource_string, pollution_amount, pollution_symbol, group=None): - resource_index = xrange(1,(len(resource_string) + 1)) - pollution_locations = sorted(random.sample(resource_index, pollution_amount)) -# pollution_parameter = Parameter.objects.get(name='sanitation.pollution') +def pollutify(experiment, pollution_amount, resource_string_length): + for group in experiment.group_set.all(): + resource_index = xrange(1,(resource_string_length + 1)) + pollution_locations = sorted(random.sample(resource_index, pollution_amount)) + pollution_parameter = Parameter.objects.get(name='sanitation.pollution') + round_data = group.current_round_data + for i, location in enumerate(pollution_locations): +# generate a GroupRoundDataValue for this location (this can be shortened) + # round_data.group_data_value_set.create(group=group, parameter=pollution_parameter, value=location) + grdv = group.data_value_set.create(round_data=round_data, parameter=pollution_parameter, value=location) + #grdv = GroupRoundDataValue.objects.create(group=group, round_data=round_data, parameter=pollution_parameter, value=location) + logger.debug("grdv is %s", grdv) + +def pollution_url_maker(pk, pollution_symbol): + pollution_url = "<a id='%d' class='pollution' href='#'>%s</a>" % (pk, pollution_symbol) + #pollution_url = '<a id='' href="#"> ' + pollution_symbol + ' </a>' + # use jQuery to bind a click handler to all DOM elements with class='pollution', + # look at jquery selector documentation + #$('.pollution').click(function() { + # ajax call here + # }); + # will probably need to use jQuery .delegate or .live to handle this properly + return pollution_url + +# returns a new string with pollution embedded in it +def get_pollution_string(group, resource_string, pollution_symbol="@"): resource_string_list = list(resource_string) - offset = len(pollution_symbol) - for i, location in enumerate(pollution_locations): -# generate a GroupRoundDataValue for this location (this can be shortened) -# grdv = GroupRoundDataValue.objects.create(group=group, round_data=group.current_round_data, parameter=pollution_parameter, value=location) -# logger.debug("grdv is %s", grdv) -# FIXME: since we're inserting more than one character we need to be careful not to insert into a location where +# XXX: since we're inserting more than one character we need to be careful not to insert into a location where # we appended text.. - resource_string_list.insert(location + (i * offset), pollution_symbol) + for i, grdv in enumerate(GroupRoundDataValue.objects.filter(group=group, round_data=group.current_round_data, is_active=True)): + pollution_url = pollution_url_maker(grdv.pk, pollution_symbol) + offset = len(pollution_url) + offset_location = grdv.value + (i * offset) + resource_string_list.insert(offset_location, pollution_url) return ''.join(resource_string_list) + --- a/vcweb/sanitation/views.py Sat Jul 09 01:05:12 2011 -0700 +++ b/vcweb/sanitation/views.py Mon Jul 11 15:55:25 2011 -0700 @@ -1,5 +1,8 @@ # importing external methods and classes +#from vcweb.core.models import Experiment from vcweb.core.models import Experiment +from vcweb.core.models import ParticipantExperimentRelationship +from vcweb.sanitation.models import pollutify from django.shortcuts import render_to_response, redirect from django.template.context import RequestContext import logging @@ -7,10 +10,6 @@ #FIXME come from database(user) treatment = "In-group" -current_location = "consent" - -#FIXME comes from type of experiment -sequence = ["consent","survey","instructions","quiz","play"] #FIXME Globals... comes from somewhere logger = logging.getLogger(__name__) @@ -23,32 +22,12 @@ #FIXME rename object to something like "experimental settings" #FIXME replace 'one week' with a calculation of duration consent = [venue, symbol,'one week', growth_rate] -resource = "Sanitation is vital for health: Readers of a prestigious medical journal were recently asked to name the greatest medical advance in the last century and a half. The result: better sanitation. In nineteenth-century Europe and North America, diarrhoea, cholera, and typhoid spread through poor sanitation was the leading cause of childhood illness and death; today, such deaths are rare in these regions. In developing countries, however, they are all too common, and recent research suggests that poor sanitation and hygiene are either the chief or the underlying cause in over half of the annual 10 million child deaths. Compelling, evidence-based analysis shows that hygiene and sanitation are among the most cost-effective public health interventions to reduce childhood mortality. Access to a toilet alone can reduce child diarrhoeal deaths by over 30 percent, and hand-washing by more than 40 percent." +resource_string = "Sanitation is vital for health: Readers of a prestigious medical journal were recently asked to name the greatest medical advance in the last century and a half. The result: better sanitation. In nineteenth-century Europe and North America, diarrhoea, cholera, and typhoid spread through poor sanitation was the leading cause of childhood illness and death; today, such deaths are rare in these regions. In developing countries, however, they are all too common, and recent research suggests that poor sanitation and hygiene are either the chief or the underlying cause in over half of the annual 10 million child deaths. Compelling, evidence-based analysis shows that hygiene and sanitation are among the most cost-effective public health interventions to reduce childhood mortality. Access to a toilet alone can reduce child diarrhoeal deaths by over 30 percent, and hand-washing by more than 40 percent." -#FIXME mode to models, make method "current_game_state" that returns game_state -resource_index = range(1,(len(resource) + 1)) pollution_amount = random.randint(1,200) -pollution = random.sample(resource_index, pollution_amount) -game_state = "" -for i, char in enumerate(resource): - if i in pollution: -#FIXME turn pollution symbol into - symbol_url = str("" + symbol + "") - game_state = game_state + symbol_url - game_state = game_state + char -#FIXME list of index out of range - -def next_url(absolute_url,current_location,sequence): - a = sequence.index(current_location) - a = a + 1 - if a == len(sequence): - a = 0 - next_page = sequence[a] - else: - next_page = sequence[a] - logger.debug("next_page: %s is valid", next_page) - return "/%s/%s" % (absolute_url, next_page) +pollution_symbol = '@' +#game_state = pollutify(resource_string, pollution_amount, pollution_symbol) #FIXME propose that quiz has a limit of 10 questions #FIXME Find a better place to put the declaration of questions quiz/survey @@ -98,11 +77,11 @@ context_instance=RequestContext(request)) #Participant - #Pages in experiment sequence + def consent(request, experiment): logger.debug("handling consent") consent = ['Introduction to Global Health Class', symbol,'one week', growth_rate] - next_url = "instructions" + next_url = "consent" return render_to_response('sanitation/consent.html', locals(), context_instance=RequestContext(request)) def survey(request, experiment): @@ -129,9 +108,16 @@ participant = request.user.participant experiment = Experiment.objects.get(pk=experiment_id) -# absolute_url = experiment.namespace -# n_url = next_url(absolute_url,current_location,sequence) + participantrelationship = ParticipantExperimentRelationship.objects.get(id = participant.id) + current_location = participantrelationship.current_location.lower() + if request.method == 'POST': + current_location = request.POST['next'] + participantrelationship.current_location = current_location + participantrelationship.save() + + + sequence = ["consent","survey","instructions","quiz","play"] if current_location in sequence: logger.debug("current location %s is valid", current_location) location_method = globals()[current_location] Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-09 08:05:26
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/53acd7144324/ changeset: 53acd7144324 user: alllee date: 2011-07-09 10:05:12 summary: setting content type appropriately for jsonp requests affected #: 1 file (59 bytes) --- a/vcweb/core/views.py Fri Jul 08 16:08:54 2011 -0700 +++ b/vcweb/core/views.py Sat Jul 09 01:05:12 2011 -0700 @@ -7,8 +7,8 @@ from django.db.models.query import QuerySet from django.core.serializers import serialize from django.core.serializers.json import DjangoJSONEncoder -from django.http import HttpResponse -from django.shortcuts import render_to_response, redirect +from django.http import HttpResponse, Http404 +from django.shortcuts import render_to_response, redirect, get_object_or_404 from django.template.context import RequestContext from django.utils.decorators import method_decorator from django.utils.functional import curry @@ -46,11 +46,12 @@ def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." callback = self.request.GET.get('callback', '') + content_type = 'application/x-json' if is_valid_jsonp_callback_value(callback): content = '%s(%s)' % (callback, content) - logger.debug("returning json content %s", content) + content_type = 'text/javascript' return HttpResponse(content, - content_type='application/json', + content_type=content_type, **httpresponse_kwargs) def convert_context_to_json(self, context, context_key='object_list', **kwargs): @@ -100,7 +101,7 @@ commons_user = user.experimenter else: logger.error("Invalid user: %s", user) - return + raise Http404 logger.debug("%s authentication_token=%s", commons_user, authentication_token) commons_user.authentication_token = authentication_token commons_user.save() Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-08 23:09:06
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/25c452d64b69/ changeset: 25c452d64b69 user: alllee date: 2011-07-09 01:08:54 summary: fixing generic instructions view affected #: 2 files (352 bytes) --- a/vcweb/core/urls.py Fri Jul 08 13:09:42 2011 -0700 +++ b/vcweb/core/urls.py Fri Jul 08 16:08:54 2011 -0700 @@ -11,7 +11,6 @@ url(r'^accounts/logout/$', login_required(LogoutView.as_view()), name='logout'), url(r'^accounts/register/$', RegistrationView.as_view(), name='register'), url(r'^accounts/profile/$', 'account_profile', name='profile'), - url(r'^participate/(?P<pk>\d+)/instructions', 'instructions', name='instructions'), url(r'^participate/(?P<namespace>\w+)/instructions', 'instructions', name='namespace_instructions'), url(r'^experiment/(?P<pk>\d+)/monitor$', MonitorExperimentView.as_view(), name='monitor_experiment'), url(r'^experiment/(?P<pk>\d+)/register-email-list$', RegisterEmailListView.as_view(), name='register_email_list'), --- a/vcweb/core/views.py Fri Jul 08 13:09:42 2011 -0700 +++ b/vcweb/core/views.py Fri Jul 08 16:08:54 2011 -0700 @@ -179,18 +179,13 @@ return super(ParticipantMixin, self).dispatch(*args, **kwargs) @login_required -def instructions(request, pk=None, namespace=None): - if pk: - experiment = Experiment.objects.get(pk=pk) - elif namespace: - experiment = Experiment.objects.get(experiment_metadata__namespace=namespace) - - if not experiment: - logger.warning("Tried to request instructions for id %s or namespace %s", pk, namespace) +def instructions(request, namespace=None): + if namespace is not None: + return render_to_response('%s/instructions.html' % namespace, + context_instance=RequestContext(request)) + else: return redirect('home') - return render_to_response(experiment.get_template_path('instructions.html'), locals(), context_instance=RequestContext(request)) - """ experimenter views FIXME: add has_perms authorization to ensure that only experimenters can access Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-08 20:09:45
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/2c1347137558/ changeset: 2c1347137558 user: alllee date: 2011-07-08 22:09:42 summary: fixing incorrect related field reference affected #: 1 file (14 bytes) --- a/vcweb/forestry/views.py Thu Jul 07 19:53:13 2011 -0700 +++ b/vcweb/forestry/views.py Fri Jul 08 13:09:42 2011 -0700 @@ -73,7 +73,7 @@ logger.debug("generating participant history for %s, current round %s", participant_group_relationship.participant, round_data) data = ParticipantRoundData() -# FIXME: this kind of binding is a bit laborious and error-prone, refactor if possible +# FIXME: laborious and error-prone data binding, refactor if possible data.round_configuration = round_data.round_configuration data.individual_harvest = get_harvest_decision(participant_group_relationship, round_data=round_data) data.group_harvest = get_group_harvest(group, round_data=round_data) @@ -183,7 +183,7 @@ def chat(request, experiment, participant): participant_group_rel = participant.get_participant_group_relationship(experiment) participant_experiment_relationship = participant.get_participant_experiment_relationship(experiment) - chat_messages = experiment.current_round_data.chat_messages.filter(participant_group_relationship__group=participant_group_rel.group) + chat_messages = experiment.current_round_data.chat_message_set.filter(participant_group_relationship__group=participant_group_rel.group) return render_to_response(experiment.current_round_template, { 'participant_group_relationship': participant_group_rel, 'participant_experiment_relationship': participant_experiment_relationship, Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <iss...@bi...> - 2011-07-08 18:53:26
|
--- you can reply above this line --- New issue 28: refactor views https://bitbucket.org/virtualcommons/vcweb/issue/28/refactor-views A Lee / alllee on Fri, 8 Jul 2011 20:53:20 +0200: Description: Replace pk retrieval with get_object_or_404 and forestry views with CBV. Responsible: alllee -- This is an issue notification from bitbucket.org. You are receiving this either because you are the owner of the issue, or you are following the issue. |
From: Bitbucket <com...@bi...> - 2011-07-08 02:53:11
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/7b1b977cea5f/ changeset: 7b1b977cea5f user: alllee date: 2011-07-08 04:53:13 summary: minor tweaks to display availability, need to add to json as well affected #: 2 files (304 bytes) --- a/vcweb/lighterprints/models.py Thu Jul 07 19:39:19 2011 -0700 +++ b/vcweb/lighterprints/models.py Thu Jul 07 19:53:13 2011 -0700 @@ -38,7 +38,7 @@ ordering = ['level', 'name'] class ActivityAvailability(models.Model): - activity = models.ForeignKey(Activity) + activity = models.ForeignKey(Activity, related_name='availability_set') available_start_time = models.TimeField(null=True, blank=True) available_end_time = models.TimeField(null=True, blank=True) --- a/vcweb/lighterprints/templates/lighterprints/activity_list.html Thu Jul 07 19:39:19 2011 -0700 +++ b/vcweb/lighterprints/templates/lighterprints/activity_list.html Thu Jul 07 19:53:13 2011 -0700 @@ -7,7 +7,12 @@ <h3>Level {{level}} Activities</h3><ul> {% for activity in activities %} - <li>{{ activity }}</li> + <li>{{ activity }} <img src='{{activity.icon_url}}' alt='activity icon' /> + <br/> + {% for activity_availability in activity.availability_set.all %} + ({{ activity_availability.available_start_time|time }} - {{ activity_availability.available_end_time|time }}) + {% endfor %} + </li> {% endfor %} </ul> {% endfor %} Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-08 02:39:19
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/a563c4658eaa/ changeset: a563c4658eaa user: alllee date: 2011-07-08 04:39:19 summary: updated full activity list with availability affected #: 1 file (9.7 KB) --- a/vcweb/lighterprints/fixtures/initial_data.json Thu Jul 07 19:21:11 2011 -0700 +++ b/vcweb/lighterprints/fixtures/initial_data.json Thu Jul 07 19:39:19 2011 -0700 @@ -8,8 +8,11 @@ "available_all_day": false, "url": "http://www.savecarbon.org/activity_form/twodegrees", "level": 1, + "group_activity": false, "summary": "Heating or cooling buildings less saves energy", - "savings": "5.5", + "savings": "5.50", + "cooldown": 1, + "icon": "", "name": "adjust-thermostat" } }, @@ -22,8 +25,11 @@ "available_all_day": true, "url": "http://www.huffingtonpost.com/bill-chameides/carbon-savings-at-home_b_113551.html", "level": 1, + "group_activity": false, "summary": "Less energy for transport when only locally grown food is consumed", - "savings": "2", + "savings": "2.00", + "cooldown": 1, + "icon": "", "name": "eat-local-lunch" } }, @@ -36,8 +42,11 @@ "available_all_day": true, "url": "http://www.epa.gov/climatechange/kids/calc/index.html", "level": 1, + "group_activity": false, "summary": "Your computer consumes less energy when it's asleep or turned off", "savings": "0.98", + "cooldown": 1, + "icon": "lighterprints/activity-icons/compsleep.bmp", "name": "enable-computer-sleep" } }, @@ -50,8 +59,11 @@ "available_all_day": true, "url": "http://www.epa.gov/climatechange/kids/calc/index.html", "level": 1, + "group_activity": false, "summary": "Recycling processes used materials into new products to prevent waste of potentially useful materials.", "savings": "0.31", + "cooldown": 1, + "icon": "", "name": "recycle" } }, @@ -64,9 +76,245 @@ "available_all_day": false, "url": "http://www.epa.gov/climatechange/kids/calc/index.html", "level": 1, + "group_activity": false, "summary": "Using mass transit, bicycle commuting, or carpooling is more efficient than traveling alone in your car.", "savings": "2.85", + "cooldown": 1, + "icon": "", "name": "share-your-ride" } + }, + { + "pk": 10, + "model": "lighterprints.activity", + "fields": { + "display_name": "Bike or take public transportation when you go out", + "description": "We assume a 22.4 miles per gallon car and a 4 mile trip length. CO2 emissions are 19.53 pounds per gallon and 1.5 pound per gallon of non-CO2 CO2 equivalent emissions. This means 0.94 pounds per mile. ", + "available_all_day": false, + "url": "http://www.epa.gov/climatechange/kids/calc/index.html", + "level": 2, + "group_activity": false, + "summary": "Reduce fossil fuel consumption and emissions by not driving a car", + "savings": "7.52", + "cooldown": 1, + "icon": "lighterprints/activity-icons/biketo.bmp", + "name": "bike-public-transport" + } + }, + { + "pk": 6, + "model": "lighterprints.activity", + "fields": { + "display_name": "Turn water off while brushing your teeth", + "description": "0.5 kWh per person per day, assuming four minutes a day (enough to account for brushing teeth twice daily) and typical energy use for water supply, treatment, and heating. With 1.52 CO2 per kWh this leads to a savings of 0.76 pound of CO2 a day.", + "available_all_day": false, + "url": "http://www.epa.gov/climatechange/kids/calc/index.html", + "level": 2, + "group_activity": false, + "summary": "Don't leave the water running while you're brushing your teeth", + "savings": "0.76", + "cooldown": 1, + "icon": "lighterprints/activity-icons/toothbrush.bmp", + "name": "brushing-your-teeth" + } + }, + { + "pk": 7, + "model": "lighterprints.activity", + "fields": { + "display_name": "Turn off your computer at night", + "description": "The average computer uses about 120 Watts (75 Watts for the screen and 45 Watts for the CPU) whether you're using it or not.\r\nOne computer left on 24 hours a day will lead to cost 1,500 pounds of CO2 into the atmosphere.", + "available_all_day": false, + "url": "http://sustainability.tufts.edu/", + "level": 2, + "group_activity": false, + "summary": "Save energy and turn off your computer when it's not needed.", + "savings": "1.37", + "cooldown": 1, + "icon": "lighterprints/activity-icons/compsleep_1.bmp", + "name": "computer-off" + } + }, + { + "pk": 9, + "model": "lighterprints.activity", + "fields": { + "display_name": "Replace beef with poultry", + "description": "Replacing the protein you get from beef with poultry can save you 1,555 pounds of CO2 emissions annually. Per day this switch leads to a 4.26 pounds of CO2 savings.", + "available_all_day": false, + "url": "http://www.simplesteps.org/food/shopping-wise/co2-smackdown-step-6-trimming-out-beef-and-pork", + "level": 2, + "group_activity": false, + "summary": "Beef production is very energy intensive", + "savings": "4.26", + "cooldown": 1, + "icon": "lighterprints/activity-icons/nobeef.bmp", + "name": "no-beef" + } + }, + { + "pk": 8, + "model": "lighterprints.activity", + "fields": { + "display_name": "Recycle paper", + "description": "Average number of pounds of CO2 equivalent per person per year that could be saved by recycling magazines (14.86), newspaper (89.76) and junk mail (100). This is 0.56 pound per day.", + "available_all_day": false, + "url": "http://www.epa.gov/climatechange/kids/calc/index.html", + "level": 2, + "group_activity": false, + "summary": "Saving paper resources and production by recycling", + "savings": "0.56", + "cooldown": 1, + "icon": "lighterprints/activity-icons/recycle.bmp", + "name": "recycle-paper" + } + }, + { + "pk": 14, + "model": "lighterprints.activity", + "fields": { + "display_name": "Air dry your clothes", + "description": "Drying your clothes saves 723 pounds of CO2 every year. This is 1.98 pounds per day.", + "available_all_day": false, + "url": "http://www.simplesteps.org/tools/house-savings-calculator#laundry", + "level": 3, + "group_activity": false, + "summary": "Air drying your clothes saves gas or electricity", + "savings": "1.98", + "cooldown": 1, + "icon": "lighterprints/activity-icons/airdry.bmp", + "name": "air-dry-clothes" + } + }, + { + "pk": 13, + "model": "lighterprints.activity", + "fields": { + "display_name": "Eat a green lunch", + "description": "You can save 500 pounds of CO2 a year by reducing waste at lunch time. This means packing your lunch in a reusable container, using reusable/washable utensils, and don\u2019t use paper napkins.", + "available_all_day": false, + "url": "http://www.savecarbon.org/activity_form/lunches", + "level": 3, + "group_activity": false, + "summary": "Reduce the amount of waste you produce at lunch time.", + "savings": "1.37", + "cooldown": 1, + "icon": "lighterprints/activity-icons/organic_1.bmp", + "name": "green-lunch" + } + }, + { + "pk": 11, + "model": "lighterprints.activity", + "fields": { + "display_name": "Turn off unnecessary lights", + "description": "Per bulb per hour: [60 watts / 1000 watts/kWh] *1.52 pounds of CO2 per kWh = 0.09 pound of CO2 per bulb per hour. Assume turning off 5 bulbs for 5 hours. This leads to 2.28 pounds of CO2 per day.", + "available_all_day": false, + "url": "http://www.epa.gov/climatechange/kids/calc/index.html", + "level": 3, + "group_activity": false, + "summary": "Turning lights off in areas that don't need it saves energy.", + "savings": "2.28", + "cooldown": 1, + "icon": "lighterprints/activity-icons/lightsoff.bmp", + "name": "lights-off" + } + }, + { + "pk": 12, + "model": "lighterprints.activity", + "fields": { + "display_name": "Become a vegan for a day", + "description": "A plant-based diet saves 1608 pound of CO2 per year compared to an average diet.", + "available_all_day": false, + "url": "http://www.simplesteps.org/tools/house-savings-calculator#diet", + "level": 3, + "group_activity": false, + "summary": "Raising animals for meat is resource intensive", + "savings": "4.41", + "cooldown": 1, + "icon": "lighterprints/activity-icons/organic.bmp", + "name": "vegan-for-a-day" + } + }, + { + "pk": 15, + "model": "lighterprints.activity", + "fields": { + "display_name": "Wash your clothes with cold water", + "description": "You can save 400 pound of CO2 a year by washing all your clothes with cold water.", + "available_all_day": false, + "url": "http://www.savecarbon.org/activity_form/washcold", + "level": 3, + "group_activity": false, + "summary": "Save energy by not heating water", + "savings": "1.10", + "cooldown": 1, + "icon": "lighterprints/activity-icons/airdry_1.bmp", + "name": "wash-cold-water" + } + }, + { + "pk": 4, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "06:00:00", + "available_end_time": "08:00:00", + "activity": 4 + } + }, + { + "pk": 1, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "12:00:00", + "available_end_time": "14:00:00", + "activity": 2 + } + }, + { + "pk": 2, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "08:00:00", + "available_end_time": "10:00:00", + "activity": 10 + } + }, + { + "pk": 3, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "16:00:00", + "available_end_time": "18:00:00", + "activity": 10 + } + }, + { + "pk": 7, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "18:00:00", + "available_end_time": "23:00:00", + "activity": 10 + } + }, + { + "pk": 5, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "07:00:00", + "available_end_time": "09:00:00", + "activity": 6 + } + }, + { + "pk": 6, + "model": "lighterprints.activityavailability", + "fields": { + "available_start_time": "21:00:00", + "available_end_time": "23:59:59", + "activity": 6 + } } ] \ No newline at end of file Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-08 02:21:09
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/bd3fb22a1d74/ changeset: bd3fb22a1d74 user: alllee date: 2011-07-08 04:21:11 summary: adding ordering and unicode to ActivityAvailability affected #: 1 file (202 bytes) --- a/vcweb/lighterprints/models.py Thu Jul 07 13:50:26 2011 -0700 +++ b/vcweb/lighterprints/models.py Thu Jul 07 19:21:11 2011 -0700 @@ -42,6 +42,12 @@ available_start_time = models.TimeField(null=True, blank=True) available_end_time = models.TimeField(null=True, blank=True) + def __unicode__(self): + return u'%s (%s - %s)' % (self.activity, self.available_start_time, self.available_end_time) + + class Meta: + ordering = ['activity', 'available_start_time'] + @simplecache def get_lighterprints_experiment_metadata(): return ExperimentMetadata.objects.get(namespace='lighterprints') Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-07 20:50:25
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/9254eb564480/ changeset: 9254eb564480 user: alllee date: 2011-07-07 22:50:26 summary: fixes issue 27 and adding icon_url to json output affected #: 2 files (45 bytes) --- a/vcweb/lighterprints/models.py Thu Jul 07 13:46:26 2011 -0700 +++ b/vcweb/lighterprints/models.py Thu Jul 07 13:50:26 2011 -0700 @@ -29,7 +29,7 @@ @property def icon_url(self): - return self.icon.url + return self.icon.url if self.icon else "" def __unicode__(self): return u'%s (+%s)' % (self.label, self.savings) --- a/vcweb/lighterprints/views.py Thu Jul 07 13:46:26 2011 -0700 +++ b/vcweb/lighterprints/views.py Thu Jul 07 13:50:26 2011 -0700 @@ -23,8 +23,8 @@ activity_by_level[activity.level].append(activity) #activity_as_dict = collections.OrderedDict() activity_as_dict = {} - for attr_name in ('pk', 'name', 'summary', 'display_name', 'description', 'savings', 'url', 'available_all_day', 'level', 'group_activity', 'icon_url'): - activity_as_dict[attr_name] = getattr(activity, attr_name) + for attr_name in ('pk', 'name', 'summary', 'display_name', 'description', 'savings', 'url', 'available_all_day', 'level', 'group_activity', 'icon_url', 'time_remaining'): + activity_as_dict[attr_name] = getattr(activity, attr_name, None) flattened_activities.append(activity_as_dict) context['activity_by_level'] = dict(activity_by_level) Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |
From: Bitbucket <com...@bi...> - 2011-07-07 20:48:17
|
1 new changeset in vcweb: http://bitbucket.org/virtualcommons/vcweb/changeset/7e50567f77ca/ changeset: 7e50567f77ca user: alllee date: 2011-07-07 22:46:26 summary: adding icon_url to JSON output for all available activities affected #: 1 file (0 bytes) --- a/vcweb/lighterprints/views.py Thu Jul 07 13:40:52 2011 -0700 +++ b/vcweb/lighterprints/views.py Thu Jul 07 13:46:26 2011 -0700 @@ -23,7 +23,7 @@ activity_by_level[activity.level].append(activity) #activity_as_dict = collections.OrderedDict() activity_as_dict = {} - for attr_name in ('pk', 'name', 'summary', 'display_name', 'description', 'savings', 'url', 'available_all_day', 'level', 'group_activity', 'cooldown'): + for attr_name in ('pk', 'name', 'summary', 'display_name', 'description', 'savings', 'url', 'available_all_day', 'level', 'group_activity', 'icon_url'): activity_as_dict[attr_name] = getattr(activity, attr_name) flattened_activities.append(activity_as_dict) Repository URL: https://bitbucket.org/virtualcommons/vcweb/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email. |