"{ required" in nested loop in stata - stata

I hate to annoy you guys with this question, but I am getting the error "{ required" even though all my loops appear to be open (and closed) properly and unfortunately Stata doesn't tell you where the error is, so I can't figure out why this is happening. By the way if I take out the append_replace section with the if statements, I am still getting the same error, so I don't think it is from that section. Here is my code:
local vars = "any_rate resp_rate circ_rate weight_rate diabetes_rate gallstones_rate mental_rate cancer_rate std_rate died_rate"
local dates = "1947 1974"
foreach var of local `vars' {
foreach i of local `dates' {
forvalues j = 500(100)2500 {
local append_replace = "append"
if "`var'"=="any_rate" {
if "`i'" == "1947" {
if `j' == 500 {
local append_replace = "replace"
}
}
}
reg `var' post`i' dobdistfrom`i'change dobdistfrom`i'changesq post`i'_dist`i' post`i'_dist`i'sq if dobdistfrom`i'change < `j' & dobdistfrom`i'change > -`j', cluster(dobdistfrom`i'change)
outreg2 using Prelim_RD_Estimates.xls, `append_replace' excel dec(3)
}
}
}
Thanks so much for your help!

I believe the problem is with the local that prevents the { from being read.
Original problematic version:
local dates = "1947 1974"
foreach i of local `dates' {
di `i'
}
Corrected version:
local dates = "1947 1974"
foreach i in `dates' {
di `i'
}
You could also just omit the quotes in "foreach i of local dates" in your original construction.

Related

How can I change one object only when one other object is selected?

I'm browsing MEL and expressions and trying to do something like this: if I select one object I deactivate one property from another. But I'm having problems with the object selection denomination. The following is an example:
If (select pCube1-r on) {
  PCube2.visibility = 0;
}
I have tried with strings too but it didn't work...
global proc myscript() {
string $a[] = ls -sl;
if ($a[0] == "pCube1")
hide = "pCube2";
else;
}
scriptJob -e"SelectionChanged"
"myScript";
Can someone help?
Thank you very much!
To find out if a given object is selected you'll need to loop over the list returned by ls -sl.
string $sel[] = `ls -sl`;
string $item;
for ($item in $sel)
{
if ($item == "your-object-here")
{
doSomething();
}
}
This is safer than using an index in any case because you can't be sure there will be an item 0.

Create stored procedure from x++

Got myself into trouble today trying to create a stored procedure from ax.
Here is a simple example:
static void testProcedureCreation(Args _args)
{
MyParamsTable myParams;
SqlStatementExecutePermission perm;
str sqlStatement;
LogInProperty Lp = new LogInProperty();
OdbcConnection myConnection;
Statement myStatement;
ResultSet myResult;
str temp;
;
select myParams;
LP.setServer(myParams.Server);
LP.setDatabase(myParams.Database);
//Lp.setUsername("sa");
//Lp.setPassword("sa");
sqlStatement = #"create procedure testproc
as begin
print 'a'
end";
//sqlStatement = strFmt(sqlStatement, myStr);
info(sqlStatement);
perm = new SqlStatementExecutePermission(sqlStatement);
perm.assert();
try
{
myConnection = new OdbcConnection(LP);
}
catch
{
info("Check username/password.");
return;
}
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(sqlStatement);
while (myResult.next())
{
temp = myResult.getString(1);
info(temp);
if (strScan(temp, 'Error', 1, strLen(temp)) > 0)
throw error(temp);
}
myStatement.close();
CodeAccessPermission::revertAssert();
}
To be honest, in my real example I am using BCP and some string concat with a lot of | ' and "".
Anyway, here is what I got:
For a couple of hours I kept changing and retrying a lot of things and, a good thought came into my mind.
"Let's try with a much easier example and check the results!"
OK, no luck, the results were the same, as you can see in the pic above.
But for no reason, I tried to :
exec testproc
in my ssms instance and to my surprise, it worked. My small procedure was there.
It would be so nice if someone could explain this behavior and maybe what should be the correct approach.
This Q/A should provide an answer.
How to get the results of a direct SQL call to a stored procedure?
executeQuery vs executeUpdate

Google Sheets Script - If or statement. Restrict onEdit to specific sheet

Super quick question. I have this function I want to run on entire workbook, except two specific sheets.
This is my code:
function onEdit(e) {
var sheet = SpreadsheetApp.getActiveSheet();
if (sheet.getName() != "Total" || sheet.getName() != "DataRange" ) {
someAction();
}
}
This just does not work, the code runs on all sheets no matter what. This is probably a noob question but.
not an "answer" as you already answered your own question, but an alternative:
I'll prefer to use an indexOf I found that (in this case) clearer thant the switch:
function onEdit(e) {
var sheet = SpreadsheetApp.getActiveSheet();
if (["Total","DataRange"].indexOf(sheet.getName()) == -1 ) {
someAction();
}
}
I just identify in an array all the sheet that I want to avoid and then check that the current sheet is not one of then (return -1)
I solved it by using switch instead
switch (sheet.getName()) {
case "Total":
return;
case "DataRange":
return;
default:
doSomething();
break;
}
Answer by Kenny Bones moved from question to answer space.

Lua: pass context into loadstring?

I'm trying to pass context into a dynamic expression that I evaluate every iteration of a for loop. I understand that the load string only evaluates within a global context meaning local variables are inaccessible. In my case I work around this limitation by converting a local into a global for the purpose of the string evaluation. Here's what I have:
require 'cosmo'
model = { { player = "Cliff", age = 35, gender = "male" }, { player = "Ally", age = 36, gender = "female" }, { player = "Jasmine", age = 13, gender = "female" }, { player = "Lauren", age = 6.5, gender = "female" } }
values = { eval = function(args)
output = ''
condition = assert(loadstring('return ' .. args.condition))
for _, it in ipairs(model) do
each = it
if condition() then
output = output .. each.player .. ' age: ' .. each.age .. ' ' .. '\n'
end
end
return output
end }
template = "$eval{ condition = 'each.age < 30' }"
result = cosmo.fill(template, values)
print (result)
My ultimate goal (other than mastering Lua) is to build out an XSLT like tempting engine where I could do something like:
apply_templates{ match = each.age > 30}[[<parent-player>$each.player</parent-player>]]
apply_templates{ match = each.age > 30}[[<child-player>$each.player</child-player>]]
...And generate different outputs. Currently I'm stuck on my above hawkish means of sharing a local context thru a global. Does anyone here have better insight on how I'd go about doing what I'm attempting to do?
It's worth noting that setfenv was removed from Lua 5.2 and loadstring is deprecated. 5.2 is pretty new so you won't have to worry about it for a while, but it is possible to write a load routine that works for both versions:
local function load_code(code, environment)
if setfenv and loadstring then
local f = assert(loadstring(code))
setfenv(f,environment)
return f
else
return assert(load(code, nil,"t",environment))
end
end
local context = {}
context.string = string
context.table = table
-- etc. add libraries/functions that are safe for your application.
-- see: http://lua-users.org/wiki/SandBoxes
local condition = load_code("return " .. args.condition, context)
Version 5.2's load handles both the old loadstring behavior and sets the environment (context, in your example). Version 5.2 also changes the concept of environments, so loadstring may be the least of your worries. Still, it's something to consider to possibly save yourself some work down the road.
You can change the context of a function with setfenv(). This allows you to basically sandbox the loaded function into its own private environment. Something like the following should work:
local context = {}
local condition = assert(loadstring('return ' .. args.condition))
setfenv(condition, context)
for _, it in ipairs(model) do
context['each'] = it
if condition() then
-- ...
This will also prevent the condition value from being able to access any data you don't want it to, or more crucially, modifying any data you don't want it to. Note, however, that you'll need to expose any top-level bindings into the context table that you want condition to be able to access (e.g. if you want it to have access to the math package then you'll need to stick that into context). Alternatively, if you don't have any problem with condition having global access and you simply want to deal with not making your local a global, you can use a metatable on context to have it pass unknown indexes through to _G:
setmetatable(context, { __index = _G })

CFGRID - replace data store or filter on more than one column

ColdFusion 8
I have a cfgrid that that is based on a query. It is not bound to a cfc function because I want a scrolling grid, not a paged grid (you must supply the page number and page size if you use BIND).. I can figure out how to make it filter on one column by using the following code, but I really need to filter on three columns...
grid.getDataSource().filter("OT_MILESTONE",t1);
Adding more to the filter string does not do the trick...it ignores anything more than the first pair of values..
so..I thought if I called a function that passes the three values and returned the query results to me, I could replace the Data Store for the grid..but I cannot figure out the syntax to get it to replace.
The returned variable for the query has the following format:
{"COLUMNS":["SEQ_KEY","ID","OT_MILESTONE"],"DATA":[[63677,"x","y"]]}
Any ideas?
have you looked at queryconvertforgrid()?
http://www.cfquickdocs.com/cf9/#queryconvertforgrid
Update: have you looked at these?
http://www.danvega.org/blog/index.cfm/2008/3/10/ColdFusion-8-Grid-Filtering
http://www.coldfusion-ria.com/Blog/index.cfm/2009/1/13/Playing-with-cfgrid--Filter-showhide-Columns-and-using-the-YUI-Buttons-library
http://cfsilence.com/blog/client/index.cfm/2007/8/9/Filtering-Records-In-An-Ajax-Grid
after much blood, sweat, tears and swearing..here's the answer, in case anyone else might need to filter a cfgrid by more than one variable:
var w1 = ColdFusion.getElementValue('wbs');
var t1 = ColdFusion.getElementValue('task');
var p1 = ColdFusion.getElementValue('project');
grid = ColdFusion.Grid.getGridObject('data');
store = grid.getDataSource();
store.clearFilter();
store.filterBy(function myfilter(record) {
var wantit = true;
if (trim(w1) != '') {
if(record.get('WBS_ID') != w1) {
wantit = false;
}}
if (trim(t1) != '') {
if(record.get('OT_MILESTONE') != t1) {
wantit = false;
}}
if (trim(p1) != '') {
if(record.get('PROJECT') != p1) {
wantit = false;
}}
return wantit;
});
ColdFusion.Grid.refresh('data',false);
you will need a JS trim function...
Make sure the column names are caps...