Any way to access pyomo variable - pyomo

I am new to pyomo. Here is the line on my code which may be having some issue:
model.delivery = Var(model.days, model.del_types, within=Binary, bounds=(0, 1), initialize=1)
How can I access model.delivery. When I am calling it from my console it is giving:
<pyomo.core.base.var.IndexedVar at 0x18bf876b8c8>

Related

Suppressing messages in Rmarkdown using sink()

I am writing a Rmarkdown document about a package called SparseTSCGM and have trouble suppressing messages generated by functions in this package. The messages I'm referring to can be generated by the following code:
if(!require(SparseTSCGM)) install.packages('SparseTSCGM')
library(SparseTSCGM)
datas <- sim.data(model="ar1", time=10,n.obs=10, n.var=5, prob0=0.35,
network="random")
res.tscgm <- sparse.tscgm(data=datas$data, lam1=NULL, lam2=NULL,nlambda=NULL, model="ar1", penalty="scad",optimality="bic_mod", control=list(maxit.out = 5, maxit.in = 5))
I have tried using the functions invisible() and suppressMessages() but these do not help in either Rmarkdown or the R console. I also tried adding the option message = FALSE as follows:
```{r message=FALSE}
library(SparseTSCGM)
datas <- sim.data(model="ar1", time=10, n.obs=10, n.var=7, prob0=0.35, network="random")
res.tscgm <- sparse.tscgm(data = data.fit, lam1 = NULL, lam2 = NULL, nlambda = NULL, model = "ar1", penalty = "lasso", optimality = "bic", control = list(maxit.out = 10, maxit.in = 100))
```
but this does not help.
I have found that I can suppress output in the R console using sink('NUL') (I'm working on a Windows system), but this approach does not work in Rmarkdown. When I try this approach the message I tried to suppress is still there but the Rmarkdown console gives a warning: "Warning message: In sink() : no sink to remove".
Does sink() not work with Rmarkdown, is there another way do to this? If there is no solution I can always manually remove the section from the HTML file but that's a last resort.

Lambda and file writing

Trying to figure out why I can't get Lambda to work with writing a file.
Here is my code:
list = (i*2 for i in range(10))
file = open("text.txt", "a")
lambda i: (file.write(str(i) + "\n")), list
and I don't even get to close the file before I get following error message:
(<function <lambda> at 0x021E1B30>, <generator object <genexpr> at 0x021EC418>)
Based on your comment, I guess what you're trying to do is:
map(lambda i: file.write(str(i) + "\n"), list)
However, I think the code you were apparently trying to avoid would be more readable:
for i in list:
file.write(str(i) + "\n")
(Also, take Peter's note to heart... using list as a variable will come back to haunt you someday when you try to use the list() built-in function and find it's been overridden.)

How to Initialize LSTMCell with tuple

I recently upgraded my tesnorflow from Rev8 to Rev12. In Rev8 the default "state_is_tuple" flag in rnn_cell.LSTMCell is set to False, so I initialized my LSTM Cell with an list, see code below.
#model definition
lstm_cell = rnn_cell.LSTMCell(self.config.hidden_dim)
outputs, states = tf.nn.rnn(lstm_cell, data, initial_state=self.init_state)
#init_state place holder and feed_dict
def add_placeholders(self):
self.init_state = tf.placeholder("float", [None, self.cell_size])
def get_feed_dict(self, data, label):
feed_dict = {self.input_data: data,
self.input_label: reg_label,
self.init_state: np.zeros((self.config.batch_size, self.cell_size))}
return feed_dict
In Rev12, the default "state_is_tuple" flag is set to True, in order to make my old code work I had to explicitly turn the flag to False. However, now I got an warning from tensorflow saying:
"Using a concatenated state is slower and will soon be deprecated.
Use state_is_tuple=True"
I tried to initialize LSTM cell with a tuple by changing the placeholder definition for self.init_state to the following:
self.init_state = tf.placeholder("float", (None, self.cell_size))
but now I got an error message saying:
"'Tensor' object is not iterable"
Does anyone know how to make this work?
Feeding a "zero state" to an LSTM is much simpler now using cell.zero_state. You do not need to explicitely define the initial state as a placeholder. Define it as a tensor instead and feed it if required. This is how it works,
lstm_cell = rnn_cell.LSTMCell(self.config.hidden_dim)
self.initial_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
outputs, states = tf.nn.rnn(lstm_cell, data, initial_state=self.init_state)
If you wish to feed some other value as the initial state, Let's say next_state = states[-1] for instance, calculate it in your session and pass it in the feed_dict like -
feed_dict[self.initial_state] = next_state
In the context of your question, lstm_cell.zero_state() should suffice.
Unrelated, but remember that you can pass both Tensors and Placeholders in the feed dictionary! That's how self.initial_state is working in the example above. Have a look at the PTB Tutorial for a working example.

Error while creating large dropdown in excel using ColdFusion

This code I have written for creating large dropdown in ColdFusion, but it is not working on my end. Could any one please help me rectify my problem. The new code is
<cfquery name="getPOP" datasource="l_webalc">
select distinct center_code from alc_pop
</cfquery>
<cfset countryName= ArrayNew(1)>
<cfloop query="getPOP">
<cfset arrayappend(countryName, getPOP.center_code)>
</cfloop>
<script>
workbook = new HSSFWorkbook();
realSheet = workbook.createSheet("Sheet xls");
hidden = workbook.createSheet("hidden");
for (int i = 0, length= countryName.length; i < length; i++) {
String name = countryName[i];
HSSFRow row = hidden.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(name);
}
namedCell = workbook.createName();
namedCell.setNameName("hidden");
namedCell.setRefersToFormula("hidden!A1:A" + countryName.length);
constraint = DVConstraint.createFormulaListConstraint("hidden");
addressList = new CellRangeAddressList(0, 0, 0, 0);
validation = new HSSFDataValidation(addressList, constraint);
workbook.setSheetHidden(1, true);
realSheet.addValidationData(validation);
stream = new FileOutputStream("c:\\range.xls");
workbook.write(stream);
stream.close();
</script>
Update 1:
(From other thread) I am getting this error message:
function keyword is missing in FUNCTION declaration. The CFML compiler
was processing: A script statement beginning with HSSFWorkbook on line
32, column 1. A script statement beginning with function on line 31,
column 9. A cfscript tag beginning on line 30, column 2.
Update 2:
Again I have modified this code and now the new error is
"The value hidden not A1:A cannot be converted to a number."
I edited the objects as mentioned in the comments and also changed the script to cfscript. Please help me to rectify this error.
<cfscript>
workbook = createObject("java", "org.apache.poi.hssf.usermodel.HSSFWorkbook");
realSheet = workbook.createSheet("Sheet xls");
hidden = workbook.createSheet("hidden");
for (i = 1; i <= arrayLen(countryName); i++){
name = countryName[i];
row = hidden.createRow(i);
cell = row.createCell(0);
cell.setCellValue(name);
}
namedCell = workbook.createName();
namedCell.setNameName("hidden");
namedCell.setRefersToFormula("hidden!A1:A"+arrayLen(countryName));
dv = createObject("java", "org.apache.poi.hssf.usermodel.DVConstraint");
constraint = dv.createFormulaListConstraint("hidden");
addressList = cellRangeList.init(0, 0, 0, 0);
validation = dataValidation.init(addressList, constraint);
workbook.setSheetHidden(1, true);
realSheet.addValidationData(validation);
stream = new FileOutputStream("c:\\range.xls");
workbook.write(stream);
stream.close();
</cfscript>
Update 3:
I have updated the code to fix the mentioned issues and and am now getting this error
"The setSheetHidden method was not found ..."
on the following line:
workbook.setSheetHidden(1, true);
There are several problems with your code. Though java syntax is similar, you cannot just copy and paste a java example and expect it to run in cfscript. You need to make some adjustments first. (Note: I am assuming script was just a typo for cfscript).
In java, you can instantiate an object using the keyword "new" ie new SomeClassName(). In CF, the new keyword can only be used with cfc's. To create a java object, you must use createObject instead. To instantiate it, call the init(...) method. It is a special method in CF that invoke's the constructor of a java class with whatever parameters you supply, ie
createObject("java", "path.to.SomeClassName").init();
To use static methods such as DVConstraint.createFormulaListConstraint(), you must also use createObject. While the java code does not create an new instance of that class, you must still use createObject to get a reference to the DVConstraint class, in CF, before you can invoke any of its methods. Note: Because it is static, no need to call init() first. ie
dv = createObject("java", "org.apache.poi.hssf.usermodel.DVConstraint");
dv.createFormulaListConstraint(...);
Java classes are organized into packages. In java classes, the full path to any referenced classes are imported at the top of the java code (not visible in the example you are using). In CF you need to use the full path in your createObject call. (Important: Paths are cAsE sEnsItIvE).
For example, instead of new HSSFWorkbook() use:
createObject("java", "org.apache.poi.hssf.usermodel.HSSFWorkbook");
If you are not sure of the path, just do a search on "POI TheClassName". Odds are the first result will be the POI JavaDocs, which show the full path at the top of each page like this:
java.lang.Object
|---org.apache.poi.ss.util.CellRangeAddressList
Unlike CF, java is strongly typed, which means you must declare a variable's type as well as it's name. For example, this line declares a variable row as type HSSFRow
HSSFRow row = hidden.createRow(i);
Since CF is typeless, it does not require a type. So running that same code in cfscript will cause the cryptic error "function keyword is missing...". The solution is to drop the variable type and just do a straight variable assignment:
row = hidden.createRow(i);
Java array indexes start at zero (0), while CF starts at one (1), so you need to fix the indexes in your for loop:
for (i = 1; i <= arrayLen(countryName); i++)
Java uses + to concatenate strings, whereas CF uses &. So you need to change the operator here "hidden!A1:A" + countryName.length. Otherwise CF will think you are trying to add two numbers, which will obviously throw an error because the first part is a string.
Assuming no version conflicts, the java example should work after you make those those adjustments.
"The setSheetHidden method was not found ..."
Just use Javacast function for boolean arguments:
workbook.setSheetHidden(1, javacast("boolean",true));

How to get Expiration Date of access token in Facebook SDK for Unity

I am using parse sdk for backend management for my game. For user signup/login parse api ask for parameter tokenExpiration. I have no idea how to get it from facebook unity sdk.
https://www.parse.com/docs/unity_guide#fbusers-signup
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(accessToken, userId, tokenExpiration);
Got this problem solved by myself using debug_token. Here is the right code on how to do it.
FB.API("/debug_token?input_token="+FB.AccessToken+"&access_token="+FB.AccessToken,Facebook.HttpMethod.GET, AccessTokenCallback);
function AccessTokenCallback(response:String){
Debug.Log(response);
var access = JSON.Parse(response);
Debug.Log("Token Expiration is: "+access["data"]["expires_at"].Value);
}
If you will print the response it will give you a JSON with all information about the access token and you can take whatever info you need about an access token.
Open FacebookAccessTokenEditor.cs and replace original line 81:
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}]";
by these two:
string getExpiresAt = ",{\"method\":\"GET\", \"relative_url\":\"debug_token?input_token="+accessToken+"\"}";
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}"+getExpiresAt+"]";
Then open FacebookEditor.cs and in method MockLoginCallback, just before line 220:
isLoggedIn = true;
insert the following lines:
var tokenData = (Dictionary<string, object>)MiniJSON.Json.Deserialize(responses[2]);
var expiresAt = (long)((Dictionary<string, object>)tokenData["data"])["expires_at"];
accessTokenExpiresAt = FromTimestamp((int)expiresAt);
also, add the missing function FromTimestamp which you can copy from AndroidFacebook.cs or IOSFacebook.cs or jus copy from here:
private DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
Finally, you can call the parse method like you do on IOS or Android or Web:
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(FB.UserId, FB.AccessToken, FB.AccessTokenExpiresAt);
Note: As I have worked on the code, I am not sure of the original line numbers, but I think they are correct. Also, this does not reflect the best coding practices, but since it is used only in a debug context, they're good enough for me.