Declaring a tuple of parameters in AMPL - ampl

Is there a way to simplify declaring a tuple of parameters in AMPL? For example, if a three-dimensional point was needed as a parameter, what I'm doing is declaring it as
param Point {{'a', 'b', 'c'}};
and then accessing it through P['a'], P['b'], and P['c']. The problem with this is, first, that it's ugly. To specify the point (1, 2, 3) in the data file you would have to write
param Point := a 1 b 2 c 3;
. I tried using the ordered keyword—i.e. param Point {{'a', 'b', 'c'} ordered};—so that the label was implied by the order—i.e. param Point := 1 2 3—, but that's not allowed inline, and having to define a separate "dummy" set is even uglier. I tried searching through the AMPL book, but found nothing for this specific purpose.
The other alternative is even worse:
param a;
param b;
param c;
It seems very stupid that there isn't a special syntax/shortcut for this.
Also note that I don't want to declare a set; I want an actual tuple parameter, of fixed length (specified through the model), whose entries are to be used as numerical parameters, and not labels.
So, is there a good way to do this?

If I've understood correctly, what you're looking for here is a way to input values for an AMPL tuple (indexed over some set S) without having to include the names of the indices (members of S) alongside the values - i.e. requiring that the index for each value is deduced from the order in which the values are provided.
I'm not aware of a simple way to do this. In AMPL, indexed numeric parameters (and variables) work in a similar way to e.g. a Python dict(): elements are referenced by key (index value), not by position. Because of this, all the methods of data input that I've seen require giving the indices alongside the values.
Given that AMPL does support ordered sets, I presume it would be possible to provide an input mode that allows for indices to be implied by position instead of stated explicitly. However, I'm not aware of this existing. It might be that it simply isn't a priority, or it might be a deliberate design decision to improve code robustness.
I suspect position-dependent inputs might be a bit more fragile for many of the problems AMPL is intended to handle; they certainly would be for the ones I've used it for. Often I want to reuse the same model with small changes to the index sets, in which case explicitly indexing the inputs helps prevent assigning the wrong values to the wrong places.

Related

How to make criteria with array field in Hibernate

I'm using Hibernate and Postgres and defined a character(1)[] column type.
So I don´t know how to make this criteria to find a value in the array.
Like this query
SELECT * FROM cpfbloqueado WHERE bloqueados #> ARRAY['V']::character[]
I am not familiar with Postgres and its types but you can define your own type using custom basic type mapping. That could simplify the query.
There are many threads here on SO regarding Postres array types and Hibernate, for instance, this one. Another array mapping example that could be useful is here. At last, here is an example of using Criteria with user type.
Code example could be
List result = session.createCriteria(Cpfbloqueado.class)
.setProjection(Projections.projectionList()
.add(Projections.property("characterColumn.attribute"), PostgresCharArrayType.class)
)
.setResultTransformer(Transformer.aliasToBean(Cpfbloqueado.class))
.add(...) // add where restrictions here
.list()
Also, if it is not important for the implementation, you can define max length in the entity model, annotating your field with #Column(length = 1).
Or if you need to store an array of characters with length of 1 it is possible to use a collection type.
I hope I got the point right, however, it would be nice if the problem domain was better described.
So you have array of single characters... Problem is that in PG that is not fixed length. I had this problem, but around 10 years ago. At that time I had that column mapped as string, and that way I was able to process internal data - simply slice by comma, and do what is needed.
If you hate that way, as I did... Look for columns with text[] type - that is more common, so it is quite easy to find out something. Please look at this sample project:
https://github.com/phstudy/jpa-array-converter-sample

Using bind variables in large insert statements

I am inheriting an application which has to read data from various types of files and use the OCI interface to move the data into an Oracle database. Most of the tables in question have about 40-50 columns, so the SQL insert statements become pretty lengthy.
When I inherited this code, it basically built up the insert statements via a series of strcats as a C string, then passed it to the appropriate OCI functions to set up and execute the statement. However, since much of the data is read directly from files into the column values, this leaves the application open to easy SQL injection. So I am trying to use bind variables to solve this problem.
In every example OCI application I can find, each variable is statically allocated and bound individually. This would lead to quite a bit of boilerplate, however and I'd like to reduce it to some sort of looping construct. So my solution is to, for each table, create a static array of strings containing the names of the table columns:
const char const *TABLE_NAME[N_COLS] = {
"COL_1",
"COL_2",
"COL_3",
...
"COL_N"
};
along with a short function that makes a placeholder out of a column name:
void makePlaceholder(char *buf, const char *col);
// "COLUMN_NAME" -> ":column_name"
So I then loop through each array and bind my values to each column, generating the placeholders as I go. One potential problem here is that, because the types of each column vary, I bind everything as SQLT_STR (strings) and thus expect Oracle to convert to the proper datatype on insertion.
So, my question(s) are:
What is the proper/idiomatic (if such a thing exists for SQL/OCI) to use bind variables for SQL insert statements with a large number of columns/params? More generally, what is the best way to use OCI to make this type of large insert statement?
Do large numbers of bind calls have a significant cost in efficiency compared to building and using vanilla C strings?
Is there any risk in binding all variables as strings and allowing Oracle to make the proper type conversion?
Thanks in advance!
Not sure about the C aspects of this. My answer will be from a DBA perspective.
Question 2:
Always use bind variables. It prevent SQL-injection and enhances performance.
The performance aspect is often overlooked by programmers. When Oracle receives a SQL it makes a hash of the entire SQL-text and looks in it's internal repository of execution plans to see if it has one. If bind variables was used it the SQL-text will be the same each time you run the query, not matter what the value of a variable is. However if you have concatenated the string your self Oracle will hash the SQL-text including content of (what you aught to have put in) variables, getting a unique hash every time. So if you do a query one million times Oracle will if you used bind variables make one execution plan, while if you did not use bind variables it will make one million execution plans and waste loads of resources doing that.

Saving Variables Prolog

Is it possible to save variables in Prolog?
I would like to save and edit a list as the program runs but I cannot find anyway of saving the list between edits.
Probably the Prolog feature you want is assert/retract of a dynamic predicate like myListVars/1, which does nothing more than save a specified list of values that you can retrieve subsequently.
For example, if you had three variables X,Y,Z that you wanted to memorialize, they could be saved into a dynamic fact myListXYZ/1 with a predicate like this:
setListXYZ(_,_,_) :-
retract(myListXYZ(_)),
fail.
setListXYZ(X,Y,Z) :-
assert(myListXYZ([X,Y,Z])).
and retrieved with a predicate like this:
getListXYZ(X,Y,Z) :-
myListXYZ([X,Y,Z]).
This approach assumes you will only have (at most) one fact at a time for myListXYZ/1, which is guaranteed if one only accesses that predicate through the get/set pair above.
I often use similar "fact" predicates to store test cases for Prolog programs where it is inconvenient to type required arguments in manually. More than one test case can be accomodated by adding an extra argument that "labels" the test cases.

Long variable names

Lets say i have a variable that contains the number of search engine names in a file, what would you name it?
number_of_seach_engine_names
search_engine_name_count
num_search_engines
engines
engine_names
other name?
The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
How about numEngineNames?
Choosing variable names is more art than science. You want something that doesn't take an epoch to type, but long enough to be expressive. It's a subjective balance.
Ask yourself, if someone were looking at the variable name for the first time, is it reasonably likely that person will understand its purpose?
A name is too long when there exists a shorter name that equally conveys the purpose of the variable.
I think engineCount would be fine here. The number of engine names is presumably equal to the number of engines.
See JaredPar's post.
It depends on the scope of the variable. A local variable in a short function is usually not worth a 'perfect name', just call it engine_count or something like that. Usually the meaning will be easy to spot, if not a comment might be better than a two-line variable name.
Variables of wider scope – i.e. global variables (if they are really necessary!), member variables – deserve IMHO a name that is almost self documentary. Of course looking up the original declaration is not difficult and most IDE do it automatically, but the identifier of the variable should not be meaningless (i.e. number or count).
Of course, all this depends a lot on your personal coding style and the conventions at your work place.
Depends on the context, if its is a local variable, as eg
int num = text.scan(SEARCH_ENGINE_NAME).size();
the more explicit the right-hand of the expression the shorter the name I'd pick. The rational is that we are in a limited scope of maybe 4-5 lines and can thus assume that the reader will be able to make the connection between the short name and the right-hand-side expression. If however, it is the field of a class, I'd rather be as verbose as possible.
See similar question
The primary technical imperative is to reduce complexity. Variables should be named to reduce complexity. Sometimes this results in shorter names, sometimes longer names. It usually corresponds to how difficult it is for a maintainer to understand the complexity of the code.
On one end of the spectrums, you have for loop iterators and indexes. These can have names like i or j, because they are just that common and simple. Giving them longer names would only cause more confusion.
If a variable is used frequently but represents something more complex, then you have to give it a clear name so that the user doesn't have to relearn what it means every time they use it.
On the other end of the spectrum are variables that are used very rarely. You still want to reduce confusion here, but giving it a short name is less important, because the penalty for relearning the purpose of the variable is not paid very often.
When thinking about your code, try to look at it from the perspective of someone else. This will help not only with picking names, but with keeping your code readable as a whole.
Having really long variable names will muddle up your code's readability, so you want to avoid those. But on the other end of the spectrum, you want to avoid ultra-short names or acronyms like "n" or "ne." Short, cryptic names like these will cause someone trying to read your code to tear their hair out. Usually one to two letter variables are used for small tasks like being incremented in a for loop, for example.
So what you're left with is a balance between these two extremes. "Num" is a commonly used abbreviation, and any semi-experienced programmer will know what you mean immediately. So something like "numEngines" or "numEngineNames" would work well. In addition to this, you can also put a comment in your code next to the variable the very first time it's used. This will let the reader know exactly what you're doing and helps to avoid any possible confusion.
I'd name it "search_engine_count", because it holds a count of search engines.
Use Esc+_+Esc to write:
this_is_a_long_variable = 42
Esc+_+Esc and _ are not identical characters in Mathematica. That's why you are allowed to use the former but not the latter.
If it is a local variable in a function, I would probably call it n, or perhaps ne. Most functions only contain two or three variables, so a long name is unnecessary.

SQL:1999 Array Type Constructor Usage?

Can anyone confirm whether or not the SQL:1999 Array type Constructor provides any operations for searching the Array in a WHERE clause?.
As an Example If a table EMPLOYEES had a column
QUALIFICATION VARCHAR(20) ARRAY[10]
containing values such as ARRAY['BSC','MBA']
Does the standard support some way of querying EMPLOYEES to find all Employees with an MBA?
Well, you can always use an element reference (ISO/IEC 9075-2:1999, 6.13 ):
WHERE QUALIFICATION(1) = 'BSC'
OR QUALIFICATION(2) = 'BSC'
...
Of course, the problem is that you need to write a comparison for each possible position.
I am not aware of any operators that allows you to compare a scalar with an array, although I would suppose a DBMS that has native support for ARRAY types ould let you create a function that does the job.
I must say I never had the need for array types - I would typically build a one-to-many detail table, or in rare cases, add multiple columns (yeah - a repeating group. send the relational police to hunt me if you like :)
Would you care to explain why you need to know this, or what problem you are trying to solve with an ARRAY?