formatting all values in a structure - coldfusion

I need to convert all values in a structure (arguments passed into a function) to uppercase.
I wrote the following method, but rather than replace the argument with the formatted one, it is creating a new key to the arguments struct (e.g. for first loop, it creates a key of '1' with the value of arguments[1], next loop creates a new key of '2' with the value of arguments[2] and so on.
Can anyone suggest how I can change the value of each key in the struct?
The code kind of shows what I am trying to do, but let me know if you need more info.
public function formatValues(){
numArgs = structCount(arguments);
for (i=1; i<=numArgs ; i=i+1){
arguments[i] = Ucase(arguments[i]);
}
return arguments;
}

Try this:
public function formatValues(){
for (var i in arguments){
if( isSimpleValue( arguments[i] ) ){
arguments[i] = ucase( arguments[i] );
}
}
return arguments;
}
writeDump(formatValues(name="moo",city="baa"));
writeDump(formatValues("moo","baa"));
This will work with named arguments and non-named arguments. It also will only modify simple values (strings, numbers, etc) and not complex variables (arrays, structures, objects)

Is it because you forgot the parameter?
public function formatValues(arguments){
var numArgs = structCount(arguments);
for (var i=1; i<=numArgs ; i=i+1)
{
arguments[i] = Ucase(arguments[i]);
}
return arguments;
}

Related

Accessing a Lua table within a table from C++ side

I'm trying to transfer a table where there may be nested tables from the lua and write to a .ini file. But I just can not how I need to go on the stack to get data from nested tables. This code does not work as it should. Function setData work not correctly. What could be the problem?
C++ code
int sasl::LuaUtilities::luaWriteIni(LuaState inOutState)
{
string path;
boost::property_tree::ptree iniTree;
LUA_CHECK_NARG_EQ(inOutState, 2);
LUA_GET_PARAM(inOutState, 1, path);
int nargs = lua_gettop(inOutState);
for (int i = 1; i <= nargs; i++) {
if (lua_istable(inOutState, nargs)) {
setData(inOutState, nargs, iniTree);
}
}
return 0;
}
void sasl::LuaUtilities::setData(LuaState inOutState, int index, boost::property_tree::ptree & inIniTree)
{
// Push an initial nil to init lua_next
lua_pushnil(inOutState);
// Parse the table at index
while (lua_next(inOutState, index))
{
if (lua_istable(inOutState, index))
{
setData(inOutState, index, inIniTree);
}
else
{
string key = lua_tostring(inOutState, -2);
string value = lua_tostring(inOutState, -1);
}
// Pop value, keep key
lua_pop(inOutState, 1);
}
return;
}
Lua code
t = {}
local fileName = findResourceFile("test.ini")
t = readINI(fileName)
writeINI(fileName, t) --this not work in c++ side
There are two problems. lua_istable(inOutState, index) is wrong, because index is not the value of the key retrieved by next. That index is always the table you're iterating over. So you'll infinitely recurse over the same table when you call setData with that index.
In fact, passing index to setData itself is almost certainly wrong. Or at least, it's probably not right. You want to use relative indices here, but calling next pushes an extra value onto the stack.
What you probably want to do is have setData assume that the table to iterate over is at index -1 (ie: the top of the stack). That way, you're just calling lua_next(state, -2) (this is -2 because the key to get the next one for is at the top). And when you recursively call setData for a table value, you don't need to provide an index, because the table value is already at the top of the stack.
The second problem is that you never write the key/value pairs. You also never check to see if the value is something which can be converted to a string. It could be a Lua userdata.

c++: Run a function 8 times and add each answer to an array or JSON it

I'm super new to C++ and am trying to build a json file that contains x0...x7 of the files that gets parsed from a pre-defined function so that it can compose a JSON string to give to R. so that it can open a socket to R and send this piece of JSON to it.
however, im kinda stuck here, here is what i have:
std::map<std::string,std::string>::const_iterator qIter;
std::string variable;
std::map<string,string> mymap;
variable = "x";
for (int i=1,i<=7,i++){
float variable+i = ( (qIter = request.getQuery().find(variable+i))
== request.getQuery().end()
)
? 0.0
: atof(qIter->second.c_str());
if ( !isLegalNumber(request.getQuery(),variable+i,variable+i) )
{
strcpy(filePath,"yourErrorFilename.html");
}
else
{
// I want to add the x0 or xn variable here into a json
// The value is now in variable 'x'of something
}
}
Any insights appreciated.
edit: here's my isLegalNumber() method
bool isLegalNumber (const std::map<std::string,std::string>&
map,
const std::string& varName,
float& value
)
{
float temp;
char* cPtr;
std::map<std::string,std::string>::const_iterator
iter = map.find(varName);
if (iter == map.end())
return(false);
temp = strtod(iter->second.c_str(),&cPtr);
if ( (*cPtr != '\0') || (cPtr == iter->second.c_str()) )
return(false);
value = temp;
return(true);
}
im trying to convert a string/ dictionary into a json,
the first question would be how to add it into a dictionary,
and second, how to convert that dictionary into JSON.
basically i want the json to look like
{
x1: value of x1,
x2: value of x2,
....
x7: value of x7
}
I'm not totally clear what you're trying to do in your example code. Specifically, I don't know what the string value variable is used for. I'm guessing you actually want to define an array of floats. You can also skip the first step where you're setting the value to either 0.0 or atof(...) since your isLegalNumber function sets it later anyway. e.g.
float x[8] = {0.0f};
// Note that arrays in C++ are zero-indexed, so your iteration variable should start at 0
for (int i=0; i<=7; i++) {
std::string varName = "x";
varName.push_back(std::to_string(i+1)); // Append the index
if ( !isLegalNumber(request.getQuery(), varName, x[i] ) {
// Error
} else {
// Add to JSON structure
}
}
Once you've got that sorted out, for working with JSON in C++, I would strongly recommend using an existing open-source library such as JSON for Modern C++, rather than rolling your own implementation. This will make it much easier to build the JSON structure you need and ensure that it is properly formatted.
That library has quite thorough documentation, and it allows you to define JSON structures using very similar syntax to the actual JSON you're trying to write, e.g.
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
// ...
};
Or in your specific case, define json j; outside the loop, and then in your if case you can do:
j[varName] = x[i];
And then you can convert it to a string using std::string s = j.dump();.

swig perl typemap(out) std::vector<std::string> doesn't return the desired output in perl

I am trying to type a typemap(out) std::vector.
I want it to get to the perl code as an array instead I am getting an array of arrays which after a double dereference contains the desired data.
how can I make it an array of strings in perl?
I have tried to edit the typemap myself and to use the typemaps in the "std_vector.i" and in "std_string.i" without editing and they all give the same results.
this is the typemap code:
%typemap(out) std::vector<std::string> {
int len = $1.size();
SV *svs = new SV[len];
for (int x = 0; x < len; x++) {
SV* sv = sv_newmortal();
sv_setpvn(sv, $1[x].data(), $1[x].size());
svs[x] = SvPV(sv, $1[x].size());
}
AV *myav = av_make(len, svs);
delete[] svs;
$result = newRV_noinc((SV*) myav);
sv_2mortal($result);
argvi++;
}
my code for testing the output:
#this return a std vector<string> in the cpp code
my #commitReturn = $SomeClass->commit();
print "\n";
#this should return a string instead it returns an array.
print $commitReturn[0];
print "\n";
#this should not work, instead it returns the desired output.
print $commitReturn[0][0];
the output is:
ARRAY(0x908c88)
20790
instead of:
20790
Can't use string ("20791") as an ARRAY ref while "strict refs"
Your commit method is just returning an array reference, not an array of array references. Maybe it looks like an array of array references because you are assigning the result to an array?
In any case, without touching the typemap code, you can dereference the function call
#commitReturn = #{$SomeClass->commit()};
or create a wrapper method to dereference it for you
package SomeClass;
...
sub commit_list {
my $self = shift;
#{$self->commit()};
}
...
#commitReturn = $SomeClass->commit_list();
To return an array instead of a reference to an array, you have to manipulate the stack such that Perl knows that more than one scalar is returned.
According to the documentation:
The current value of the argument stack pointer is contained in a
variable argvi. Whenever a new output value is added, it is critical
that this value be incremented. For multiple output values, the final
value of argvi should be the total number of output values.
So the following typemap should be sufficient:
%typemap(out) std::vector<std::string> {
int len = $1.size();
for (int x = 0; x < len; x++) {
$result = sv_newmortal();
sv_setpvn($result, $1[x].data(), $1[x].size());
argvi++;
}
}

passing variable arguments to listener method in a loop

I want to pass args while calling service in loop. The problem is 1- If I use anonymous function as in following code;
for (var j:int = 0; j < listItems.length; j++)
{
_service.addEventListener(ResultEvent.RESULT, _anonymous = function(event:ResultEvent):void{
thumbnailResultHandler(event,listItems[k].ObjectID)
});
}
then, when starts running thumbnailResultHandler, pushing the latest value of j, and so latest value of listItems array. Because they are working async.
2- If I use following option to pass args;
_anonymous = onClick(listItems[j].ObjectID,j);
_service.addEventListener(ResultEvent.RESULT, _anonymous);
in for loop, and here is onClick function
public function onClick(n:Number,k:Number):Function
{
_service.removeEventListener(ResultEvent.RESULT,_anonymous);
return function(event:ResultEvent):void
{
trace( count++) ;//traces 25 times but must be just 5.
}
}
then, when thumbnailResultHandler runs, this method access both I passed values to onClick function and then works 5x5 times instead of 5 times working.
This must work once in each resultHandler , but reading both parameters in every result.
ASSUME listItems.length = 5
Any suggestion how can I fix this issue ?

returning multiple strings from a function

I have a function where i want to be able return what is printed out so then i can print the output on the page. How will i return both of the string which are outputted within both of those if statements ?
std::vector<std::string> el;
split(el,message,boost::is_any_of("\n"));
std::string a ("");
for(int i = 0; i < el.size(); i++)
{
if(el[i].substr(0,3) == ".X/")
{
DCS_LOG_DEBUG("--------------- Validating .X/ ---------------")
std::string str = el[i].substr(3);
std::vector<std::string>st;
split(st,str,boost::is_any_of("/"));
boost::regex const string_matcher(splitMask[0]);
if(boost::regex_match(st[0],string_matcher))
{
a = "Correct Security Instruction";
}
else
{
a = "Incorrect Security Instruction"
}
boost::regex const string_matcher1(splitMask[1]);
if(boost::regex_match(st[1],string_matcher1))
{
a = "Correct Security screening result"
}
else
{
a = "Incorrect Security screening result"
}
return a;
}
}
Thankfull for any help :)
You can return an std::pair of strings, for instance.
Define a class with two appropriately-named string members and return an instance of that.
Then, start to think about what methods or other data would be useful to have on that class.
You can push the strings in a std::vector that is passed to the function as a reference and later iterate over the vector upon return.
I would return a std::pair of bool values (one to indicate if the instruction is correct, and one to indicate if the screening result is correct), and let the calling code interpret the results.