Example #1
0
File: files.py Project: nirgal/ngw
 def form_valid(self, form):
     cg = self.contactgroup
     request = self.request
     if not cg.userperms & perms.WRITE_FILES:
         raise PermissionDenied
     upfile = request.FILES['file_to_upload']
     # name has already been sanitized by UploadedFile._set_name
     path = self.kwargs['path']
     fullfilename = cg.get_fullfilename(os.path.join(path, upfile.name))
     destination = None
     try:  # We're not using "with" because we want to show errors
         destination = open(force_str(fullfilename), 'wb')
         for chunk in upfile.chunks():
             destination.write(chunk)
         messages.add_message(
             request, messages.SUCCESS,
             _('File {} has been uploaded successfully.')
             .format(upfile.name))
     except IOError as err:
         messages.add_message(
             request, messages.ERROR,
             _('Could not upload file {filename}: {error}').format(
                 filename=upfile.name,
                 error=err))
     finally:
         if destination:
             destination.close()
     return self.get(self.request)
Example #2
0
    def get_data(self):
        # Gather our instances
        try:
            instances = api.server_list(self.request)
        except:
            instances = []
            exceptions.handle(self.request,
                              _('Unable to retrieve instances.'))
        # Gather our flavors and correlate our instances to them
        if instances:
            try:
                flavors = api.flavor_list(self.request)
            except:
                flavors = []
                exceptions.handle(self.request, ignore=True)

            full_flavors = SortedDict([(str(flavor.id), flavor)
                                        for flavor in flavors])
            # Loop through instances to get flavor info.
            for instance in instances:
                try:
                    flavor_id = instance.flavor["id"]
                    if flavor_id in full_flavors:
                        instance.full_flavor = full_flavors[flavor_id]
                    else:
                        # If the flavor_id is not in full_flavors list,
                        # get it via nova api.
                        instance.full_flavor = api.flavor_get(self.request,
                                                              flavor_id)
                except:
                    msg = _('Unable to retrieve instance size information.')
                    exceptions.handle(self.request, msg)
        return instances
Example #3
0
    def clean(self):
        self.handle_deleted_and_added_contributions()

        super().clean()

        found_contributor = set()
        count_responsible = 0
        for form in self.forms:
            if not form.cleaned_data or form.cleaned_data.get('DELETE'):
                continue
            contributor = form.cleaned_data.get('contributor')
            if contributor is None:
                raise forms.ValidationError(_('Please select the name of each added contributor. Remove empty rows if necessary.'))
            if contributor and contributor in found_contributor:
                raise forms.ValidationError(_('Duplicate contributor found. Each contributor should only be used once.'))
            elif contributor:
                found_contributor.add(contributor)

            if form.cleaned_data.get('responsibility') == 'RESPONSIBLE':
                count_responsible += 1

        if count_responsible < 1:
            raise forms.ValidationError(_('No responsible contributor found. Each course must have exactly one responsible contributor.'))
        elif count_responsible > 1:
            raise forms.ValidationError(_('Too many responsible contributors found. Each course must have exactly one responsible contributor.'))
Example #4
0
def dump_module_extensions(course, unit):
    """
    Dumps data about students with due date extensions for a particular module,
    specified by 'url', in a particular course.
    """
    data = []
    header = [_("Username"), _("Full Name"), _("Extended Due Date")]
    query = StudentFieldOverride.objects.filter(
        course_id=course.id,
        location=unit.location,
        field='due')
    for override in query:
        due = DATE_FIELD.from_json(json.loads(override.value))
        due = due.strftime("%Y-%m-%d %H:%M")
        fullname = override.student.profile.name
        data.append(dict(zip(
            header,
            (override.student.username, fullname, due))))
    data.sort(key=lambda x: x[header[0]])
    return {
        "header": header,
        "title": _("Users with due date extensions for {0}").format(
            title_or_url(unit)),
        "data": data
    }
Example #5
0
 def handle(self, request, data):
     domain = api.keystone.get_default_domain(self.request)
     try:
         LOG.info('Creating user with name "%s"' % data['name'])
         if "email" in data:
             data['email'] = data['email'] or None
         new_user = api.keystone.user_create(request,
                                             name=data['name'],
                                             email=data['email'],
                                             password=data['password'],
                                             project=data['project'],
                                             enabled=True,
                                             domain=domain.id)
         messages.success(request,
                          _('User "%s" was successfully created.')
                          % data['name'])
         if data['project'] and data['role_id']:
             roles = api.keystone.roles_for_user(request,
                                     new_user.id,
                                     data['project']) or []
             assigned = [role for role in roles if role.id == str(
                 data['role_id'])]
             if not assigned:
                 try:
                     api.keystone.add_tenant_user_role(request,
                                                     data['project'],
                                                     new_user.id,
                                                     data['role_id'])
                 except Exception:
                     exceptions.handle(request,
                                     _('Unable to add user '
                                         'to primary project.'))
         return new_user
     except Exception:
         exceptions.handle(request, _('Unable to create user.'))
Example #6
0
 def clean_shipping_absolute(self):
     if not self.value:
         raise ValidationError(_("A discount value is required"))
     if self.range:
         raise ValidationError(_("No range should be selected as this benefit does not " "apply to products"))
     if self.max_affected_items:
         raise ValidationError(_("Shipping discounts don't require a 'max affected items' " "attribute"))
Example #7
0
def merge_path(request):
    """
    Path merging view
    """
    response = {}

    if request.method == 'POST':
        try:
            ids_path_merge = request.POST.getlist('path[]')

            if len(ids_path_merge) == 2:
                path_a = Path.objects.get(pk=ids_path_merge[0])
                path_b = Path.objects.get(pk=ids_path_merge[1])
                if not path_a.same_structure(request.user) or not path_b.same_structure(request.user):
                    response = {'error': _(u"You don't have the right to change these paths")}

                elif path_a.merge_path(path_b):
                    response = {'success': _(u"Paths merged successfully")}
                    messages.success(request, _(u"Paths merged successfully"))

                else:
                    response = {'error': _(u"No matching points to merge paths found")}

            else:
                raise

        except Exception as exc:
            response = {'error': exc, }

    return HttpResponse(json.dumps(response), mimetype="application/json")
Example #8
0
    def confirm(self, ok_func, *msgs):
        """Execute the specified callable `ok_func` after the user has
        confirmed the specified message.
        
        The confirmation message may be specified as a series of
        positional arguments which will be concatenated to a single
        prompt.

        The callable will be called with a single positional argument
        which will be the action request that confirmed the
        message. In a web context this will be another object than
        this one.

        In a non-interactive environment the `ok_func` function is
        called directly (i.e. we don't ask any confirmation and act as
        confirmation had been given).

        """
        cb = self.add_callback(*msgs)

        def noop(ar):
            return ar.success(_("Aborted"))
        cb.add_choice('yes', ok_func, _("Yes"))
        cb.add_choice('no', noop, _("No"))
        self.set_callback(cb)

        if not self.renderer.is_interactive:
            if self._confirm_answer:
                ok_func(self)
Example #9
0
def select_variant_from_properties(request):
    """
    This is called via an ajax call if the combination of properties are
    changed.
    """
    product_id = request.POST.get("product_id")

    try:
        variant = Product.objects.get(pk=product_id)
    except Product.DoesNotExist:
        return HttpResponse("")
    else:
        product = variant.parent

    options = lfs_utils.parse_properties(request)
    variant = product.get_variant(options)

    if variant is None:
        msg = _(u"The choosen combination of properties is not deliverable.")
        variant = product.get_default_variant()
    else:
        msg = _(u"The product has been changed according to your selection.")

    result = simplejson.dumps({
        "product": product_inline(request, variant),
        "message": msg,
    }, cls=LazyEncoder)

    return HttpResponse(result, mimetype='application/json')
Example #10
0
 def get_human_hour(self):
     if self.scrub_hour == '*':
         return _(u'Every hour')
     elif self.scrub_hour.startswith('*/'):
         return _(u'Every {0} hour(s)').format(self.scrub_hour.split('*/')[1])
     else:
         return self.scrub_hour
Example #11
0
 def get_human_daymonth(self):
     if self.scrub_daymonth == '*':
         return _(u'Everyday')
     elif self.scrub_daymonth.startswith('*/'):
         return _(u'Every {0} days').format(self.scrub_daymonth.split('*/')[1])
     else:
         return self.scrub_daymonth
Example #12
0
 def get_human_minute(self):
     if self.scrub_minute == '*':
         return _(u'Every minute')
     elif self.scrub_minute.startswith('*/'):
         return _(u'Every {0} minute(s)').format(self.scrub_minute.split('*/')[1])
     else:
         return self.scrub_minute
Example #13
0
    def __init__(self, path, raw_file_url=None, username=None, password=None,
                 local_site_name=None):
        if not is_exe_in_path('git'):
            # This is technically not the right kind of error, but it's the
            # pattern we use with all the other tools.
            raise ImportError

        self.path = self._normalize_git_url(path)
        self.raw_file_url = raw_file_url
        self.username = username
        self.password = password
        self.local_site_name = local_site_name
        self.git_dir = None

        url_parts = urlparse.urlparse(self.path)

        if url_parts[0] == 'file':
            self.git_dir = url_parts[2]

            p = self._run_git(['--git-dir=%s' % self.git_dir, 'config',
                               'core.repositoryformatversion'])
            failure = p.wait()

            if failure:
                # See if we have a permissions error
                if not os.access(self.git_dir, os.R_OK):
                    raise SCMError(_("Permission denied accessing the local "
                                     "Git repository '%s'") % self.git_dir)
                else:
                    raise SCMError(_('Unable to retrieve information from '
                                     'local Git repository'))
Example #14
0
def video_handler(request, video, format="mp4", prev=None, next=None):

    if not video["available"]:
        if request.is_admin:
            # TODO(bcipolli): add a link, with querystring args that auto-checks this video in the topic tree
            messages.warning(request, _("This video was not found! You can download it by going to the Update page."))
        elif request.is_logged_in:
            messages.warning(request, _("This video was not found! Please contact your teacher or an admin to have it downloaded."))
        elif not request.is_logged_in:
            messages.warning(request, _("This video was not found! You must login as an admin/teacher to download the video."))

    # Fallback mechanism
    available_urls = dict([(lang, avail) for lang, avail in video["availability"].iteritems() if avail["on_disk"]])
    if video["available"] and not available_urls:
        vid_lang = "en"
        messages.success(request, "Got video content from %s" % video["availability"]["en"]["stream"])
    else:
        vid_lang = select_best_available_language(request.language, available_codes=available_urls.keys())


    context = {
        "video": video,
        "title": video["title"],
        "selected_language": vid_lang,
        "video_urls": video["availability"].get(vid_lang),
        "subtitle_urls": video["availability"].get(vid_lang, {}).get("subtitles"),
        "prev": prev,
        "next": next,
        "backup_vids_available": bool(settings.BACKUP_VIDEO_SOURCE),
        "use_mplayer": settings.USE_MPLAYER and is_loopback_connection(request),
    }
    return context
Example #15
0
    def get_visibility_errors(self, customer):
        if self.product.deleted:
            yield ValidationError(_('This product has been deleted.'), code="product_deleted")

        if customer and customer.is_all_seeing:  # None of the further conditions matter for omniscient customers.
            return

        if not self.visible:
            yield ValidationError(_('This product is not visible.'), code="product_not_visible")

        is_logged_in = (bool(customer) and not customer.is_anonymous)

        if not is_logged_in and self.visibility_limit != ProductVisibility.VISIBLE_TO_ALL:
            yield ValidationError(
                _('The Product is invisible to users not logged in.'),
                code="product_not_visible_to_anonymous")

        if is_logged_in and self.visibility_limit == ProductVisibility.VISIBLE_TO_GROUPS:
            # TODO: Optimization
            user_groups = set(customer.groups.all().values_list("pk", flat=True))
            my_groups = set(self.visibility_groups.values_list("pk", flat=True))
            if not bool(user_groups & my_groups):
                yield ValidationError(
                    _('This product is not visible to your group.'),
                    code="product_not_visible_to_group"
                )

        for receiver, response in get_visibility_errors.send(ShopProduct, shop_product=self, customer=customer):
            for error in response:
                yield error
Example #16
0
    def __init__(self, *args, **kwargs):
        from servo.lib.utils import empty
        super(GsxRepairForm, self).__init__(*args, **kwargs)
        repair = self.instance
        techs = User.techies.filter(location=repair.order.location)
        c = [(u.tech_id, u.get_full_name()) for u in techs]
        c.insert(0, ('', '-------------------',))
        self.fields['tech_id'] = forms.ChoiceField(choices=c,
                                                   required=False,
                                                   label=_('Technician'))
        self.fields['parts'].initial = repair.order.get_parts()

        if repair.can_mark_complete is False:
            del(self.fields['mark_complete'])
            del(self.fields['replacement_sn'])

        choices = Template.templates()
        for f in ('notes', 'symptom', 'diagnosis',):
            self.fields[f].widget = AutocompleteTextarea(choices=choices)
        
        symptom_codes = self.instance.get_symptom_code_choices()
        self.fields['symptom_code'] = forms.ChoiceField(choices=symptom_codes,
                                                        label=_('Symptom group'))
        
        if empty(self.instance.symptom_code):
            # default to the first choice
            self.instance.symptom_code = symptom_codes[0][0]

        issue_codes = self.instance.get_issue_code_choices()
        self.fields['issue_code'] = forms.ChoiceField(choices=issue_codes,
                                                      label=_('Issue code'))
Example #17
0
 def clean_multibuy(self):
     if not self.range:
         raise ValidationError(_("Multibuy benefits require a product range"))
     if self.value:
         raise ValidationError(_("Multibuy benefits don't require a value"))
     if self.max_affected_items:
         raise ValidationError(_("Multibuy benefits don't require a 'max affected items' " "attribute"))
Example #18
0
 def object_action(self, form, instance):
     try:
         if instance.is_superuser or instance.is_staff:
             messages.error(
                 self.request,
                 _(
                     'Super user and staff user password '
                     'reseting is not allowed, use the admin '
                     'interface for these cases.'
                 )
             )
         else:
             instance.set_password(form.cleaned_data['new_password_1'])
             instance.save()
             messages.success(
                 self.request, _(
                     'Successfull password reset for user: %s.'
                 ) % instance
             )
     except Exception as exception:
         messages.error(
             self.request, _(
                 'Error reseting password for user "%(user)s": %(error)s'
             ) % {
                 'user': instance, 'error': exception
             }
         )
Example #19
0
 def clean_shipping_percentage(self):
     if self.value > 100:
         raise ValidationError(_("Percentage discount cannot be greater than 100"))
     if self.range:
         raise ValidationError(_("No range should be selected as this benefit does not " "apply to products"))
     if self.max_affected_items:
         raise ValidationError(_("Shipping discounts don't require a 'max affected items' " "attribute"))
 def __init__(self, *args, **kwargs):
     super(SummaryField, self).__init__(*args, **kwargs)
     self.required = False
     self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
     self.max_length = 300
     self.label  = _('update summary:')
     self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
Example #21
0
File: api.py Project: heshunwq/hue
def export_result(request):
  response = {'status': -1, 'message': _('Exporting result failed.')}

  # Passed by check_document_access_permission but unused by APIs
  notebook = json.loads(request.POST.get('notebook', '{}'))
  snippet = json.loads(request.POST.get('snippet', '{}'))
  data_format = json.loads(request.POST.get('format', 'hdfs-file'))
  destination = json.loads(request.POST.get('destination', ''))
  overwrite = json.loads(request.POST.get('overwrite', False))

  api = get_api(request, snippet)

  if data_format == 'hdfs-file':
    if overwrite and request.fs.exists(destination):
      if request.fs.isfile(destination):
        request.fs.do_as_user(request.user.username, request.fs.rmtree, destination)
      else:
        raise ValidationError(_("The target path is a directory"))
    response['watch_url'] = api.export_data_as_hdfs_file(snippet, destination, overwrite)
    response['status'] = 0
  elif data_format == 'hive-table':
    notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
    response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=save_as_table&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
    response['status'] = 0
  elif data_format == 'hdfs-directory':
    notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
    response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=insert_as_query&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
    response['status'] = 0

  return JsonResponse(response)
Example #22
0
def get_size(instance):
    if hasattr(instance, "full_flavor"):
        size_string = _("%(name)s | %(RAM)s RAM")
        vals = {'name': instance.full_flavor.name,
                'RAM': sizeformat.mbformat(instance.full_flavor.ram)}
        return size_string % vals
    return _("Not available")
Example #23
0
def dump_student_extensions(course, student):
    """
    Dumps data about the due date extensions granted for a particular student
    in a particular course.
    """
    data = []
    header = [_("Unit"), _("Extended Due Date")]
    units = get_units_with_due_date(course)
    units = {u.location: u for u in units}
    query = StudentFieldOverride.objects.filter(
        course_id=course.id,
        student=student,
        field='due')
    for override in query:
        location = override.location.replace(course_key=course.id)
        if location not in units:
            continue
        due = DATE_FIELD.from_json(json.loads(override.value))
        due = due.strftime("%Y-%m-%d %H:%M")
        title = title_or_url(units[location])
        data.append(dict(zip(header, (title, due))))
    return {
        "header": header,
        "title": _("Due date extensions for {0} {1} ({2})").format(
            student.first_name, student.last_name, student.username),
        "data": data}
Example #24
0
 def check_server_disallowed(self):
     """
     Check if server domain name or IP is disallowed in settings.py.
     """
     hostname = self.netloc_parts[2].lower()
     if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
         settings.DISALLOWED_DOMAIN_LIST):
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
     try:
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
             locals()))
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
         return
     server = long_ip(ip)
     # print 'server', server, dotted_ip(server), ip
     for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
         disallowed = disallowed.strip()
         if disallowed == '' or disallowed.startswith('#'):
             continue
         mask = bit_mask(32)
         if '/' in disallowed:
             disallowed, bits = disallowed.split('/', 1)
             mask = slash_mask(int(bits))
         identifier = long_ip(disallowed) & mask
         masked = server & mask
         if masked == identifier:
             raise ValidationError(unicode(
                 _("Server IP address %(ip)s is disallowed.") % locals()))
Example #25
0
    def crop_and_upload_image_to_popit(self, image_filename, crop_bounds, moderator_why_allowed, make_primary):
        original = PillowImage.open(image_filename)
        # Some uploaded images are CYMK, which gives you an error when
        # you try to write them as PNG, so convert to RGBA (this is
        # RGBA rather than RGB so that any alpha channel (transparency)
        # is preserved).
        person_id = self.queued_image.person.id
        person_extra = PersonExtra.objects.get(base__id=person_id)
        original = original.convert('RGBA')
        cropped = original.crop(crop_bounds)
        ntf = NamedTemporaryFile(delete=False)
        cropped.save(ntf.name, 'PNG')
        md5sum = get_file_md5sum(ntf.name)
        filename = str(person_id) + '.png'
        source = _(
            'Uploaded by {uploaded_by}: Approved from photo moderation queue'
        ).format(uploaded_by=self.queued_image.user.username)

        ImageExtra.objects.create_from_file(
            ntf.name,
            join('images', filename),
            base_kwargs={
                'source': source,
                'is_primary': make_primary,
                'content_object': person_extra,
            },
            extra_kwargs={
                'md5sum': md5sum,
                'uploading_user': self.queued_image.user,
                'user_notes': self.queued_image.justification_for_use,
                'copyright': moderator_why_allowed,
                'user_copyright': self.queued_image.why_allowed,
                'notes': _('Approved from photo moderation queue'),
            },
        )
Example #26
0
    def __init__(self, *args, **kwargs):
        super(ReservationCrispyFormModelForm,self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_action = ""
        self.helper.form_method = "POST"
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-3'
        self.helper.field_class = 'col-sm-4'
        self.fields["acceptation"].widget = forms.RadioSelect()
        # delete empty choice for the type
        del self.fields["acceptation"].choices[0]
        self.helper.layout = layout.Layout(
            layout.Fieldset(
                _("Main data"),
                Field("acceptation", css_class="input-block-level"),
                _("Renseignement"),
                Field("firstname", css_class="input-block-level"),
                Field("lastname", css_class="input-block-level"),
                Field("telephone", css_class="input-block-level"),
                Field("accompagnement", css_class="input-block-level"),
                Field("notes", css_class="input-block-level", rows="3"),
                ),
                FormActions(
                    Submit("submit", _("Save")),
                    Button('cancel', 'Cancelar', onclick="window.location.href='/';")
                )
        )
Example #27
0
 def handle(self, *args, **options):
     message = options.get('message')
     verbosity = options.get('verbosity')
     get_template('templated_email/notice.email')
     if not message:
         raise CommandError(_('message must be included in options'))
     # get all users
     users = User.objects.all()
     for user in users:
         name = user.get_full_name()
         if not name or len(name) == 0:
             name = user.email
         if verbosity:
             self.stdout.write(_(
                 'Emailing name: %(name)s, email: %(email)s')
                 % {'name': name, 'email': user.email})
         # send each email separately so users cannot see eachother
         send_templated_mail(
             template_name='notice',
             from_email='noreply@ona.io',
             recipient_list=[user.email],
             context={
                 'username': user.username,
                 'full_name': name,
                 'message': message
             }, )
Example #28
0
    def clean_destination(self):
        create = self.cleaned_data.get("create")
        dest = self.cleaned_data.get("destination")
        dest = os.path.abspath(dest.strip().replace("..", ""))

        if not self.jail:
            jail = self.cleaned_data.get("jail")
            if jail:
                self.jail = Jails.objects.get(jail_host=jail)

        if not self.jail:
            raise forms.ValidationError(
                _("This shouldn't happen, but the jail could not be found")
            )

        full = "%s/%s%s" % (self.jc.jc_path, self.jail.jail_host, dest)

        if len(full) > 88:
            raise forms.ValidationError(
                _("The full path cannot exceed 88 characters")
            )

        if not os.path.exists(full):
            os.makedirs(full)

        return dest
Example #29
0
def create_saved_search(request, database_name=settings.MONGO_DB_NAME,
                collection_name=settings.MONGO_MASTER_COLLECTION,
                        skip=0, limit=200, return_keys=()):
    name = _("Create a Saved Search")
    if request.method == 'POST':
        form = SavedSearchForm(request.POST)
        if form.is_valid():
            ss = form.save(commit = False)
            ss.user = request.user
            ss.save()
                
            return HttpResponseRedirect(reverse('saved_searches'))
        else:
            #The form is invalid
             messages.error(request,_("Please correct the errors in the form."))
             return render_to_response('generic/bootstrapform.html',
                                            {'form': form,
                                             'name':name,
                                             },
                                            RequestContext(request))
            
   #this is a GET
    idata ={'database_name': database_name,
            'collection_name': collection_name}
    
    
    context= {'name':name,
              'form': SavedSearchForm(initial=idata)
              }
    return render_to_response('generic/bootstrapform.html',
                             RequestContext(request, context,))
def render_js_extra(context, **pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:

        def js_extra():
            return render_js_extra(context)

        settings = context.get("settings", UNDEFINED)
        __M_writer = context.writer()
        # SOURCE LINE 57
        __M_writer(
            u"\n  <script type=\"text/javascript\">\n    $(function() {\n\n      var view_name = 'view-login';\n\n      // adding js class for styling with accessibility in mind\n      $('body').addClass('js').addClass(view_name);\n\n      // new window/tab opening\n      $('a[rel=\"external\"], a[class=\"new-vp\"]')\n      .click( function() {\n      window.open( $(this).attr('href') );\n      return false;\n      });\n\n      // form field label styling on focus\n      $(\"form :input\").focus(function() {\n        $(\"label[for='\" + this.id + \"']\").parent().addClass(\"is-focused\");\n      }).blur(function() {\n        $(\"label\").parent().removeClass(\"is-focused\");\n      });\n    });\n\n    (function() {\n        var urlParams = {};\n        var searchString = window.location.search.substring(1);\n        if (searchString !== undefined) {\n            var pairs = searchString.split('&');\n            for (var i = 0; i < pairs.length; i++) {\n                var values = pairs[i].split('=');\n                urlParams[values[0]] = values[1] === undefined ? false : decodeURIComponent(values[1]);\n            }\n        }\n\n        if (localStorage.pepperpd_login_email)\n        {\n            $(\"#email\").val(localStorage.pepperpd_login_email);\n        }\n        toggleSubmitButton(true);\n\n        $('#login-form').on('submit', function() {\n            toggleSubmitButton(false);\n        });\n\n        $('#login-form').on('ajax:error', function() {\n            toggleSubmitButton(true);\n        });\n\n        $('#login-form').on('ajax:success', function(event, json, xhr) {\n            if (json.success) {\n                if ($('#remember-yes').attr(\"checked\"))\n                {\n                    localStorage.pepperpd_login_email=$(\"#email\").val();\n                }\n\n                if (urlParams['next'] !== undefined && !isExternal(urlParams['next']) && urlParams['next'].match(/^course.+courseware/)) {\n                    var next = urlParams['next'];\n                    if (next.substring(0,1) != '/') {\n                        next = '/' + next;\n                    }\n                  location.href = next;\n                } else if (urlParams['next'] !== undefined && !isExternal(urlParams['next']) && urlParams['next'].match(/^\\/sso\\/idp\\/auth/)) {\n                   location.href = urlParams['next'];\n                }  else {\n                    location.href = \""
        )
        # SOURCE LINE 122
        __M_writer(filters.decode.utf8(reverse("dashboard")))
        __M_writer(
            u"\";\n                }\n\n            } else {\n                toggleSubmitButton(true);\n                $('.message.submission-error').addClass('is-shown').focus();\n                $('.message.submission-error .message-copy').html(json.value);\n            }\n        });\n    })(this);\n\n    function toggleSubmitButton(enable) {\n      var $submitButton = $('form .form-actions #submit');\n\n\n      if(enable) {\n        $submitButton.\n          removeClass('is-disabled').\n          removeProp('disabled').\n\n          <!--@begin:modify LogIn -> Log In-->\n          <!--@date:2013-11-02-->\n          html(\""
        )
        # SOURCE LINE 144
        __M_writer(filters.decode.utf8(_("Log In").format(platform_name=settings.PLATFORM_NAME)))
        __M_writer(u" <span class='orn-plus'>&</span> ")
        __M_writer(filters.decode.utf8(_("Access My Courses")))
        __M_writer(
            u"\");\n          <!--@end-->\n      } else {\n        $submitButton.\n          addClass('is-disabled').\n          prop('disabled', true).\n          html(gettext('Processing your account information &hellip;'));\n      }\n\n    }\n\n//------------- Clear time storage-------------------//\n\n    function clearTimeSessionStorage(){\n      var user_id = sessionStorage.getItem('user_id');\n      if(user_id != null){\n        sessionStorage.removeItem(user_id + '_course_id');\n        sessionStorage.removeItem(user_id + '_vertical_id');\n        sessionStorage.removeItem(user_id + '_type');\n        sessionStorage.removeItem(user_id + '_time');\n        sessionStorage.removeItem('user_id');\n      }\n    }\n\n    clearTimeSessionStorage();\n\n  </script>\n"
        )
        return ""
    finally:
        context.caller_stack._pop_frame()