Separate each entry of brace-enclosed lists with new-line via clang-format - clang-format

I have brace-enclosed lists to initialize an array. I'd like to have my array initializers new-line for each entry of the array, which looks like:
const char* const array_of_strings[] = {
"Hey",
"Hi",
"Hello",
"Soup",
"Atom"
};
Though, clang-format formats this array to:
const char *const array_of_strings[] = {"Hey", "Hi", "Hello", "Soup", "Atom"};
usually new lining once the list gets past ColumnLimit. Is my wanted formatting possible using clang-format?

It is mostly possible. You need two things:
Set the BinPackArguments style option to false. I guess clang-format is treating the brace-enclosed initializer list as arguments. (The documentation doesn't really specify this, but it seems reasonable.)
Use the comma-after-last-item feature. To do this, add a comma between "Atom" and the closing brace. This feature is not documented anywhere that I've seen, but it has been in clang-format for many versions and many years.
With both of the above, and otherwise default clang-format settings, your output would look like:
const char *const array_of_strings[] = {
"Hey",
"Hi",
"Hello",
"Soup",
"Atom",
};

Related

How does the parsing of variables in Yocto work?

There are some variables that I just use without knowing what it does. Could someone explain the logic behind all these parsing in Yocto?
What does the underscore do? What are the available arguments other than _append_pn?
PACKAGECONFIG_append_pn-packagename = " packagename"
PREFERRED_VERSION_linux-imx_mx6 = "3.10.17"
SRC_URI_append_toolchain-clang = " file://0004-Remove-clang-unsupported-compiler-flags.patch "
EXTRA_OECONF_append_arm = " --enable-fpm=arm"
How about this one? I know that adding in this way is to single out a package, but how does it work?
LICENSE_FLAGS_WHITELIST_append = " commerical_packagename"
Someone also mentioned something weird with this that worked for them: bitbake: how to add package depending on MACHINE?
IMAGE_INSTALL_append_machine1 += " package1"
The documentation covers this pretty well: https://www.yoctoproject.org/docs/latest/bitbake-user-manual/bitbake-user-manual.html#basic-syntax
The longer version is that _ introduces an override, which is a way of saying "do something special" instead of just assigning.
Some are operations such as append and prepend.
FOO = "1"
FOO_append = "2"
FOO is now "12" as 2 was appended to 1.
(_prepend does what you'd expect)
_remove can be used to remove items from a whitespace-separated list.
FOO = "1 2 3"
FOO_remove = "2"
FOO is now "1 3".
pn_[foo] is an override for a specific recipe name (historical naming, it means package name, but actually refers to the recipe). So your local.conf can do:
EXTRA_OEMAKE_pn-foo = "bar"
And you've just set EXTRA_OEMAKE for the foo recipe, and just the foo recipe.
There are other overrides. The architectures all have overrides, so _arm _x86 _mips etc specify that an assignment is specific to those architectures.

Tidy long string in Ruby

I have a method in Ruby, which needs an API URL:
request_url = "http://api.abc.com/v3/avail?rev=#{ENV['REV']}&key=#{ENV['KEY']}&locale=en_US&currencyCode=#{currency}&arrivalDate=#{check_in}&departureDate=#{check_out}&includeDetails=true&includeRoomImages=true&room1=#{total_guests}"
I want to format it to be more readable. It should take arguments.
request_url = "http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}"
But of course there's line break. I tried heredoc, but I want it to be in one line.
I would prefer to not build URI queries by joining strings, because that might lead to URLs that are not correctly encoded (see a list of characters that need to be encoded in URIs).
There is the Hash#to_query method in Ruby on Rails that does exactly what you need and it ensure that the parameters are correctly URI encoded:
base_url = 'http://api.abc.com/v3/avail'
arguments = {
rev: ENV['REV'],
key: ENV['KEY'],
locale: 'en_US',
currencyCode: currency,
arrivalDate: check_in,
departureDate: check_out,
includeDetails: true,
includeRoomImages: true,
room1: total_guests
}
request_url = "#{base_url}?#{arguments.to_query}"
You could use an array and join the strings:
request_url = [
"http://api.abc.com/v3/avail?",
"&rev=#{ENV['REV']}",
"&key=#{ENV['KEY']}",
"&locale=en_US",
"&currencyCode=#{currency}",
"&arrivalDate=#{check_in}",
"&departureDate=#{check_out}",
"&includeDetails=true",
"&includeRoomImages=true",
"&room1=#{total_guests}",
].join('')
Even easier, you can use the %W array shorthand notation so you don't have to write out all the quotes and commas:
request_url = %W(
http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}
).join('')
Edit: Of course, spickermann makes a very good point above on better ways to accomplish this specifically for URLs. However, if you're not constructing a URL and just working with strings, the above methods should work fine.
You can extend strings in Ruby using the line continuation operator. Example:
request_url = "http://api.abc.com/v3/avail?" \
"&rev=#{ENV['REV']}" \
"&key=#{ENV['KEY']}"

How do I get lua string match to parse an environment variable string?

I have a config file parser written in lua.
I'd like to detect values that are environment variables and change them with os.getenv.
It's probably a bit ambitious because I can have values like
"a string with an embedded ${VARIABLE} in here"
or
"another string with an env $VARIABLE"
And I should probably allow escaping them with double $$ to allow a literal $.
How do I do this?
This is what I have so far, but it isn't right
local envvar = string.match(value, "%$([%w_]+)")
if envvar then
print("Envvar=", envvar)
value = value:gsub("(%$[%w_]+)", os.getenv(envvar))
end
For example, I can't figure out how to use the %b balance option here to properly match { } combinations. And make them optional. How do I make this work robustly?
In fact, I realise it's probably more complicated than this. What if more than one environment variable was specified?
local text = [[
Example: ${LANG}, $TEXTDOMAINDIR, $$10.00, $$LANG, $UNDEFINED
Nested braces: {{${SHELL}}}
]]
text = text:gsub('$%$','\0')
:gsub('${([%w_]+)}', os.getenv)
:gsub('$([%w_]+)', os.getenv)
:gsub('%z','$')
print(text)
--> Example: en_US.UTF-8, /usr/share/locale/, $10.00, $LANG, $UNDEFINED
--> Nested braces: {{/bin/bash}}

Line breaks are being lost when sending sms from mvc3

For some reasons the line breaks when send SMS from MVC, not working.
I am using code like,
Constants.cs
public struct SmsBody
{
public const string SMSPostResume=
"[ORG_NAME]"+
"[CONTACT_NUMBER]"+
"[ORG_NAME]"+
"[CONTACT_PERSON]"+
"[EMAIL]"+
"[MOBILE_NUMBER]";
}
Then I call these variables at controller like,
SmsHelper.Sendsms(
Constants.SmsSender.UserId,
Constants.SmsSender.Password,
Constants.SmsBody.SMSPostResume
.Replace("[NAME],",candidate.Name)
.Replace("[EMAIL],",candidate.Email) etc......
My Issue is when i get sms these all things are same line. no spacing.
MY OUTPUT
Dearxxxxyyy#gmail.com0000000000[QUALIFICATION][FUNCTION][DESIGNATION][PRESENT_SALARY][LOCATION][DOB][TOTAL_EXPERIENCE][GENDER] like that.
How to give space between these? Anyone know help me...
Putting the string parts on separate lines, and concatenating them is not a line break... The parts will end up exactly after one another. You should try putting a \n (line break escaped sequence) at each place you want a line break:
public const string SMSPostResume=
"[ORG_NAME]\n"+
"[CONTACT_NUMBER]\n"+
"[ORG_NAME]\n"+
"[CONTACT_PERSON]\n"+
"[EMAIL]\n"+
"[MOBILE_NUMBER]\n";
Also a note based on #finman's comment:
Depending on the service it might be \r\n instead of \n though
So you should look up int he API docs which one would work.
Also there is another error: you try to match string constants with a , at their ends, and the original ones don't have that...
SmsHelper.Sendsms(
Constants.SmsSender.UserId,
Constants.SmsSender.Password,
Constants.SmsBody.SMSPostResume
.Replace("[NAME],",candidate.Name) // <- this line!
.Replace("[EMAIL],",candidate.Email) // <- this line!
You should rewrite either the format string to include, or the replaces to exclude the ,:
SmsHelper.Sendsms(
Constants.SmsSender.UserId,
Constants.SmsSender.Password,
Constants.SmsBody.SMSPostResume
.Replace("[NAME]",candidate.Name) // <- no "," this time
.Replace("[EMAIL]",candidate.Email) // <- no "," this time
//...etc
public const string SMSPostResume=
"[ORG_NAME]"+
"\r[CONTACT_NUMBER]"+
"\r[ORG_NAME]"+
"\r[CONTACT_PERSON]"+
"\r[EMAIL]"+
"\r[MOBILE_NUMBER]";
Also, in
Replace("[NAME],",candidate.Name)
are you sure you want the comma after [NAME] ? If it's not in the string, don't try to replace it.

Best way of storing an "array of records" at design-time

I have a set of data that I need to store at design-time to construct the contents of a group of components at run-time.
Something like this:
type
TVulnerabilityData = record
Vulnerability: TVulnerability;
Name: string;
Description: string;
ErrorMessage: string;
end;
What's the best way of storing this data at design-time for later retrieval at run-time? I'll have about 20 records for which I know all the contents of each "record" but I'm stuck on what's the best way of storing the data.
The only semi-elegant idea I've come up with is "construct" each record on the unit's initialization like this:
var
VulnerabilityData: array[Low(TVulnerability)..High(TVulnerability)] of TVulnerabilityData;
....
initialization
VulnerabilityData[0].Vulnerability := vVulnerability1;
VulnerabilityData[0].Name := 'Name of Vulnerability1';
VulnerabilityData[0].Description := 'Description of Vulnerability1';
VulnerabilityData[0].ErrorMessage := 'Error Message of Vulnerability1';
VulnerabilityData[1]......
.....
VulnerabilityData[20]......
Is there a better and/or more elegant solution than this?
Thanks for reading and for any insights you might provide.
You can also declare your array as consts and initialize it...
const
VulnerabilityData: array[Low(TVulnerability)..High(TVulnerability)] of TVulnerabilityData =
(
(Vulnerability : vVulnerability1; Name : Name1; Description : Description1; ErrorMessage : ErrorMessage1),
(Vulnerability : vVulnerability2; Name : Name2; Description : Description2; ErrorMessage : ErrorMessage2),
[...]
(Vulnerability : vVulnerabilityX; Name : NameX; Description : DescriptionX; ErrorMessage : ErrorMessageX)
)
);
I don't have an IDE on this computer to double check the syntax... might be a comma or two missing. But this is how you should do it I think.
not an answer but may be a clue: design-time controls can have images and other binary data associated with it, why not write your data to a resource file and read from there? iterating of course, to make it simpler, extensible and more elegant
The typical way would be a file, either properties style (a=b\n on each line) cdf, xml, yaml (preferred if you have a parser for it) or a database.
If you must specify it in code as in your example, you should start by putting it in something you can parse into a simple format then iterate over it. For instance, in Java I'd instantiate an array:
String[] vals=new String[]{
"Name of Vulnerability1", "Description of Vulnerability1", "Error Message of Vulnerability1",
"Name of Vulnerability2", ...
}
This puts all your data into one place and the loop that reads it can easily be changed to read it from a file.
I use this pattern all the time to create menus and for other string-intensive initialization.
Don't forget that you can throw some logic in there too! For instance, with menus I will sometimes create them using data like this:
"^File", "Open", "Close", "^Edit", "Copy", "Paste"
As I'm reading this in I scan for the ^ which tells the code to make this entry a top level item. I also use "+Item" to create a sub-group and "-Item" to go back up to the previous group.
Since you are completely specifying the format you can add power later. For instance, if you coded menus using the above system, you might decide at first that you could use the first letter of each item as an accelerator key. Later you find out that File/Close conflicts with another "C" item, you can just change the protocol to allow "Close*e" to specify that E should be the accelerator. You could even include ctrl-x with a different character. (If you do shorthand data entry tricks like this, document it with comments!)
Don't be afraid to write little tools like this, in the long run they will help you immensely, and I can turn out a parser like this and copy/paste the values into my code faster than you can mold a text file to fit your example.

Resources