当前位置: 首页>>代码示例>>Python>>正文


Python app.UsageError方法代码示例

本文整理汇总了Python中absl.app.UsageError方法的典型用法代码示例。如果您正苦于以下问题:Python app.UsageError方法的具体用法?Python app.UsageError怎么用?Python app.UsageError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在absl.app的用法示例。


在下文中一共展示了app.UsageError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(_):
  if len(sys.argv) < 3:
    raise app.UsageError('Must pass at least two arguments, font file or font'
                         ' dir to diff')

  font1 = sys.argv[1]
  font2 = sys.argv[2]
  dirs = os.path.isdir(font1) and os.path.isdir(font2)
  files = os.path.isfile(font1) and os.path.isfile(font2)

  if not dirs and not files:
    print('%s and %s must both point to directories or font files' % (
        font1, font2))
    sys.exit(1)

  if dirs:
    CompareDirs(font1, font2)

  if files:
    CompareFiles(font1, font2) 
开发者ID:googlefonts,项目名称:gftools,代码行数:22,代码来源:gftools-compare-font.py

示例2: validate_args

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def validate_args(argv):
  """Validates the input arguments. Raises a UsageError if invalid."""
  valid_commands = ["up", "down", "print", "reload"]
  error = ""
  if len(argv) < 2:
    error = ("Command not provided. "
             "Command must be one of %s" % valid_commands)
  elif argv[1] not in valid_commands:
    error = "Command must be one of %s" % valid_commands

  if len(argv) > 3:
    print("Too many arguments.")

  if len(argv) == 3:
    valid_targets = ["trainer", "decoder", "tensorboard", "all"]
    if argv[2] not in valid_targets:
      error = "Target must be one of %s" % valid_targets

  if error:
    raise app.UsageError(error) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:22,代码来源:gke_launch.py

示例3: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  # Datasets.
  preprocessed_train_dataset, preprocessed_test_dataset = (
      _load_and_preprocess_datasets())

  # Train and Evaluate Model.
  model = _train_and_evaluate(
      preprocessed_train_dataset,
      preprocessed_test_dataset,
      epochs=FLAGS.epochs)

  # Save Model.
  _save(model, FLAGS.path_to_save_model_checkpoint) 
开发者ID:tensorflow,项目名称:federated,代码行数:18,代码来源:train_emnist_classifier_model.py

示例4: tokenize

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def tokenize(ds, dataset_name):
  """Tokenizes a line into words with alphanum characters."""

  def extract_strings(example):
    if dataset_name == 'shakespeare':
      return tf.expand_dims(example['snippets'], 0)
    elif dataset_name == 'stackoverflow':
      return example['tokens']
    else:
      raise app.UsageError('Dataset not supported: ', dataset_name)

  def tokenize_line(line):
    return tf.data.Dataset.from_tensor_slices(tokenizer.tokenize(line)[0])

  def mask_all_symbolic_words(word):
    return tf.math.logical_not(
        tf_text.wordshape(word, tf_text.WordShape.IS_PUNCT_OR_SYMBOL))

  tokenizer = tf_text.WhitespaceTokenizer()
  ds = ds.map(extract_strings)
  ds = ds.flat_map(tokenize_line)
  ds = ds.map(tf_text.case_fold_utf8)
  ds = ds.filter(mask_all_symbolic_words)
  return ds 
开发者ID:tensorflow,项目名称:federated,代码行数:26,代码来源:heavy_hitters_utils.py

示例5: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  # x = np.arange(-3.0, 3.0, 0.01)
  # x = np.random.uniform(-0.01, 0.01, size=1000)
  x = np.random.uniform(-10.0, 10.0, size=1000)
  # x = np.random.uniform(-1, 1, size=1000)
  x = np.sort(x)
  tr = np.zeros_like(x)
  t = np.zeros_like(x)
  iter_count = 500
  for _ in range(iter_count):
    y = _ternary(x)
    yr = _ternary(x, sto=True)
    t = t + y
    tr = tr + yr

  plt.plot(x, t/iter_count)
  plt.plot(x, tr/iter_count)
  plt.ylabel('mean (%s samples)' % iter_count)
  plt.show() 
开发者ID:google,项目名称:qkeras,代码行数:24,代码来源:example_ternary.py

示例6: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  flags.mark_flag_as_required('prediction_file')

  sources, predictions, target_lists = score_lib.read_data(
      FLAGS.prediction_file, FLAGS.case_insensitive)
  logging.info(f'Read file: {FLAGS.prediction_file}')
  exact = score_lib.compute_exact_score(predictions, target_lists)
  sari, keep, addition, deletion = score_lib.compute_sari_scores(
      sources, predictions, target_lists)
  print(f'Exact score:     {100*exact:.3f}')
  print(f'SARI score:      {100*sari:.3f}')
  print(f' KEEP score:     {100*keep:.3f}')
  print(f' ADDITION score: {100*addition:.3f}')
  print(f' DELETION score: {100*deletion:.3f}') 
开发者ID:google-research,项目名称:lasertagger,代码行数:18,代码来源:score_main.py

示例7: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  recall_values = {}
  for setting in ['static', 'dynamic']:
    recall = []
    for seed in range(FLAGS.num_trials):
      with file_util.open(
          os.path.join(FLAGS.source_path, str(seed), 'cumulative_recall_%s.txt')
          % setting, 'r') as infile:
        recall.append(np.loadtxt(infile))
      recall_values[setting] = np.vstack(recall)

  lending_plots.plot_cumulative_recall_differences(
      recall_values,
      path=os.path.join(FLAGS.plotting_dir, 'combined_simpsons_paradox.pdf')) 
开发者ID:google,项目名称:ml-fairness-gym,代码行数:19,代码来源:aggregate_lending_recall_values.py

示例8: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  # TODO(): add tests to check correct plots generated.
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  deltas = None

  # Casting to float since these are sometimes passed through flags as strings.
  feature_mu = [float(mu) for mu in FLAGS.feature_mu]
  if FLAGS.noisy_features or FLAGS.noisy_threshold:
    results, thresholds, deltas, stdevs = run_noisy_experiment(
        noise_dist=FLAGS.noisy_dist,
        noisy_features=FLAGS.noisy_features,
        noisy_threshold=FLAGS.noisy_threshold,
        feature_mu=feature_mu)
    plot_deltas(deltas)
    for sd in stdevs:
      plot_thresholds(results[sd], thresholds, name=sd)
      plot_metrics(results[sd], thresholds, name=sd)

  else:
    results, thresholds = run_baseline_experiment(FLAGS.feature_mu)
    results_noise, _, _, _ = run_noisy_experiment(
        noisy_features=True, stdevs=[0.1])
    plot_threshold_pair([results, results_noise[0.1]],
                        ['Noiseless Features', 'Noisy Features'], thresholds) 
开发者ID:google,项目名称:ml-fairness-gym,代码行数:27,代码来源:college_admission_main.py

示例9: _main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def _main(argv):
  """Main function for invoking the `nsl.tools.build_graph` function."""
  flag = flags.FLAGS
  flag.showprefixforinfo = False
  if len(argv) < 3:
    raise app.UsageError(
        'Invalid number of arguments; expected 2 or more, got %d' %
        (len(argv) - 1))

  build_graph_from_config(
      argv[1:-1], argv[-1],
      nsl_configs.GraphBuilderConfig(
          id_feature_name=flag.id_feature_name,
          embedding_feature_name=flag.embedding_feature_name,
          similarity_threshold=flag.similarity_threshold,
          lsh_bits=flag.lsh_bits,
          random_seed=flag.random_seed)) 
开发者ID:tensorflow,项目名称:neural-structured-learning,代码行数:19,代码来源:build_graph.py

示例10: _main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def _main(argv):
  """Main function for invoking the `nsl.tools.pack_nbrs` function."""
  flag = flags.FLAGS
  flag.showprefixforinfo = False
  # Check that the correct number of arguments have been provided.
  if len(argv) != 5:
    raise app.UsageError('Invalid number of arguments; expected 4, got %d' %
                         (len(argv) - 1))

  pack_nbrs(
      labeled_examples_path=argv[1],
      unlabeled_examples_path=argv[2],
      graph_path=argv[3],
      output_training_data_path=argv[4],
      add_undirected_edges=flag.add_undirected_edges,
      max_nbrs=flag.max_nbrs,
      id_feature_name=flag.id_feature_name) 
开发者ID:tensorflow,项目名称:neural-structured-learning,代码行数:19,代码来源:pack_nbrs.py

示例11: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  global users
  global private_key

  with open(FLAGS.passwd) as f:
    users = json.load(f)

  logging.info('Loaded: %s', users.keys())

  # Note you really shouldn't have multiple keys in the jwks, as we will only use the last one.
  with open(FLAGS.jwk) as f:
    jwks = json.load(f)
    for key in jwks['keys']:
      private_key = (key['kid'], jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(key)))


  api.run(host='0.0.0.0', port=FLAGS.port) 
开发者ID:google,项目名称:android-emulator-container-scripts,代码行数:22,代码来源:jwt-provider.py

示例12: Run

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def Run(main: Callable[[], None]):
  """Begin executing the program.

  Args:
    main: The main function to execute. It takes no arguments. If any command
    line arguments remain after flags parsing, an error is raised. If it
    returns an integer, it is used as the process's exit code.
  """

  def RunWithoutArgs(argv: List[str]):
    """Run the given function without arguments."""
    if len(argv) > 1:
      raise UsageError("Unknown arguments: '{}'.".format(" ".join(argv[1:])))
    main()

  RunWithArgs(RunWithoutArgs)


# Logging functions. 
开发者ID:ChrisCummins,项目名称:clgen,代码行数:21,代码来源:app.py

示例13: main

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  export_path = FLAGS.export_path
  if os.path.exists(export_path):
    raise ValueError(f'Export_path {export_path} already exists. Please '
                     'specify a different path or delete the existing one.')

  module = _ExtractModule(FLAGS.block3_strides, FLAGS.iou)

  # Load the weights.
  checkpoint_path = FLAGS.ckpt_path
  module.LoadWeights(checkpoint_path)
  print('Checkpoint loaded from ', checkpoint_path)

  # Save the module
  tf.saved_model.save(module, export_path) 
开发者ID:tensorflow,项目名称:models,代码行数:20,代码来源:export_model.py

示例14: __init__

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def __init__(
      self, app_servers, build_target, deployment_type, loaner_path, version,
      web_app_dir, yaml_files):
    super(AppEngineServerConfig, self).__init__(deployment_type, loaner_path)
    self._build_target = build_target
    self._version = version
    self._web_app_dir = web_app_dir
    self._yaml_files = yaml_files
    self._app_servers = _ParseAppServers(app_servers)
    if self._deployment_type not in list(self._app_servers.keys()):
      raise app.UsageError(
          'Application name provided is not in the list of App Servers.\n'
          'Please check the name and/or the deploy.sh configuration.') 
开发者ID:google,项目名称:loaner,代码行数:15,代码来源:deploy_impl.py

示例15: testAppEngineServerConfigWithMissingDeploymentServer

# 需要导入模块: from absl import app [as 别名]
# 或者: from absl.app import UsageError [as 别名]
def testAppEngineServerConfigWithMissingDeploymentServer(self):
    """Test a deployment server that is not in appservers, raises UsageError."""
    with self.assertRaises(app.UsageError):
      self.CreateTestAppEngineConfig(deployment_type='not_real_server') 
开发者ID:google,项目名称:loaner,代码行数:6,代码来源:deploy_impl_test.py


注:本文中的absl.app.UsageError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。