IC: Send Valid Or Invalid User Code Format.
495010
def _ic_decode(self, msg):
        """"""
        code = msg[4:16]
        if re.match(r'(0\d){6}', code):
            code = re.sub(r'0(\d)', r'\1', code)
        return {'code': code, 'user': int(msg[16:19])-1,
                'keypad': int(msg[19:21])-1}
1092578
def send_exit_with_code(cls, sock, code):
    """"""
    encoded_exit_status = cls.encode_int(code)
    cls.send_exit(sock, payload=encoded_exit_status)
778141
def validate_options(self, k, v):
        """"""

        super().validate_options(k, v)
        if k == 'errors' and v.lower() not in ('strict', 'replace', 'ignore', 'backslashreplace'):
            raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
        if k == 'normalize' and v.upper() not in ('NFC', 'NFKC', 'NFD', 'NFKD'):
            raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
80439
def _raise_on_invalid_client(self, request):
        """"""
        if self.request_validator.client_authentication_required(request):
            if not self.request_validator.authenticate_client(request):
                log.debug('Client authentication failed, %r.', request)
                raise InvalidClientError(request=request)
        elif not self.request_validator.authenticate_client_id(request.client_id, request):
            log.debug('Client authentication failed, %r.', request)
            raise InvalidClientError(request=request)
646742
def validate(self):
        

        if not (self.recipients or self.cc or self.bcc):
            raise InvalidMessage("No recipients have been added")

        if not self.body and not self.html:
            raise InvalidMessage("No body has been set")

        if not self.sender:
            raise InvalidMessage("No sender address has been set")

        if self.is_bad_headers():
            raise BadHeaders
1167404
def _send_status_0x01_request(self):
        """"""
        status_command = StandardSend(self._address,
                                      COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01)
        self._send_method(status_command, self._status_message_0x01_received)
625721
def is_valid(self):
        """"""
        for lineedit in self.lineedits:
            if lineedit in self.validate_data and lineedit.isEnabled():
                validator, invalid_msg = self.validate_data[lineedit]
                text = to_text_string(lineedit.text())
                if not validator(text):
                    QMessageBox.critical(self, self.get_name(),
                                     "%s:<br><b>%s</b>" % (invalid_msg, text),
                                     QMessageBox.Ok)
                    return False
        return True
1213383
def _validate_country_codes(self, ccs):
        """"""
        for cc in ccs:
            if cc not in self.country_codes:
                raise InvalidCountryCodeError(cc)
        return {'country': ",".join(ccs)}
744645
def _validate(self):
        
        if not is_valid_subject(self.subject):
            raise MessageError("Invalid subject: '%s'" % self.subject)
        if not is_valid_type(self.type):
            raise MessageError("Invalid type: '%s'" % self.type)
        if not is_valid_sender(self.sender):
            raise MessageError("Invalid sender: '%s'" % self.sender)
        if not self.binary and not is_valid_data(self.data):
            raise MessageError("Invalid data: data is not JSON serializable: %s"
                               % str(self.data))
61997
def validate_format(self, allowed_formats):
        
        if self.format in allowed_formats:
            return

        ui.error("Export type '{0}' does not accept '{1}' format, only: "
                 "{2}".format(self.type, self.format, allowed_formats))
        sys.exit(1)
1092616
def raise_for_status(self):
        """"""

        http_error_msg = ''
        if isinstance(self.reason, bytes):
            # We attempt to decode utf-8 first because some servers
            # choose to localize their reason strings. If the string
            # isn't utf-8, we fall back to iso-8859-1 for all other
            # encodings. (See PR #3538)
            try:
                reason = self.reason.decode('utf-8')
            except UnicodeDecodeError:
                reason = self.reason.decode('iso-8859-1')
        else:
            reason = self.reason

        if 400 <= self.status_code < 500:
            http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)

        elif 500 <= self.status_code < 600:
            http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)

        if http_error_msg:
            raise HTTPError(http_error_msg, response=self)
924396
def validate(cls, code, prefix):
        '''
        
        '''
        reasons = []

        pieces = code.split('-')
        n = len(pieces)
        if n > 3:
            reasons.append('{}invalid geo code "{}"'.format(prefix, code))
        elif n > 0 and pieces[0] not in geo_data:
            reasons.append('{}unknown continent code "{}"'
                           .format(prefix, code))
        elif n > 1 and pieces[1] not in geo_data[pieces[0]]:
            reasons.append('{}unknown country code "{}"'.format(prefix, code))
        elif n > 2 and \
                pieces[2] not in geo_data[pieces[0]][pieces[1]]['provinces']:
            reasons.append('{}unknown province code "{}"'.format(prefix, code))

        return reasons
478562
def __validate_email(self, email):
        """"""

        e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)
        if e:
            return email
        else:
            error = "Invalid email address: " + str(email)
            msg = self.GRIMOIRELAB_INVALID_FORMAT % {'error': error}
            raise InvalidFormatError(cause=msg)
734436
def hex(self):
        """"""
        props = self._message_properties()
        msg = bytearray([MESSAGE_START_CODE_0X02, self._code])

        for prop in props:
            # pylint: disable=unused-variable
            for key, val in prop.items():
                if val is None:
                    pass
                elif isinstance(val, int):
                    msg.append(val)
                elif isinstance(val, Address):
                    if val.addr is None:
                        pass
                    else:
                        msg.extend(val.bytes)
                elif isinstance(val, MessageFlags):
                    msg.extend(val.bytes)
                elif isinstance(val, bytearray):
                    msg.extend(val)
                elif isinstance(val, bytes):
                    msg.extend(val)
                elif isinstance(val, Userdata):
                    msg.extend(val.bytes)

        return binascii.hexlify(msg).decode()
1164828
function sendHTMLErrorCode(code, message, res) {
  return function () {
    res.type('html');
    res.send(code + ' ' + message);
  };
}
101060
def form_valid(self,form):
        '''
        
        '''
        emailTo = form.cleaned_data.get('emailTo')
        emailType = form.cleaned_data.get('emailType')
        recipientName = form.cleaned_data.get('recipientName')
        fromName = form.cleaned_data.get('fromName')
        message = form.cleaned_data.get('message')

        logger.info('Processing gift certificate.')

        try:
            voucher = Voucher.create_new_code(
                prefix='GC_',
                name=_('Gift certificate: %s%s for %s' % (getConstant('general__currencySymbol'),self.amount, emailTo)),
                category=getConstant('vouchers__giftCertCategory'),
                originalAmount=self.amount,
                singleUse=False,
                forFirstTimeCustomersOnly=False,
                expirationDate=None,
            )
        except IntegrityError:
            logger.error('Error creating gift certificate voucher for Invoice #%s' % self.invoiceId)
            emailErrorMessage(_('Gift certificate transaction not completed'), self.invoiceId)

        template = getConstant('vouchers__giftCertTemplate')

        # Attempt to attach a PDF of the gift certificate
        rf = RequestFactory()
        pdf_request = rf.get('/')

        pdf_kwargs = {
            'currencySymbol': getConstant('general__currencySymbol'),
            'businessName': getConstant('contact__businessName'),
            'certificateAmount': voucher.originalAmount,
            'certificateCode': voucher.voucherId,
            'certificateMessage': message,
            'recipientName': recipientName,
            'fromName': fromName,
        }
        if recipientName:
            pdf_kwargs.update({})

        attachment = GiftCertificatePDFView(request=pdf_request).get(request=pdf_request,**pdf_kwargs).content or None

        if attachment:
            attachment_name = 'gift_certificate.pdf'
        else:
            attachment_name = None

        # Send a confirmation email
        email_class = EmailRecipientMixin()
        email_class.email_recipient(
            subject=template.subject,
            content=template.content,
            send_html=template.send_html,
            html_content=template.html_content,
            from_address=template.defaultFromAddress,
            from_name=template.defaultFromName,
            cc=template.defaultCC,
            to=emailTo,
            currencySymbol=getConstant('general__currencySymbol'),
            businessName=getConstant('contact__businessName'),
            certificateAmount=voucher.originalAmount,
            certificateCode=voucher.voucherId,
            certificateMessage=message,
            recipientName=recipientName,
            fromName=fromName,
            emailType=emailType,
            recipient_name=recipientName,
            attachment_name=attachment_name,
            attachment=attachment
        )

        # Remove the invoice session data
        self.request.session.pop(INVOICE_VALIDATION_STR,None)

        return HttpResponseRedirect(self.get_success_url())
1337279
def _send(self, value, mode):
        """"""

        # Assemble the parameters sent to the pigpio script
        params = [mode]
        params.extend([(value >> i) & 0x01 for i in range(8)])
        # Switch off pigpio's exceptions, so that we get the return codes
        pigpio.exceptions = False
        while True:
            ret = self.pi.run_script(self._writescript, params)
            if ret >= 0:
                break
            elif ret != pigpio.PI_SCRIPT_NOT_READY:
                raise pigpio.error(pigpio.error_text(ret))
            # If pigpio script is not ready, sleep and try again
            c.usleep(1)
        # Switch on pigpio's exceptions
        pigpio.exceptions = True