本文整理匯總了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
示例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
示例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
#}}}
示例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
示例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)
示例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({})
示例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')
示例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')
示例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
示例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
示例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
}
示例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
示例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)))
示例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)
示例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))