I'm working with ColdFusion and CFScript. At the moment I've no problems, but noticed that I can call values in 3 ways:
Value
'Value'
'#Value#'
What are the differences between them? Thanks in advance!
Value
CF searches for a variable called Value (case insensitive) starting with the VARIABLES scope and then progressing through other scopes (like URL and FORM), stopping at the first variable found.
'Value'
A literal string with the characters V, a, l, u and e.
'#Value#'
A string where Value will be evaluated (CF evalautes stuff between #). If the variable Value (case insensitive) is a so called simple value, the variable will be cast to a string. Otherwise, an exception is thrown since non-simple (ie complex ) values are not automatically cast as strings. This is basically equivalent to '' & Value & '' (string concatenation).
Value = 'Hello World !!';
writeOutput(Value);
>> Hello World !!
writeOutput('Value');
>> Value
writeOutput('#Value#');
>> Hello World !!
writeOutput( evaluate('Value') );
>> Hello World !!
Related
I read that in Matlab it is possible to include a function call inside a regex transformation like this $1double$2[${doubleTextNumber($4)}], assuming 1, 2, 3 to be some regex groups, and 4 to be a purely numeric group. The exact thing I want to do is to catch all arrays consisting of the type creal_T, replace the type with double and double the length of the array.
codeText = "typedef struct {
double tolRob;
creal_T Mt2o[704];
creal_T Ho2o[704];
creal_T Ht2t[704];
creal_T Zo2t[704];
creal_T Ztd[64];
} testType;"
So, I want the struct above to become:
typedef struct {
double tolRob;
double Mt2o[1408];
double Ho2o[1408];
double Ht2t[1408];
double Zo2t[1408];
double Ztd[128];
} SpdEstType;
In Matlab I have made a function to convert a number to text and double it:
function [doubleValue] = doubleTextNumber(inputNumber)
doubleValue = string(str2double(inputNumber)*2.0);
end
I also have a regex that I expect would find the number in each declaration and feed it to the function:
resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*)(\[([^\]]*\d+)\])',
"$1double$2[${doubleTextNumber($4)}]");
However, as I run this peace of code, Matlab gives me the following error msg:
Error using regexprep
Evaluation of 'doubleTextNumber($4)' failed:
Undefined function 'doubleTextNumber' for input arguments of type 'char'.
As far as I understand, I have made the method do conversion from char, and expect it also to accept this value from my regex. I have tested that it works when I input '704' or "704" directly, and also that the regex works appart from this insertion.
Why does not Matlab find the function from my regex? (they are in the same m file)
It looks like I had 3 issues with my original approach:
In order for regexprep() to recognize my function, it had to be moved to its own m-file. Simply calling a method from inside the same file did not work.
I was using https://regex101.com/ to edit the search expression, but even though it seemed to be selecting the number inside the brackets, group 4 did not get populated by regexprep() in Matlab. A new version did work, and populated group 3 with the numbers I wanted: (?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]
I also added more conversion options to my multiplication method in case the input was a combination of numbers and char arrays.
The final version of my regex call becomes:
resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]',
"$1double$2[${multiplyTextNumbers($3,2)}]");
where multiplyTextNumbers() is defined in its own m file as
function [productText] = multiplyTextNumbers(inputFactorText1,inputFactorText2)
%MULTIPLY This method takes numbers as input, and acepts either string,
%char or double or any combination of the three. Returns a string with the
%resulting product.
if (isstring(inputFactorText1) || ischar(inputFactorText1))
inputFactor1 = str2double(inputFactorText1);
else
inputFactor1 = inputFactorText1;
end
if (isstring(inputFactorText2) || ischar(inputFactorText2))
inputFactor2 = str2double(inputFactorText2);
else
inputFactor2 = inputFactorText2;
end
productText = sprintf('%d',inputFactor1*inputFactor2);
end
Hope this can be helpefull to others facing similar issues.
void* PrintHello(void *threadid)
{
long tid;
tid =(long)threadid;
printf("Hello World! It's me, thread #%ld!\n",tid);
pthread_exit(NULL);
}
I'm wondering what each element of the variable declaration stands for and if there is an easier way (more readable/analogous) to just printf?
# =
% =
ld = Long int
! = not?
\n = new line
Also, the pointers seem to be written in two different ways on our slides.
There is:
void* function_name(void* args)
And there is:
void* function_name(void *args)
What is the significance of the asterisk location? Which looks to be correct in this example?
When printing something with a variable, you require % to declare this is the spot where the var input is gonna be. # is just a regular character. ld just represents the type of var you are inputting. In this case, long. ! means nothing as well, it's just a regular character. Also, when printing a var, the only thing that matters (in this case) is the thing between the % and the variable type which is ld in this case. \n just means new line as you stated before.
The asterisks location doesn't change anything. Both of them are correct. The reason for the asterisks is just to tell you it's a pointer
Read your compiler's documentation for printf(). Or online documentation, like this one, or this one. Documentation will explain to you exactly what the various parameters and placeholders are.
In your example, # and ! don't mean anything. They are outside of any format specifier, so they are just literal character data like the majority of your format string content is. Only specifiers preceded by % have any special meaning.
The % character is an escape character that tells printf() to process the following ld specifier. printf() will replace %ld with the value of the tid variable in the formatted string.
Perhaps you would also be interested to see the analogous C++ statement?
Also, for some of you, the C++ version will explain what the printf format info does.
std::printf by default directs the output to stdout. C++ uses std::cout
'#' and '!' are just characters (in both forms)
So, in C++:
std::cout << '#' << tid << "!\n";
However, I would probably use:
std::cout << '#' << tid << '!' << std::endl;
Notes:
Did you notice there is no %ld? The compiler already knows the type of tid (i.e. long int), so you need not explain it a second time to std::cout like you would have to with std::printf.
As an additional benefit, when someone changes the tid type to int32_t (or perhaps int64_t, or static_cast to something smaller), the cout line is un-affected. Quick, what is XX of %XXd for a "long long unsigned int"? How about we never look that up again.
What is the significance of the asterisk location? Which looks to be
correct in this example?
Both forms are 'correct'. I prefer the '* ' form, probably because of my background (with little 'c' exposure).
As stated already by others, %ld in format string "Hello World! It's me, thread #%ld!\n" defines the place where a variable of type long will be placed. # and ! are ordinary characters, and \n stands for a new line (special character backslash gives the subsequent character a special meaning).
But there is another issue in your code when you assign long tid =(long)threadid while having threadid being of type void*, i.e. a pointer to some unspecific type. Actually, if you know that threadid will point to a long, you should write long tid = *((long*)threadid) in order to dereference the pointer and interpret it as particular type long; otherwise, you would assign the pointer value (i.e. some memory address).
This is not a particular keyword of C Language.
let me explain by breaking it up.
#%ld!\n
Equals to
# : Hash character to show count/numbers
%ld : Specifier referencing a long integer that you want to show.
! : Simple exclamatory character.
\n : New line
I have a third party script for a subroutine that I need to work with. This subroutine is as follows
Subroutine COpen(io, Name )
Character*(*) Name
Character*1023 NameIn, NameOut
NameIn = Trim(Name)//' '
Call Get_OrMakeFileName( NameIn, NameOut )
Open(io,file=NameOut,access="APPEND")
End
I don't understand the Character*(*) name syntax. Isn't the typical way to declare string variables simply. character :: name*4 with the *4 part designating the number of characters? Can anyone please explain the purpose of this alternate syntax? What kind of object does it generate?
In short: character*(*) declares a character variable of assumed length.
There are a number of ways of declaring the length of a character variable. One, as seen in the question's code, is
character*1023 ...
where a literal constant follows the *. Equivalent to that is
character([len=]1023) ...
(len= being optional). In this case the length needn't be a literal constant.
These two forms declare a variable of a particular length. There are two other forms of a length for a character variable:
assumed length - character([len=]*) ... ;
deferred length - character([len=]:) ....
Like with character*1023 the assumed and deferred length declarations may be written in this style:
character*(*) ... ! Assumed length
character*(:) ... ! Deferred length
character*(1023) ... ! For completeness
Well, what does "assumed length" mean?
For a dummy argument such as Name it's length is taken from the length of the actual argument of the procedure. With character :: Name*4 the argument is of length 4, regardless of the length of the argument to the subroutine (as long as it's of length at least 4). When the dummy is of assumed length it is of length 12 if the argument is of length 12, and so on.
Although not in the question, a character named constant may also assume its length from the defining expression:
character*(*), parameter :: label='This long'
Deferred length is left to other questions.
Just had an interesting argument in the comment to one of my questions. My opponent claims that the statement "" does not contain "" is wrong.
My reasoning is that if "" contained another "", that one would also contain "" and so on.
Who is wrong?
P.S.
I am talking about a std::string
P.S. P.S
I was not talking about substrings, but even if I add to my question " as a substring", it still makes no sense. An empty substring is nonsense. If you allow empty substrings to be contained in strings, that means you have an infinity of empty substrings. What is the point of that?
Edit:
Am I the only one that thinks there's something wrong with the function std::string::find?
C++ reference clearly says
Return Value: The position of the first character of the first match.
Ok, let's assume it makes sense for a minute and run this code:
string empty1 = "";
string empty2 = "";
int postition = empty1.find(empty2);
cout << "found \"\" at index " << position << endl;
The output is: found "" at index 0
Nonsense part: how can there be index 0 in a string of length 0? It is nonsense.
To be able to even have a 0th position, the string must be at least 1 character long.
And C++ is giving a exception in this case, which proves my point:
cout << empty2.at( empty1.find(empty2) ) << endl;
If it really contained an empty string it would had no problem printing it out.
It depends on what you mean by "contains".
The empty string is a substring of the empty string, and so is contained in that sense.
On the other hand, if you consider a string as a collection of characters, the empty string can't contain the empty string, because its elements are characters, not strings.
Relating to sets, the set
{2}
is a subset of the set
A = {1, 2, 3}
but {2} is not a member of A - all A's members are numbers, not sets.
In the same way, {} is a subset of {}, but {} is not an element in {} (it can't be because it's empty).
So you're both right.
C++ agrees with your "opponent":
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool contains = string("").find(string("")) != string::npos;
cout << "\"\" contains \"\": "
<< boolalpha << contains;
}
Output: "" contains "": true
Demo
It's easy. String A contains sub-string B if there is an argument offset such that A.substr(offset, B.size()) == B. No special cases for empty strings needed.
So, let's see. std::string("").substr(0,0) turns out to be std::string(""). And we can even check your "counter-example". std::string("").substr(0,0).substr(0,0) is also well-defined and empty. Turtles all the way down.
The first thing that is unclear is whether you are talking about std::string or null terminated C strings, the second thing is why should it matter?. I will assume std::string.
The requirements on std::string determine how the component must behave, not what its internal representation must be (although some of the requirements affect the internal representation). As long as the requirements for the component are met, whether it holds something internally is an implementation detail that you might not even be able to test.
In the particular case of an empty string, there is nothing that mandates that it holds anything. It could just hold a size member set to 0 and a pointer (for the dynamically allocated memory if/when not empty) also set to 0. The requirement in operator[] requires that it returns a reference to a character with value 0, but since that character cannot be modified without causing undefined behavior, and since strict aliasing rules allow reading from an lvalue of char type, the implementation could just return a reference to one of the bytes in the size member (all set to 0) in the case of an empty string.
Some implementations of std::string use small object optimizations, in those implementations there will be memory reserved for small strings, including an empty string. While the std::string will obviously not contain a std::string internally, it might contain the sequence of characters that compose an empty string (i.e. a terminating null character)
empty string doesn't contain anything - it's EMPTY. :)
Of course an empty string does not contain an empty string. It'll be turtles all the way down if it did.
Take String empty = ""; that is declaring a string literal that is empty, if you want a string literal to represent a string literal that is empty you would need String representsEMpty = """"; but of course, you need to escape it, giving you string actuallyRepresentsEmpty = "\"\"";
ps, I am taking a pragmatic approach to this. Leave the maths nonsense at the door.
Thinking about you amendment, it could be possible that your 'opponent' meant was that an 'empty' std::string still has an internal storage for characters which is itself empty of characters. That would be an implementation detail I am sure, it could perhaps just keep a certain size (say 10) array of characters 'just incase', so it will technically not be empty.
Of course, there is the trick question answer that 'nothing' fits into anything infinite times, a sort of 'divide by zero' situation.
Today I had the same question since I'm currently bound to a lousy STL implementation (dating back to the pre-C++98 era) that differs from C++98 and all following standards:
TEST_ASSERT(std::string().find(std::string()) == string::npos); // WRONG!!! (non-standard)
This is especially bad if you try to write portable code because it's so hard to prove that no feature depends on that behaviour. Sadly in my case that's actually true: it does string processing to shorten phone numbers input depending on a subscriber line spec.
On Cppreference, I see in std::basic_string::find an explicit description about empty strings that I think matches exactly the case in question:
an empty substring is found at pos if and only if pos <= size()
The referred pos defines the position where to start the search, it defaults to 0 (the beginning).
A standard-compliant C++ Standard Library will pass the following tests:
TEST_ASSERT(std::string().find(std::string()) == 0);
TEST_ASSERT(std::string().substr(0, 0).empty());
TEST_ASSERT(std::string().substr().empty());
This interpretation of "contain" answers the question with yes.
I'm working on a little console game with ncurses. In the main menu I want the user to be able to set the control keys. Now as far as I understood, in ncurses you can access e.a. the a-key by the int value of the char 'a'. Using the key ingame with 'a' works flawlessly, however I'm stuck with the menu:
For each key binding I have stored an int-value that is defaulted to e.a. 'a'. When the game starts, I read the 'a' binding correctly from the int-value and can use it ingame. However, it is not displayed correctly. I want it to be like this: "Left: a". I do it like this:
std::string key = "Left: " + static_cast<char>(_value);
_value being the int-value I stored and initialized as 'a'. I also tried it without the cast, btw.
Now what's being displayed is strange. Instead of "a" it says "~T^C". For the letters "s" and "d" it doesn't display anything at all. "w" becomes some very strange encoding question marks.
I suppose it's got something to do with the encoding of the characters in int-values or something. So what can I do to get it displayed the right way?
Thanks a lot!
You're adding together the adress of string literal and ASCII value of _value. String key is then constructed from whatever happens to be at that garbage adress.
Remember that string literals are of type array of N const char and that arrays decay to pointer to their first element when passed to functions and operators etc., which yields you const char*. The built in + operator for pointers doesn't do string concatenation. You need to construct a std::string from at least one of operands for overloaded operator to kick in:
std::string key = std::string("Left: ") + static_cast<char>(_value);