Throws a standard exception for when a value is not encodable by an
        encoder.
18724
def invalidate_value(
        cls,
        value: Any,
        exc: Type[Exception]=EncodingTypeError,
        msg: Optional[str]=None,
    ) -> None:
        
        raise exc(
            "Value `{rep}` of type {typ} cannot be encoded by {cls}{msg}".format(
                rep=abbr(value),
                typ=type(value),
                cls=cls.__name__,
                msg="" if msg is None else (": " + msg),
            )
        )
787989
static public function throwTypingError($value)
    {
        $givenValue = (gettype($value) == 'object') ? get_class($value) : gettype($value);
        $acceptedTypes = array('boolean', 'integer', 'float', 'double', 'string', 'Duration', 'Pair', 'DirectedPair', 'Point');
        $acceptedTypes = implode(", ", $acceptedTypes);
        $msg = "A value is not compliant with the QTI runtime model datatypes: ${acceptedTypes} . '${givenValue}' given.";
        throw new InvalidArgumentException($msg);
    }
1140613
private void encodeThis() throws IOException {
        minMaxValid = false;
        if (permitted == null && excluded == null) {
            this.extensionValue = null;
            return;
        }
        DerOutputStream seq = new DerOutputStream();

        DerOutputStream tagged = new DerOutputStream();
        if (permitted != null) {
            DerOutputStream tmp = new DerOutputStream();
            permitted.encode(tmp);
            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                                 true, TAG_PERMITTED), tmp);
        }
        if (excluded != null) {
            DerOutputStream tmp = new DerOutputStream();
            excluded.encode(tmp);
            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                                 true, TAG_EXCLUDED), tmp);
        }
        seq.write(DerValue.tag_Sequence, tagged);
        this.extensionValue = seq.toByteArray();
    }
979219
def safely_encode(unicode_or_str, encoding='utf-8'):
  '''  '''
  if isinstance(unicode_or_str, unicode):
    rstr = unicode_or_str.encode(encoding, 'replace')
  elif isinstance(unicode_or_str, str):
    rstr = unicode_or_str
  else:
    raise Exception(u'Not of type unicode or str')

  return rstr
522677
def encode(value, encoding='utf-8', encoding_errors='strict'):
    
    if isinstance(value, bytes):
        return value
    if not isinstance(value, basestring):
        value = str(value)
    if isinstance(value, unicode):
        value = value.encode(encoding, encoding_errors)
    return value
843530
@Override
    public void encodeTo(FLEncoder enc) {
        final Encoder encoder = new Encoder(enc);
        internalDict.encodeTo(encoder);
        encoder.release();
    }
1172188
def encode(cls, value):
        
        try:
            if float(value) + 0 == value:
                return repr(value)
        except (TypeError, ValueError):
            pass

        raise InvalidValue('not a float')
1303589
public boolean process(byte value) throws Exception {
        if (value == (byte) 'e' || value == (byte) 'E') {
            return true;
        }
        if (value >= (byte) '0' && value <= (byte) '9') {
            return true;
        }
        return value == JSON_MINUS || value == JSON_PLUS || value == (byte) '.';
    }
74968
private void determineValueType(Object value){
		if (value instanceof Integer){
			this.valueEncoder.valueType = INTEGER;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(4).putInt((Integer)value).array();
		}
		else if (value instanceof Long) {
			this.valueEncoder.valueType = LONG;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(8).putLong((Long)value).array();
		}
		else if (value == null){
			this.valueEncoder.valueType = NULL;
		}
		else {
			ObjectOutputStream oos = null;
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				oos = new ObjectOutputStream(bos);
				oos.writeObject(value);
				this.valueEncoder.valueType = OBJECT;
				this.valueEncoder.valueBytes = bos.toByteArray();
			} catch (Exception e) {
				throw new IllegalStateException("Failed to serialize value: " + value, e);
			} finally {
				try {
					if (oos != null){
						oos.close();
					}
				} catch (Exception e2) {/*ignore*/}
			}
		}
	}
947929
private byte[] encode(byte[] input) throws EncoderException
    {
        if (encoder != null)
        {
            return encoder.encode(input);
        }
        else
        {
            return DEFAULT_CODER.encode(input);
        }
    }
870006
def encode(self, value):
        ""
        if isinstance(value, Token):
            return value.encoded_value
        elif isinstance(value, bytes):
            return value
        elif isinstance(value, bool):
            # special case bool since it is a subclass of int
            raise DataError("Invalid input of type: 'bool'. Convert to a "
                            "byte, string or number first.")
        elif isinstance(value, float):
            value = repr(value).encode()
        elif isinstance(value, (int, long)):
            # python 2 repr() on longs is '123L', so use str() instead
            value = str(value).encode()
        elif not isinstance(value, basestring):
            # a value we don't know how to deal with. throw an error
            typename = type(value).__name__
            raise DataError("Invalid input of type: '%s'. Convert to a "
                            "byte, string or number first." % typename)
        if isinstance(value, unicode):
            value = value.encode(self.encoding, self.encoding_errors)
        return value
1146535
def create_exception(self, code):
        
        frame = deepcopy(self)
        frame.length = 3
        frame.fcode += 0x80
        frame.data = bytearray(chr(code))
        return frame
1173823
public IoBuffer encode(Object message) throws Exception {
        if (message != null) {
            try {
                return encodePacket((Packet) message);
            } catch (Exception e) {
                log.error("Error encoding", e);
            }
        } else if (log.isDebugEnabled()) {
            try {
                String callingMethod = Thread.currentThread().getStackTrace()[4].getMethodName();
                log.debug("Message is null at encode, expecting a Packet from: {}", callingMethod);
            } catch (Throwable t) {
                log.warn("Problem getting current calling method from stacktrace", t);
            }
        }
        return null;
    }
785494
function(value) {
		if ([
			['%5B', '%5D'],
			['%7B', '%7D']
		].some(function isencoded(tokens) {
			return value.startsWith(tokens[0]) && value.endsWith(tokens[1]);
		})) {
			try {
				value = JSON.parse(decodeURIComponent(value));
			} catch (exception) {
				value = null;
				console.error(this + ': Bad JSON: ' + exception.message);
			}
		}
		return value;
	}
348117
public UnsupportedEncodingException toJDKException() {
        UnsupportedEncodingException e = new UnsupportedEncodingException() {
            @Override
            public synchronized Throwable fillInStackTrace() {
                return this;
            }
        };
        e.setStackTrace(getStackTrace());
        return e;
    }
606831
def encode(cls, value):
        
        coerced = unicode(value)
        if coerced == value and cls.PATTERN.match(coerced):
            return coerced.encode(cls._encoding)

        raise InvalidValue('not ascii')
198034
private void encodeThis() throws IOException {
        if (require == -1 && inhibit == -1) {
            this.extensionValue = null;
            return;
        }
        DerOutputStream tagged = new DerOutputStream();
        DerOutputStream seq = new DerOutputStream();

        if (require != -1) {
            DerOutputStream tmp = new DerOutputStream();
            tmp.putInteger(require);
            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                         false, TAG_REQUIRE), tmp);
        }
        if (inhibit != -1) {
            DerOutputStream tmp = new DerOutputStream();
            tmp.putInteger(inhibit);
            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                         false, TAG_INHIBIT), tmp);
        }
        seq.write(DerValue.tag_Sequence, tagged);
        this.extensionValue = seq.toByteArray();
    }