Encode a tf.Scalar string to a tf.Tensor.

    This will be necessary for on-the-fly tokenization.

    Args:
      s: a tf.Scalar with dtype tf.string
    Returns:
      a 1d tf.Tensor with dtype tf.int32
338905
def encode_tf(self, s):
    
    ids = subword_text_encoder_ops.subword_text_encoder_encode(
        s, self._filepath)
    # the c++ op apppends 1=EOS - drop it.
    return ids[:-1]
728536
def numpy_scalar_to_python(scalar):
    
    scalar_type = type(scalar)
    if np.issubclass_(scalar_type, np.float_):
        return float(scalar)
    elif np.issubclass_(scalar_type, np.int_):
        return int(scalar)
    return scalar
347739
def convert_values(self):
        
        def stringify(value):
            if self.encoding is not None:
                encoder = partial(pprint_thing_encoded,
                                  encoding=self.encoding)
            else:
                encoder = pprint_thing
            return encoder(value)

        lhs, rhs = self.lhs, self.rhs

        if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.is_scalar:
            v = rhs.value
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = Timestamp(_ensure_decoded(v))
            if v.tz is not None:
                v = v.tz_convert('UTC')
            self.rhs.update(v)

        if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.is_scalar:
            v = lhs.value
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = Timestamp(_ensure_decoded(v))
            if v.tz is not None:
                v = v.tz_convert('UTC')
            self.lhs.update(v)
159553
def CreateString(self, s, encoding='utf-8', errors='strict'):
        """"""

        self.assertNotNested()
        ## @cond FLATBUFFERS_INTERNAL
        self.nested = True
        ## @endcond

        if isinstance(s, compat.string_types):
            x = s.encode(encoding, errors)
        elif isinstance(s, compat.binary_types):
            x = s
        else:
            raise TypeError("non-string passed to CreateString")

        self.Prep(N.UOffsetTFlags.bytewidth, (len(x)+1)*N.Uint8Flags.bytewidth)
        self.Place(0, N.Uint8Flags)

        l = UOffsetTFlags.py_type(len(s))
        ## @cond FLATBUFFERS_INTERNAL
        self.head = UOffsetTFlags.py_type(self.Head() - l)
        ## @endcond
        self.Bytes[self.Head():self.Head()+l] = x

        return self.EndVector(len(x))
451008
def to_bytes(s):
    
    if bytes != str:
        if type(s) == str:
            return s.encode('utf-8')
    return s
896006
def fsencoding(s, encoding=sys.getfilesystemencoding()):
    
    if isinstance(s, unicode):
        s = s.encode(encoding)
    return s
935797
def load_tensor(f, format=None):  # type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto
    '''
    
    '''
    s = _load_bytes(f)
    return load_tensor_from_string(s, format=format)
355816
public void encode(final MiniSatStyleSolver s, final LNGIntVector lits) {
    assert lits.size() != 0;
    if (lits.size() == 1)
      addUnitClause(s, lits.get(0));
    else {
      final LNGIntVector seqAuxiliary = new LNGIntVector();
      for (int i = 0; i < lits.size() - 1; i++) {
        seqAuxiliary.push(mkLit(s.nVars(), false));
        MaxSAT.newSATVariable(s);
      }
      for (int i = 0; i < lits.size(); i++) {
        if (i == 0) {
          addBinaryClause(s, lits.get(i), not(seqAuxiliary.get(i)));
          addBinaryClause(s, not(lits.get(i)), seqAuxiliary.get(i));
        } else if (i == lits.size() - 1) {
          addBinaryClause(s, lits.get(i), seqAuxiliary.get(i - 1));
          addBinaryClause(s, not(lits.get(i)), not(seqAuxiliary.get(i - 1)));
        } else {
          addBinaryClause(s, not(seqAuxiliary.get(i - 1)), seqAuxiliary.get(i));
          addTernaryClause(s, lits.get(i), not(seqAuxiliary.get(i)), seqAuxiliary.get(i - 1));
          addBinaryClause(s, not(lits.get(i)), seqAuxiliary.get(i));
          addBinaryClause(s, not(lits.get(i)), not(seqAuxiliary.get(i - 1)));
        }
      }
    }
  }
92579
def encode(s):
    
    if not isinstance(s, text_type):
        return s

    r = []
    _in = []

    def extend_result_if_chars_buffered():
        if _in:
            r.extend(['&', modified_utf7(''.join(_in)), '-'])
            del _in[:]

    for c in s:
        if ord(c) in PRINTABLE:
            extend_result_if_chars_buffered()
            r.append(c)
        elif c == '&':
            extend_result_if_chars_buffered()
            r.append('&-')
        else:
            _in.append(c)

    extend_result_if_chars_buffered()

    return ''.join(r)
167592
def to_s format=:symbol
      if format == :name
        unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name 
      else
        unit_string = @unit.send format 
      end

      string =  "#{@value}"
      string += " #{unit_string}" unless unit_string.empty?

      string
    end
1050116
def _decode(self, s, encode_nominal=False, matrix_type=DENSE):
        ''''''

        # Make sure this method is idempotent
        self._current_line = 0

        # If string, convert to a list of lines
        if isinstance(s, basestring):
            s = s.strip('\r\n ').replace('\r\n', '\n').split('\n')

        # Create the return object
        obj = {
            u'description': u'',
            u'relation': u'',
            u'attributes': [],
            u'data': []
        }
        attribute_names = {}

        # Create the data helper object
        data = _get_data_object_for_decoding(matrix_type)

        # Read all lines
        STATE = _TK_DESCRIPTION
        s = iter(s)
        for row in s:
            self._current_line += 1
            # Ignore empty lines
            row = row.strip(' \r\n')
            if not row: continue

            u_row = row.upper()

            # DESCRIPTION -----------------------------------------------------
            if u_row.startswith(_TK_DESCRIPTION) and STATE == _TK_DESCRIPTION:
                obj['description'] += self._decode_comment(row) + '\n'
            # -----------------------------------------------------------------

            # RELATION --------------------------------------------------------
            elif u_row.startswith(_TK_RELATION):
                if STATE != _TK_DESCRIPTION:
                    raise BadLayout()

                STATE = _TK_RELATION
                obj['relation'] = self._decode_relation(row)
            # -----------------------------------------------------------------

            # ATTRIBUTE -------------------------------------------------------
            elif u_row.startswith(_TK_ATTRIBUTE):
                if STATE != _TK_RELATION and STATE != _TK_ATTRIBUTE:
                    raise BadLayout()

                STATE = _TK_ATTRIBUTE

                attr = self._decode_attribute(row)
                if attr[0] in attribute_names:
                    raise BadAttributeName(attr[0], attribute_names[attr[0]])
                else:
                    attribute_names[attr[0]] = self._current_line
                obj['attributes'].append(attr)

                if isinstance(attr[1], (list, tuple)):
                    if encode_nominal:
                        conversor = EncodedNominalConversor(attr[1])
                    else:
                        conversor = NominalConversor(attr[1])
                else:
                    CONVERSOR_MAP = {'STRING': unicode,
                                     'INTEGER': lambda x: int(float(x)),
                                     'NUMERIC': float,
                                     'REAL': float}
                    conversor = CONVERSOR_MAP[attr[1]]

                self._conversors.append(conversor)
            # -----------------------------------------------------------------

            # DATA ------------------------------------------------------------
            elif u_row.startswith(_TK_DATA):
                if STATE != _TK_ATTRIBUTE:
                    raise BadLayout()

                break
            # -----------------------------------------------------------------

            # COMMENT ---------------------------------------------------------
            elif u_row.startswith(_TK_COMMENT):
                pass
            # -----------------------------------------------------------------
        else:
            # Never found @DATA
            raise BadLayout()

        def stream():
            for row in s:
                self._current_line += 1
                row = row.strip()
                # Ignore empty lines and comment lines.
                if row and not row.startswith(_TK_COMMENT):
                    yield row

        # Alter the data object
        obj['data'] = data.decode_rows(stream(), self._conversors)
        if obj['description'].endswith('\n'):
            obj['description'] = obj['description'][:-1]

        return obj
1108928
def to_str(s):
    
    if bytes != str:
        """
        这里的比较在python2中是True，在Python3中是False
        """
        if type(s) == bytes:
            return s.decode('utf-8')
    return s
1215689
def from_string(cls, s: str) -> 'ComponentRef':
        

        components = s.split('.')
        return cls.from_tuple(components)
976672
public void encodeString(final String s) throws IOException {
		final int lenChars = s.length();
		final int lenCharacters = s.codePointCount(0, lenChars);
		encodeUnsignedInteger(lenCharacters);
		encodeStringOnly(s);
	}
1295446
public Object stringToKey(String s) {
      char type = s.charAt(0);
      switch (type) {
         case 'S':
            // this is a String, NOT a Short. For Short see case 'X'.
            return s.substring(2);
         case 'I':
            // This is an Integer
            return Integer.valueOf(s.substring(2));
         case 'Y':
            // This is a BYTE
            return Byte.valueOf(s.substring(2));
         case 'L':
            // This is a Long
            return Long.valueOf(s.substring(2));
         case 'X':
            // This is a SHORT
            return Short.valueOf(s.substring(2));
         case 'D':
            // This is a Double
            return Double.valueOf(s.substring(2));
         case 'F':
            // This is a Float
            return Float.valueOf(s.substring(2));
         case 'B':
            // This is a Boolean, NOT a Byte. For Byte see case 'Y'.
            return Boolean.valueOf(s.substring(2));
         case 'C':
            // This is a Character
            return Character.valueOf(s.charAt(2));
         case 'U':
            // This is a java.util.UUID
            return UUID.fromString(s.substring(2));
         case 'A':
            // This is an array of bytes encoded as a Base64 string
            return Base64.getDecoder().decode(s.substring(2));
         case 'T':
            // this is a custom Transformable or a type with a registered Transformer
            int indexOfSecondDelimiter = s.indexOf(':', 2);
            String keyClassName = s.substring(2, indexOfSecondDelimiter);
            String keyAsString = s.substring(indexOfSecondDelimiter + 1);
            Transformer t = getTransformer(keyClassName);
            if (t != null) {
               return t.fromString(keyAsString);
            } else {
               throw log.noTransformerForKey(keyClassName);
            }
      }
      throw new CacheException("Unknown key type metadata: " + type);
   }
1130146
def bytes_(s, encoding='utf-8', errors='strict'):
    
    if isinstance(s, text_type):  # pragma: no cover
        return s.encode(encoding, errors)
    return s
192998
def encode_to_shape(inputs, shape, scope):
  """"""
  with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
    w, h = shape[1], shape[2]
    x = inputs
    x = tfl.flatten(x)
    x = tfl.dense(x, w * h, activation=None, name="enc_dense")
    x = tf.reshape(x, (-1, w, h, 1))
    return x