Argument Parser error: "the following arguments are required:" - arguments

I am newer to coding and can't figure out what to fix about my code to make this run. The error that I keep getting is this:
usage: submit.py [-h] [--username USERNAME] [--password PASSWORD]
[--location LOCATION] [--dry-run] [--report REPORT]
[--https | --http]
assign [tasks ...]
submit.py: error: the following arguments are required: assign
Below is the snippet of my program that the error is referring to, namely the line parser.add_argument('assign', help=next(ihelp))
import argparse
parser = argparse.ArgumentParser()
helps = [ 'assignment name'
, 'numbers or ranges of problems/tasks to submit'
, 'your username (you can make one up)'
, 'your password (optional)'
, 'your geographical location (optional, used for mapping activity)'
, 'display tests without actually running them'
, 'specify where to send the results'
, 'use an encrypted connection to the grading server'
, 'use an unencrypted connection to the grading server'
]
ihelp = iter(helps)
parser.add_argument('assign', help=next(ihelp))
parser.add_argument('tasks', default=profile.get('TASKS',None), nargs='*', help=next(ihelp))
parser.add_argument('--username', '--login', default=profile.get('USERNAME',None), help=next(ihelp))
parser.add_argument('--password', default=profile.get('PASSWORD',None), help=next(ihelp))
parser.add_argument('--location', default=profile.get('LOCATION',None), help=next(ihelp))
parser.add_argument('--dry-run', default=False, action='store_true', help=next(ihelp))
parser.add_argument('--report', default=profile.get('REPORT',None), help=next(ihelp))
group = parser.add_mutually_exclusive_group()
group.add_argument('--https', dest="protocol", const="https", action="store_const", help=next(ihelp))
group.add_argument('--http', dest="protocol", const="http", action="store_const", help=next(ihelp))
parser.add_argument('--verbose', default=False, action='store_true', help=argparse.SUPPRESS)
parser.add_argument('--show-submission', default=False, action='store_true', help=argparse.SUPPRESS)
parser.add_argument('--show-feedback', default=False, action='store_true', help=argparse.SUPPRESS)
args = parser.parse_args()
asgn_name = os.path.splitext(args.assign)[0]
report = args.report
location = args.location
dry_run = args.dry_run
I have tried some things from the internet like changing the line into this: args = parser.parse_args(args) and I have tried adding a default=profile to the assign line like the rest of the parser lines, but that didn't change the error.
I would really welcome any help, as I need to get this fixed by tonight!

It really depends on what you are trying to do.
If all you want is to make it run then you can simply add nargs="?" to the assign argument declaration. This however will make the argument optional, which may or may not be your intention.
parser.add_argument('assign', help=next(ihelp), nargs="?", default=profile.get("Some Default Value"))

Related

Unexpected index error using choice module

I've been trying to use args in a function so that it can accept an unspecified amount of parameters but during testing I seem to be lumped with this error. Which seems to be produced by the choice module itself not the file i'm writing.
File "C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
Here is the code i'm trying to run:
def key_word_choice(key, *otherkeys):
key_choice = []
for items in sauces:
if key and otherkeys in items:
key_choice.append(items[0])
print("You should choose:", choice(key_choice))
key_word_choice('hot', 'garlic', 'buffalo')

Can I specify that an argument can't be used with a specific choice in Ansible module spec?

I'm looking for a way of specifying that a module argument can't be used if another argument has a certain value.
You can specify required_if to require an argument if another argument has a specific value but I need the opposite.
Something that's conceptually similar to mutually_exclusive and might be called forbidden_if.
I'm developing a module that creates a login for an SQL server. It can either be a SQL login that's specific to the server or a Windows log in that uses the domain controller.
For an SQL login you must specify a password for but you can't for Windows as this is set by the domain controller. Logins have an identifier (SID) that may be specified by the user for SQL logins but can't be for Window.
Although it's a Powershell module for a Windows host I'll use Python examples because that's what the documentation is in.
This is the spec for a module that creates an SQL login
module = AnsibleModule(
argument_spec=dict(
username=dict(type='str', required=True),
password=dict(type='str', no_log=True, required=True),
sid=dict(type='str', required=False),
),
supports_check_mode=True
)
and one for a Windows login
module = AnsibleModule(
argument_spec=dict(
username=dict(type='str', required=True),
),
supports_check_mode=True
)
This is my current attempt at a spec for a combined module
module = AnsibleModule(
argument_spec=dict(
username=dict(type='str', required=True),
password=dict(type='str', no_log=True, required=False),
sid=dict(type='str', required=False),
login_type=dict(
type='str',
choices=[ 'sql', 'windows' ],
default='sql',
required=False
)
),
required_if=[
('login_type', 'sql', ('password')),
],
supports_check_mode=True
)
I was able to make password required for the sql login_type. Since password and sid can't be specified for a windows login so I'd like to prevent them being used if login_type is windows. Is this possible and if so, how do I do it?
I don't see a solution to your problem without coding the test:
arguments = dict(
username=dict(type='str', required=True),
password=dict(type='str', no_log=True, required=False),
sid=dict(type='str', required=False),
login_type=dict(
type='str',
choices=[ 'sql', 'windows' ],
default='sql',
required=False
)
)
module = AnsibleModule(
argument_spec=arguments,
required_if=[
('login_type', 'sql', ('password',)),
],
supports_check_mode=True
)
if module.params['login_type'] == 'windows' and (module.params['password'] or module.params['sid']):
module.fail_json(msg="unable to use 'login_type=windows' with args 'password' or 'sid'")
FYI: I noticed an error in your code, you forgot the , in the test:
required_if=[
('login_type', 'sql', ('password'**,**)),
],
Result:
fatal: [localhost]: FAILED! => {"changed": false, "msg": "unable to use 'login_type=windows' with args 'password' or 'sid'"}

Suppress LightGBM warnings in Optuna

I am getting below warnings while I am using Optuna to tune my model.
Please tell me how to suppress these warnings?
[LightGBM] [Warning] feature_fraction is set=0.2, colsample_bytree=1.0 will be ignored. Current value: feature_fraction=0.2
[LightGBM] [Warning] min_data_in_leaf is set=5400, min_child_samples=20 will be ignored. Current value: min_data_in_leaf=5400
[LightGBM] [Warning] min_gain_to_split is set=13.203719815769512, min_split_gain=0.0 will be ignored. Current value: min_gain_to_split=13.203719815769512
I am not familiar with Optuna but I ran into this issue using Python/lightgbm.
As of v3.3.2, the parameters tuning page included parameters that seem to be renamed, deprecated, or duplicative. If, however, you stick to setting/tuning the parameters specified in the model object you can avoid this warning.
from lightgbm import LGBMRegressor
params = LGBMRegressor().get_params()
print(params)
These are the only parameters you want to set. If you want to be able to include all the parameters, you could do something like below.
from lightgbm import LGBMRegressor
lgr = LGBMRegressor()
params = lgr.get_params()
aliases = [
{'min_child_weight', 'min_sum_hessian_in_leaf'},
{'min_child_samples', 'min_data_in_leaf'},
{'colsample_bytree', 'feature_fraction'},
{'subsample', 'bagging_fraction'}
]
for alias in aliases:
if len(alias & set(params)) == 2:
arg = random.choice(sorted(alias))
params[arg] = None
lgr = LGBMRegressor(**params)
The code sets one or the other in each parameter pair that seems to be duplicative. Now, when you call lgr.fit(X, y) you should not get the warning.

Why does puppet think my custom fact is a string?

I am trying to create a custom fact I can use as the value for a class parameter in a hiera yaml file.
I am using the openstack/puppet-keystone module and I want to use fernet-keys.
According to the comments in the module I can use this parameter.
# [*fernet_keys*]
# (Optional) Hash of Keystone fernet keys
# If you enable this parameter, make sure enable_fernet_setup is set to True.
# Example of valid value:
# fernet_keys:
# /etc/keystone/fernet-keys/0:
# content: c_aJfy6At9y-toNS9SF1NQMTSkSzQ-OBYeYulTqKsWU=
# /etc/keystone/fernet-keys/1:
# content: zx0hNG7CStxFz5KXZRsf7sE4lju0dLYvXdGDIKGcd7k=
# Puppet will create a file per key in $fernet_key_repository.
# Note: defaults to false so keystone-manage fernet_setup will be executed.
# Otherwise Puppet will manage keys with File resource.
# Defaults to false
So wrote this custom fact ...
[root#puppetmaster modules]# cat keystone_fernet/lib/facter/fernet_keys.rb
Facter.add(:fernet_keys) do
setcode do
fernet_keys = {}
puts ( 'Debug keyrepo is /etc/keystone/fernet-keys' )
Dir.glob('/etc/keystone/fernet-keys/*').each do |fernet_file|
data = File.read(fernet_file)
if data
content = {}
puts ( "Debug Key file #{fernet_file} contains #{data}" )
fernet_keys[fernet_file] = { 'content' => data }
end
end
fernet_keys
end
end
Then in my keystone.yaml file I have this line:
keystone::fernet_keys: '%{::fernet_keys}'
But when I run puppet agent -t on my node I get this error:
Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Function Call, "{\"/etc/keystone/fernet-keys/1\"=>{\"content\"=>\"xxxxxxxxxxxxxxxxxxxx=\"}, \"/etc/keystone/fernet-keys/0\"=>{\"content\"=>\"xxxxxxxxxxxxxxxxxxxx=\"}}" is not a Hash. It looks to be a String at /etc/puppetlabs/code/environments/production/modules/keystone/manifests/init.pp:1144:7 on node mgmt-01
I had assumed that I had formatted the hash correctly because facter -p fernet_keys output this on the agent:
{
/etc/keystone/fernet-keys/1 => {
content => "xxxxxxxxxxxxxxxxxxxx="
},
/etc/keystone/fernet-keys/0 => {
content => "xxxxxxxxxxxxxxxxxxxx="
}
}
The code in the keystone module looks like this (with line numbers)
1142
1143 if $fernet_keys {
1144 validate_hash($fernet_keys)
1145 create_resources('file', $fernet_keys, {
1146 'owner' => $keystone_user,
1147 'group' => $keystone_group,
1148 'subscribe' => 'Anchor[keystone::install::end]',
1149 }
1150 )
1151 } else {
Puppet does not necessarily think your fact value is a string -- it might do, if the client is set to stringify facts, but that's actually beside the point. The bottom line is that Hiera interpolation tokens don't work the way you think. Specifically:
Hiera can interpolate values of any of Puppet’s data types, but the
value will be converted to a string.
(Emphasis added.)

Python error: one of the arguments is required

I'm trying to run a code from github that uses Python to classify images but I'm getting an error.
here is the code:
import argparse as ap
import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Get the path of the testing set
parser = ap.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--testingSet", help="Path to testing Set")
group.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
args = vars(parser.parse_args())
# Get the path of the testing image(s) and store them in a list
image_paths = []
if args["testingSet"]:
test_path = args["testingSet"]
try:
testing_names = os.listdir(test_path)
except OSError:
print "No such directory {}\nCheck if the file exists".format(test_path)
exit()
for testing_name in testing_names:
dir = os.path.join(test_path, testing_name)
class_path = imutils.imlist(dir)
image_paths+=class_path
else:
image_paths = [args["image"]]
and this is the error message I'm getting
usage: getClass.py [-h]
(- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test TESTINGSET | - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg IMAGE)
[- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset]
getClass.py: error: one of the arguments - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/--testingSet - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg/--image is required
can you please help me with this? where and how should I write the file path?
This is an error your own program is issuing. The message is not about the file path but about the number of arguments. This line
group = parser.add_mutually_exclusive_group(required=True)
says that only one of your command-line arguments (-t, -i) is permitted. But it appears from the error message that you are supplying both --testingSet and --image on your command line.
Since you only have 3 arguments, I have to wonder if you really need argument groups at all.
To get your command line to work, drop the mutually-exclusive group and add the arguments to the parser directly.
parser.add_argument("-t", "--testingSet", help="Path to testing Set")
parser.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')

Resources