本文整理汇总了Python中pydoc.locate方法的典型用法代码示例。如果您正苦于以下问题:Python pydoc.locate方法的具体用法?Python pydoc.locate怎么用?Python pydoc.locate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydoc
的用法示例。
在下文中一共展示了pydoc.locate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_builtin
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def test_builtin(self):
for name in ('str', 'str.translate', '__builtin__.str',
'__builtin__.str.translate'):
# test low-level function
self.assertIsNotNone(pydoc.locate(name))
# test high-level function
try:
pydoc.render_doc(name)
except ImportError:
self.fail('finding the doc of {!r} failed'.format(o))
for name in ('not__builtin__', 'strrr', 'strr.translate',
'str.trrrranslate', '__builtin__.strrr',
'__builtin__.str.trrranslate'):
self.assertIsNone(pydoc.locate(name))
self.assertRaises(ImportError, pydoc.render_doc, name)
示例2: test_builtin
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def test_builtin(self):
for name in ('str', 'str.translate', '__builtin__.str',
'__builtin__.str.translate'):
# test low-level function
self.assertIsNotNone(pydoc.locate(name))
# test high-level function
try:
pydoc.render_doc(name)
except ImportError:
self.fail('finding the doc of {!r} failed'.format(name))
for name in ('not__builtin__', 'strrr', 'strr.translate',
'str.trrrranslate', '__builtin__.strrr',
'__builtin__.str.trrranslate'):
self.assertIsNone(pydoc.locate(name))
self.assertRaises(ImportError, pydoc.render_doc, name)
示例3: test_keras_autoencoder_scoring
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def test_keras_autoencoder_scoring(model, kind, n_features_out):
"""
Test the KerasAutoEncoder and KerasLSTMAutoEncoder have a working scoring function
"""
Model = pydoc.locate(f"gordo.machine.model.models.{model}")
model = Pipeline([("model", Model(kind=kind))])
X = np.random.random((8, 2))
# Should be able to deal with y output different than X input features
y = np.random.random((8, n_features_out))
with pytest.raises(NotFittedError):
model.score(X, y)
model.fit(X, y)
score = model.score(X, y)
logger.info(f"Score: {score:.4f}")
示例4: resolve
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def resolve(clz, module=None):
"""Resolve the configurable type."""
unresolve = 'could not resolve type `{}`'
notsubclass = 'resolved type {} is not subclass of {}'
ctype = pydoc.locate(clz)
if not ctype and module:
if isinstance(module, six.string_types):
clz = module + '.' + clz
else: # use it as a module
clz = module.__name__ + '.' + clz
ctype = resolve(clz)
if not ctype:
raise RuntimeError(unresolve.format(clz))
if not issubclass(ctype, Configurable):
raise RuntimeError(notsubclass.format(str(ctype), str(Configurable)))
return ctype
示例5: __load_functions__
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def __load_functions__ (symtbl):
"""Loads all Python functions from the module specified in the
``functions`` configuration parameter (in config.yaml) into the given
symbol table (Python dictionary).
"""
modname = ait.config.get('functions', None)
if modname:
module = pydoc.locate(modname)
if module is None:
msg = 'No module named %d (from config.yaml functions: parameter)'
raise ImportError(msg % modname)
for name in dir(module):
func = getattr(module, name)
if callable(func):
symtbl[name] = func
示例6: create_bot
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def create_bot(flags=TEST_FLAGS, return_dataset=False):
"""Chatbot factory: Creates and returns a fresh bot. Nice for
testing specific methods quickly.
"""
# Wipe the graph and update config if needed.
tf.reset_default_graph()
config = io_utils.parse_config(flags=flags)
io_utils.print_non_defaults(config)
# Instantiate a new dataset.
print("Setting up", config['dataset'], "dataset.")
dataset_class = locate(config['dataset']) \
or getattr(data, config['dataset'])
dataset = dataset_class(config['dataset_params'])
# Instantiate a new chatbot.
print("Creating", config['model'], ". . . ")
bot_class = locate(config['model']) or getattr(chatbot, config['model'])
bot = bot_class(dataset, config)
if return_dataset:
return bot, dataset
else:
return bot
示例7: test_builtin
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def test_builtin(self):
for name in ('str', 'str.translate', 'builtins.str',
'builtins.str.translate'):
# test low-level function
self.assertIsNotNone(pydoc.locate(name))
# test high-level function
try:
pydoc.render_doc(name)
except ImportError:
self.fail('finding the doc of {!r} failed'.format(name))
for name in ('notbuiltins', 'strrr', 'strr.translate',
'str.trrrranslate', 'builtins.strrr',
'builtins.str.trrranslate'):
self.assertIsNone(pydoc.locate(name))
self.assertRaises(ImportError, pydoc.render_doc, name)
示例8: _ensure_loaded
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def _ensure_loaded(connector_list):
"""Loads everything in a given path.
This will make sure all classes have been loaded and therefore all
decorators have registered class.
:param start_path: The starting path to load.
"""
classes = []
for conn in connector_list:
try:
conn_class = locate(conn)
classes.append(conn_class)
except Exception:
pass
return classes
示例9: config_get
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def config_get(self, op, key, definition):
# TODO De-duplicate code from dffml/base.py
try:
value = traverse_config_get(self.extra_config, key)
except KeyError as error:
raise MissingConfig("%s missing %s" % (op.name, key))
# TODO Argparse nargs and Arg and primitives need to be unified
if "Dict" in definition.primitive:
# TODO handle Dict / spec completely
self.logger.critical(
"Dict / spec'd arguments are not yet completely handled"
)
value = json.loads(value[0])
else:
typecast = pydoc.locate(
definition.primitive.replace("List[", "").replace("]", "")
)
# TODO This is a oversimplification of argparse's nargs
if definition.primitive.startswith("List["):
value = list(map(typecast, value))
else:
value = typecast(value[0])
if typecast is str and value in ["True", "False"]:
raise MissingConfig("%s missing %s" % (op.name, key))
return value
示例10: queue_page
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def queue_page(model_import, job_import, worker_count, offset):
"""
Spool a page of model instances for a job.
Args:
model_import (str)
job_import (str)
worker_count (int)
offset (int)
"""
# Import callables.
model = locate(model_import)
job = locate(job_import)
for row in model.page_cursor(worker_count, offset):
config.rq.enqueue(job, row.id)
示例11: __init__
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def __init__(self, params):
super(DecodeText, self).__init__(params)
self._unk_mapping = None
self._unk_replace_fn = None
if self.params["unk_mapping"] is not None:
self._unk_mapping = _get_unk_mapping(self.params["unk_mapping"])
if self.params["unk_replace"]:
self._unk_replace_fn = functools.partial(
_unk_replace, mapping=self._unk_mapping)
self._postproc_fn = None
if self.params["postproc_fn"]:
self._postproc_fn = locate(self.params["postproc_fn"])
if self._postproc_fn is None:
raise ValueError("postproc_fn not found: {}".format(
self.params["postproc_fn"]))
开发者ID:akanimax,项目名称:natural-language-summary-generation-from-structured-data,代码行数:19,代码来源:decode_text.py
示例12: _create_decoder
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def _create_decoder(self, encoder_output, features, _labels):
attention_class = locate(self.params["attention.class"]) or \
getattr(decoders.attention, self.params["attention.class"])
attention_layer = attention_class(
params=self.params["attention.params"], mode=self.mode)
# If the input sequence is reversed we also need to reverse
# the attention scores.
reverse_scores_lengths = None
if self.params["source.reverse"]:
reverse_scores_lengths = features["source_len"]
if self.use_beam_search:
reverse_scores_lengths = tf.tile(
input=reverse_scores_lengths,
multiples=[self.params["inference.beam_search.beam_width"]])
return self.decoder_class(
params=self.params["decoder.params"],
mode=self.mode,
vocab_size=self.target_vocab_info.total_size,
attention_values=encoder_output.attention_values,
attention_values_length=encoder_output.attention_values_length,
attention_keys=encoder_output.outputs,
attention_fn=attention_layer,
reverse_scores_lengths=reverse_scores_lengths)
开发者ID:akanimax,项目名称:natural-language-summary-generation-from-structured-data,代码行数:27,代码来源:attention_seq2seq.py
示例13: run_service
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def run_service(service_name, params):
logger.info('run_service %s with %s', service_name, params)
service = get_service(service_name)
if not service:
raise Exception('Service not found {}'.format(service_name))
# locate the service implementation
Service = locate(service.get('engine'))
# load the default parameter values from the service definition
parameters = {}
definition = service.get('input', {})
for k, v in definition.items():
if 'default' in v:
parameters[k] = v.get('default')
# merge with the given parameters
if params:
parameters.update(params)
service = Service(parameters, service=service)
if not service.execute:
raise Exception('Service {} does not have an "execute" method at {}'.format(service_name, service.engine))
return service.execute()
示例14: transform_and_save_embedding
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def transform_and_save_embedding(self):
"""
Transforming the numpy array with real and imaginary values.
Creating a pandas dataframe and saving it as a csv.
"""
print("\nSaving the embedding.")
features = [self.real_and_imaginary.real, self.real_and_imaginary.imag]
self.real_and_imaginary = np.concatenate(features, axis=1)
columns_1 = ["reals_"+str(x) for x in range(self.settings.sample_number)]
columns_2 = ["imags_"+str(x) for x in range(self.settings.sample_number)]
columns = columns_1 + columns_2
self.real_and_imaginary = pd.DataFrame(self.real_and_imaginary, columns=columns)
self.real_and_imaginary.index = self.index
self.real_and_imaginary.index = self.real_and_imaginary.index.astype(locate(self.settings.node_label_type))
self.real_and_imaginary = self.real_and_imaginary.sort_index()
self.real_and_imaginary.to_csv(self.settings.output)
示例15: setUp
# 需要导入模块: import pydoc [as 别名]
# 或者: from pydoc import locate [as 别名]
def setUp(self):
self.models = {}
with open("models.json") as json_file:
data = json.load(json_file)
for mdl_json in data["models_database"]:
model = locate("models." + mdl_json["run"])
model.set_up()
self.models[mdl_json["name"]] = get_env()