I am using picocli to show the usage of my command-line application.
What I am not able to reach is to hide the name of the Java variable which appears in the printed output and from my point of view it looks so ugly.
This is the configutation of my CommandLine.Option:
#CommandLine.Option(
names = {"-a", "--abc"},
description = "Please, hide the Java variable name...")
private String xxx;
And this is how it is rendered:
-a, --abc=<xxx> Please, hide the Java variable name...
As you can see the name of the Java variable appears after the equal sign: <xxx>
I would like to hide it, like this:
-a, --abc Please, hide the Java variable name...
I checked the API but I could not see anything related to this.
Is there any way to turn it off?
The picocli annotations API does not provide for this, but it is possible to achieve this by overriding the Help API and plugging in your own option renderer. For example:
public class HideOptionParams {
#Option(names = {"-u", "--user"}, defaultValue = "${user.name}",
description = "The connecting user name.")
private String user;
#Option(names = {"-p", "--password"}, interactive = true,
description = "Password for the user.")
private String password;
#Option(names = {"-o", "--port"}, defaultValue = "12345",
description = "Listening port, default is ${DEFAULT-VALUE}.")
private int port;
public static void main(String[] args) {
CommandLine cmd = new CommandLine(new HideOptionParams());
cmd.setHelpFactory(new IHelpFactory() {
public Help create(final CommandSpec commandSpec, ColorScheme colorScheme) {
return new Help(commandSpec, colorScheme) {
#Override
public IOptionRenderer createDefaultOptionRenderer() {
return new IOptionRenderer() {
public Text[][] render(OptionSpec option,
IParamLabelRenderer ignored,
ColorScheme scheme) {
return makeOptionList(option, scheme);
}
};
}
};
}
});
cmd.usage(System.out);
}
private static Text[][] makeOptionList(OptionSpec option, ColorScheme scheme) {
String shortOption = option.shortestName(); // assumes every option has a short option
String longOption = option.longestName(); // assumes every option has a short and a long option
if (option.negatable()) { // ok to omit if you don't have negatable options
INegatableOptionTransformer transformer =
option.command().negatableOptionTransformer();
shortOption = transformer.makeSynopsis(shortOption, option.command());
longOption = transformer.makeSynopsis(longOption, option.command());
}
// assume one line of description text (may contain embedded %n line separators)
String[] description = option.description();
Text[] descriptionFirstLines = scheme.text(description[0]).splitLines();
Text EMPTY = Ansi.OFF.text("");
List<Text[]> result = new ArrayList<Text[]>();
result.add(new Text[]{
scheme.optionText(String.valueOf(
option.command().usageMessage().requiredOptionMarker())),
scheme.optionText(shortOption),
scheme.text(","), // we assume every option has a short and a long name
scheme.optionText(longOption), // just the option name without parameter
descriptionFirstLines[0]});
for (int i = 1; i < descriptionFirstLines.length; i++) {
result.add(new Text[]{EMPTY, EMPTY, EMPTY, EMPTY, descriptionFirstLines[i]});
}
// if #Command(showDefaultValues = true) was set, append line with default value
if (option.command().usageMessage().showDefaultValues()) {
Text defaultValue = scheme.text(" Default: " + option.defaultValueString(true));
result.add(new Text[]{EMPTY, EMPTY, EMPTY, EMPTY, defaultValue});
}
return result.toArray(new Text[result.size()][]);
}
}
This shows the following usage help message:
Usage: <main class> [-p] [-o=<port>] [-u=<user>]
-o, --port Listening port, default is 12345.
-p, --password Password for the user.
-u, --user The connecting user name.
Note that the parameter label is omitted in the options list, but is still shown in the synopsis. If you do not want any parameter labels shown in the synopsis, you can specify a custom synopsis in the #Command annotation, see this section in the user manual.
Related
my first question is here
however since I was advised that questions should not change the original matter I created a new one.
I am saving user settings and I would like to save it in the list, I have had a look on setting by James however I found that that its not possible to save it in the list. So ia have decided to use Xamarin Essentials.
First I tried to save only a string value, which after some struggle I managed to work out and now I am trying to save an object
static void AddToList(SettingField text)
{
var savedList = new List<SettingField>(Preference.SavedList);
savedList.Add(text);
Preference.SavedList = savedList;
}
private void ExecuteMultiPageCommand(bool value)
{
var recognitionProviderSettings = new RecognitionProviderSettings
{SettingFields = new List<SettingField>()};
var set = new SettingField()
{
ProviderSettingId = "test",
Value = "test"
};
AddToList(set);
NotifyPropertyChanged("IsMultiPage");
}
and then the sterilization and des
public static class Preference
{
private static SettingField _settingField;
public static List<SettingField> SavedList
{
get
{
//var savedList = Deserialize<List<string>>(Preferences.Get(nameof(SavedList), "tesr"));
var savedList = Newtonsoft.Json.JsonConvert.DeserializeObject<SettingField>(Preferences.Get(nameof(SavedList), _settingField)) ;
SavedList.Add(savedList);
return SavedList ?? new List<SettingField>();
}
set
{
var serializedList = Serialize(value);
Preferences.Set(nameof(SavedList), serializedList);
}
}
static T Deserialize<T>(string serializedObject) => JsonConvert.DeserializeObject<T>(serializedObject);
static string Serialize<T>(T objectToSerialize) => JsonConvert.SerializeObject(objectToSerialize);
}
}
But Preferences.Get doesn't take object, is there any other way how can I save my setting to a object list? Please advise
I would recommend you to use SecureStorage. You can save your strings only into it. So the place where you have serilized your object as json. Just convert your json to string with .ToString() and save it into secure storage.
You may continue saving your serialized json object as string in Shared preferences but it is recommended to use SecureStorage Instead.
So currently I'm trying to make a print feature for my Notepad application. I already have a kind of working Print feature, but it prints the full TextArea not only the string that is written into it.
I already tried to make it just print a string, but the PrintJob is not able to handle it, because it needs the actual TextArea, where the Text is written into.
My current Print Stuff:
public void doPrint() {
String toPrint = writeArea.getText();
printSetup(writeArea, Main.primaryStage);
}
private final Label jobStatus = new Label();
private void printSetup(Node node, Stage owner)
{
// Create the PrinterJob
PrinterJob job = PrinterJob.createPrinterJob();
if (job == null)
{
return;
}
// Show the print setup dialog
boolean proceed = job.showPrintDialog(owner);
if (proceed)
{
print(job, node);
}
}
private void print(PrinterJob job, Node node)
{
// Set the Job Status Message
jobStatus.textProperty().bind(job.jobStatusProperty().asString());
// Print the node
boolean printed = job.printPage(node);
if (printed)
{
job.endJob();
}
}
What I want to have:
A print that only shows the String, just like any other notepad application does if you try to print something
What I currently get:
The full textarea with frame.
As I mentioned in the comment you can wrap it into a Text, but then the first line for some reason isn't displayed correctly.
The solution would be to use a Label instead like:
printSetup(new Label(toPrint), Main.primaryStage);
Right now I cant even compile this program. Im trying to write a program that takes a inputted string and then encrypts the letters by swapping them out with another letter predetermined in a array and then shows you again the original text. any help would be appreciated.
import java.util.Scanner;
public class Array {
private char [] alphabet = new char [25];
private char [] crypt = new char [25];
String oldMessage;
public Array()
{ char[] alphabet = "abcdefghijklmnoptqrstuvwxyz".toCharArray();
char[] crypt = "qwertyuiopasdfghjklzxcvbnm|".toCharArray();
}
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a message that you would like to encrypt\n");
oldMessage = scan.nextLine();
String newMessage = "";
for (int i=0; i<oldMessage.length(); ++i) {
int index = alphabet.indexOf(old.charAt(i));
if (index == -1)
newMessage +="?";
else
newMessage += crypt.charAt(index);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {Array myApplication = new Array(); myApplication.run();}
First off, when encountering errors, it's always best to include the error in your question--often it will point you right to the source of the error. What does your compiler say when the build fails?
Next, I'm on my phone right now and can't verify that I've found all the problems, but remember that strings in Java are immutable, meaning that they can't be changed after creation. This means that you can't append to them in the way you're doing. Try using the StringBuilder class to accomplish what you're looking for here, or filling a new array as you go and converting to String at the end.
Also, it looks like you're missing two end braces (the for loop and the run method).
From static method run() you are referring to non-static variables like alphabet, crypt, oldMessage.
This is first that comes into mind
When registering a custom language service extension, Visual Studio creates a new options entry for the language within the Text Editor node (in the Visual Studio options dialog). Beneath that node two default nodes are created named General and Tabs, whereby the General tab contains statement completion and display settings...
In the Dispay group there are three options; one of them is the Navigation Bar checkbox (which shows/hides the editor´s navigation bar). For my custom language service, this option is disabled. Of course, it´s not implemented yet.
I would like to know, what I have to do, to provide a navigation bar for my custom editor... I guess that there is a certain interface I have to implement in the editor´s factory, or the language service package must export a certain MEF component, or, or, ...
Jon Senchyna´s answer guided me into the right direction. The OnSynchronizeDropdowns method gets never called (the SDK documentation is just wrong in that case). What did the final trick was to override at least GetComboAttributes, GetEntryAttributes and GetEntryText to get text-only items for both combo boxes...
[ComVisible(true)]
public sealed class CustomTypeAndMemberDropdownBars : TypeAndMemberDropdownBars
{
private readonly IList<string> declarations;
private readonly IList<string> members;
public CustomTypeAndMemberDropdownBars(
LanguageService languageService,
IVsTextView view)
: base(languageService)
{
// TODO: initialize declarations and members from the given text view...
this.declarations = ...
this.members = ...
}
private enum ComboIndex
{
Types = 0,
Members = 1
}
public override int GetComboAttributes(
int combo,
out uint entries,
out uint entryType,
out IntPtr imageList)
{
entries = 0;
imageList = IntPtr.Zero;
entryType = (uint)DROPDOWNENTRYTYPE.ENTRY_TEXT;
var comboType = (ComboIndex)combo;
switch (comboType)
{
case ComboIndex.Types:
entries = (uint)this.declarations.Count();
break;
case ComboIndex.Members:
entries = (uint)this.members.Count();
break;
}
return VSConstants.S_OK;
}
public override int GetEntryAttributes(
int combo,
int entry,
out uint fontAttrs)
{
fontAttrs = (uint)DROPDOWNFONTATTR.FONTATTR_PLAIN;
return VSConstants.S_OK;
}
public override int GetEntryText(
int combo,
int entry,
out string text)
{
text = null;
var comboType = (ComboIndex)combo;
switch (comboType)
{
case ComboIndex.Types:
text = this.declarations[entry];
break;
case ComboIndex.Members:
text = this.members[entry];
break;
}
return VSConstants.S_OK;
}
public override bool OnSynchronizeDropdowns(
LanguageService languageService,
IVsTextView textView,
int line,
int col,
ArrayList dropDownTypes,
ArrayList dropDownMembers,
ref int selectedType,
ref int selectedMember)
{
return false;
}
}
I believe the following steps should be what you need:
In your Package class, set the ShowDropDownOptions property to true in the ProvideLanguageService attribute
Create a class that implements TypeAndMemberDropdownBars
In your LanguageService class, implement the CreateDropDownHelper function and have it return an instance of your TypeAndMemberDropdownBars
The Goal is to have a list of options (that a user can chose through radio buttons) in one place(for eg: a yaml config file). No other place should have this list hard-coded
I've done something similar to create select elements, and I think enums worked just fine. Doing radio buttons should be very similar. I've set it up so that the labels can be defined in the messages file. I'm going to try to excerpt the relevant portions from my larger auto-form-generation code (using FastTags) the best I can. It's a bit heavy for this one case but it makes sense in the larger system.
I use the tag like #{form.selector 'order.status' /}, which looks find the variable named order in the template, sees that status is declared as public Status status, and then goes to find all the values of the Status enum and generate options for them in the select element.
First, I use a FieldContext object which just contains a bunch of info that's used by the other code to determine what to generate along with some utility methods:
public class FieldContext {
public final Map<?,?> args;
public final ExecutableTemplate template;
public final int fromLine;
public Class clazz = null;
public Field field = null;
public Object object = null;
public Object value = null;
private Map<String,String> attrs = new HashMap<String,String>();
private Map<String,Boolean> printed = new HashMap<String,Boolean>();
private List<Option> options;
...
Then I have this in another helper class (its info gets added to the FieldContext):
public List<Option> determineOptions(FieldContext context) {
List<Option> options = new ArrayList<Option>();
if (context.field.getType().isEnum()) {
for (Object option : context.field.getType().getEnumConstants()) {
options.add(new Option(option.toString(), Message.get(option.toString())));
}
}
return options;
}
then the tag declaration is
public static void _selector(Map<?,?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
String field_name = args.get("arg").toString();
TagContext.current().data.put("name", field_name);
SelectHelper helper = HelperFactory.getHelper(SelectHelper.class);
try {
FieldContext context = new FieldContext(field_name, args, template, fromLine);
helper.autoconfigure(context);
TagContext.current().data.put("selected", helper.determineValue(context));
out.print("<div class=\"formutil-field formutil-selector\">");
out.print("<label for=\"" + context.getAttr("id") + "\">");
out.print(helper.findOrCreateLabel(context));
out.print("</label>");
out.print("<select");
context.printAttribute(out, "id", "name");
out.print(">");
if (context.hasOptions()) {
for (Option option : context.getOptions()) {
out.print("<option value=\"" + option.value + "\">" + option.label + "</option>");
}
}
out.print("</select>");
context.printErrorIfPresent(out);
context.printValidationHints(out);
out.println("</div>");
}
...
}