當前位置: 首頁>>代碼示例>>Python>>正文


Python six.string_types方法代碼示例

本文整理匯總了Python中six.string_types方法的典型用法代碼示例。如果您正苦於以下問題:Python six.string_types方法的具體用法?Python six.string_types怎麽用?Python six.string_types使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在six的用法示例。


在下文中一共展示了six.string_types方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_prep_value

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def get_prep_value(self, value):
        if value is self.Empty or value is None:
            return ''  # CharFields should use '' as their empty value, rather than None

        if isinstance(value, six.string_types):
            value = self.KEY_CLASS.from_string(value)

        assert isinstance(value, self.KEY_CLASS), "%s is not an instance of %s" % (value, self.KEY_CLASS)
        serialized_key = six.text_type(_strip_value(value))
        if serialized_key.endswith('\n'):
            # An opaque key object serialized to a string with a trailing newline.
            # Log the value - but do not modify it.
            log.warning(u'{}:{}:{}:get_prep_value: Invalid key: {}.'.format(
                self.model._meta.db_table,  # pylint: disable=protected-access
                self.name,
                self.KEY_CLASS.__name__,
                repr(serialized_key)
            ))
        return serialized_key 
開發者ID:appsembler,項目名稱:figures,代碼行數:21,代碼來源:models.py

示例2: similarity_label

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def similarity_label(self, words, normalization=True):
        """
        you can calculate more than one word at the same time.
        """
        if self.model==None:
            raise Exception('no model.')
        if isinstance(words, string_types):
            words=[words]
        vectors=np.transpose(self.model.wv.__getitem__(words))
        if normalization:
            unit_vector=unitvec(vectors,ax=0) # 這樣寫比原來那樣速度提升一倍
            #unit_vector=np.zeros((len(vectors),len(words)))
            #for i in range(len(words)):
            #    unit_vector[:,i]=matutils.unitvec(vectors[:,i])
            dists=np.dot(self.Label_vec_u, unit_vector)
        else:
            dists=np.dot(self.Label_vec, vectors)
        return dists 
開發者ID:Coldog2333,項目名稱:Financial-NLP,代碼行數:20,代碼來源:NLP.py

示例3: get_from_module

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def get_from_module(identifier, module_params, module_name,
                    instantiate=False, kwargs=None):
    #{{{
    if isinstance(identifier, six.string_types):
        res = module_params.get(identifier)
        if not res:
            raise ValueError('Invalid ' + str(module_name) + ': ' +
                             str(identifier))
        if instantiate and not kwargs:
            return res()
        elif instantiate and kwargs:
            return res(**kwargs)
        else:
            return res
    elif isinstance(identifier, dict):
        name = identifier.pop('name')
        res = module_params.get(name)
        if res:
            return res(**identifier)
        else:
            raise ValueError('Invalid ' + str(module_name) + ': ' +
                             str(identifier))
    return identifier
#}}} 
開發者ID:lingluodlut,項目名稱:Att-ChemdNER,代碼行數:26,代碼來源:utils.py

示例4: clean_value

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def clean_value(value, unit="", convert_to_percent=False, max_dgts=3):
    """return clean value with maximum digits and optional unit and percent"""
    dgts = max_dgts
    value = str(value) if not isinstance(value, six.string_types) else value
    try:
        value = Decimal(value)
        dgts = len(value.as_tuple().digits)
        dgts = max_dgts if dgts > max_dgts else dgts
    except DecimalException:
        return value
    if convert_to_percent:
        value = Decimal(value) * Decimal("100")
        unit = "%"
    val = "{{:.{}g}}".format(dgts).format(value)
    if unit:
        val += " {}".format(unit)
    return val 
開發者ID:materialsproject,項目名稱:MPContribs,代碼行數:19,代碼來源:utils.py

示例5: deserialize_dtype

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def deserialize_dtype(d):
    """
    Deserializes a JSONified :obj:`numpy.dtype`.

    Args:
        d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object.

    Returns:
        A :obj:`dtype` object.
    """
    if isinstance(d['descr'], six.string_types):
        return np.dtype(d['descr'])
    descr = []
    for col in d['descr']:
        col_descr = []
        for c in col:
            if isinstance(c, six.string_types):
                col_descr.append(str(c))
            elif type(c) is list:
                col_descr.append(tuple(c))
            else:
                col_descr.append(c)
        descr.append(tuple(col_descr))
    return np.dtype(descr) 
開發者ID:gregreen,項目名稱:dustmaps,代碼行數:26,代碼來源:json_serializers.py

示例6: test_getTextFor

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def test_getTextFor(self):
        files = self.loader.fetchFiles()

        # the contents of each file
        for fItem in files:
            text = self.loader.getTextFor(fItem)

            # Should be some text
            self.assertIsInstance(text, six.string_types, "Should be some text")

            # Should be non-empty for existing items
            self.assertGreater(len(text), 0, "Should be non-empty")

        # Should raise exception for invalid file items
        with self.assertRaises(Exception, msg="Should raise exception for invalid file items"):
            text = self.loader.getTextFor({}) 
開發者ID:CLARIAH,項目名稱:grlc,代碼行數:18,代碼來源:test_loaders.py

示例7: test_get_yaml_decorators

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def test_get_yaml_decorators(self):
        rq, _ = self.loader.getTextForName('test-sparql')

        decorators = gquery.get_yaml_decorators(rq)

        # Query always exist -- the rest must be present on the file.
        self.assertIn('query', decorators, 'Should have a query field')
        self.assertIn('summary', decorators, 'Should have a summary field')
        self.assertIn('pagination', decorators,
                      'Should have a pagination field')
        self.assertIn('enumerate', decorators, 'Should have a enumerate field')

        self.assertIsInstance(
            decorators['summary'], six.string_types, 'Summary should be text')
        self.assertIsInstance(
            decorators['pagination'], int, 'Pagination should be numeric')
        self.assertIsInstance(
            decorators['enumerate'], list, 'Enumerate should be a list') 
開發者ID:CLARIAH,項目名稱:grlc,代碼行數:20,代碼來源:test_gquery.py

示例8: test_get_json_decorators

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def test_get_json_decorators(self):
        rq, _ = self.loader.getTextForName('test-sparql-jsonconf')

        decorators = gquery.get_yaml_decorators(rq)

        # Query always exist -- the rest must be present on the file.
        self.assertIn('query', decorators, 'Should have a query field')
        self.assertIn('summary', decorators, 'Should have a summary field')
        self.assertIn('pagination', decorators,
                      'Should have a pagination field')
        self.assertIn('enumerate', decorators, 'Should have a enumerate field')

        self.assertIsInstance(
            decorators['summary'], six.string_types, 'Summary should be text')
        self.assertIsInstance(
            decorators['pagination'], int, 'Pagination should be numeric')
        self.assertIsInstance(
            decorators['enumerate'], list, 'Enumerate should be a list') 
開發者ID:CLARIAH,項目名稱:grlc,代碼行數:20,代碼來源:test_gquery.py

示例9: _prepare_batch

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def _prepare_batch(sents, projector):
    if isinstance(sents, six.string_types):
        sents = [sents]

    sents = [np.array(projector(s)) for s in sents]
    lengths = [len(s) for s in sents]
    sents = _pad_sequences(sents, 0, max(lengths))

    idx = np.array(sorted(range(len(lengths)), key=lambda x: lengths[x], reverse=True))
    inv = np.array(sorted(range(len(lengths)), key=lambda x: idx[x]))
    sents = sents[idx]
    lengths = np.array(lengths)[idx].tolist()

    sents = as_variable(sents)
    if torch.cuda.is_available():
        sents = sents.cuda()
    return sents, lengths, idx, inv 
開發者ID:ExplorerFreda,項目名稱:VSE-C,代碼行數:19,代碼來源:saliency_visualization.py

示例10: __get_source_preset

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def __get_source_preset(self, source, preset=None):
        if preset is None:
            preset = 'table'
            if isinstance(source, six.string_types):
                source_path = source.lower()
                if source_path.endswith('datapackage.json') or source_path.endswith(
                    '.zip'
                ):
                    preset = 'datapackage'
            elif isinstance(source, dict):
                if 'resources' in source:
                    preset = 'datapackage'
            elif isinstance(source, list):
                if source and isinstance(source[0], dict) and 'source' in source[0]:
                    preset = 'nested'

        return preset 
開發者ID:frictionlessdata,項目名稱:goodtables-py,代碼行數:19,代碼來源:inspector.py

示例11: run

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def run(self, arguments, endpoints=None, *args, **kwargs):
        """
        Return part of swagger object. This part contains "paths", "definitions" and "securityDefinitions"
        :return: dict
        """
        if endpoints is None:
            raise Py2SwaggerPluginException('Configuration is missed. Please add PLUGIN_SETTINGS[\'endpoints\'] to your '
                                            'configuration file.')

        for path, method, callback in endpoints:
            if isinstance(callback, six.string_types):
                callback = load_class(callback)
            self._introspect(path, method, callback)

        return {
            'paths': self._paths,
            'securityDefinitions': self._security_definitions
        } 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:20,代碼來源:simple.py

示例12: __init__

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def __init__(self, command, parent=None, ignoreFailure=False):
        """
        Construct command object.

        command: array of strings specifying command and arguments
                 Passing a single string is also supported if there are
                 no spaces within arguments (only between them).
        parent: parent object (should be ConfigObject subclass)
        """
        self.parent = parent
        self.ignoreFailure = ignoreFailure

        if type(command) == list:
            self.command = [str(v) for v in command]
        elif isinstance(command, six.string_types):
            self.command = command.split()

        # These are set after execute completes.
        self.pid = None
        self.result = None 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:22,代碼來源:command.py

示例13: writeFile

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def writeFile(filename, line, mode="a"):
    """Adds the following cfg (either str or list(str)) to this Chute's current
        config file (just stored locally, not written to file."""
    try:
        if isinstance(line, list):
            data = "\n".join(line) + "\n"
        elif isinstance(line, six.string_types):
            data = "%s\n" % line
        else:
            out.err("Bad line provided for %s\n" % filename)
            return
        fd = open(filename, mode)
        fd.write(data)
        fd.flush()
        fd.close()

    except Exception as e:
        out.err('Unable to write file: %s\n' % (str(e))) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:20,代碼來源:pdos.py

示例14: isValid

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def isValid(self):
        """
        Check if configuration is valid.

        Returns a tuple (True/False, None or str).
        """
        # Check required fields.
        for field in Dockerfile.requiredFields:
            if getattr(self.service, field, None) is None:
                return (False, "Missing required field {}".format(field))

        command = self.service.command
        if not isinstance(command, six.string_types + (list, )):
            return (False, "Command must be either a string or list of strings")

        packages = self.service.build.get("packages", [])
        if not isinstance(packages, list):
            return (False, "Packages must be specified as a list")
        for pkg in packages:
            if re.search(r"\s", pkg):
                return (False, "Package name ({}) contains whitespace".format(pkg))

        return (True, None) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:25,代碼來源:dockerfile.py

示例15: to_example

# 需要導入模塊: import six [as 別名]
# 或者: from six import string_types [as 別名]
def to_example(dictionary):
  """Helper: build tf.Example from (string -> int/float/str list) dictionary."""
  features = {}
  for (k, v) in six.iteritems(dictionary):
    if not v:
      raise ValueError("Empty generated field: %s" % str((k, v)))
    if isinstance(v[0], six.integer_types):
      features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
    elif isinstance(v[0], float):
      features[k] = tf.train.Feature(float_list=tf.train.FloatList(value=v))
    elif isinstance(v[0], six.string_types):
      if not six.PY2:  # Convert in python 3.
        v = [bytes(x, "utf-8") for x in v]
      features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
    elif isinstance(v[0], bytes):
      features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
    else:
      raise ValueError("Value for %s is not a recognized type; v: %s type: %s" %
                       (k, str(v[0]), str(type(v[0]))))
  return tf.train.Example(features=tf.train.Features(feature=features)) 
開發者ID:akzaidi,項目名稱:fine-lm,代碼行數:22,代碼來源:generator_utils.py


注:本文中的six.string_types方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。