How to get the variable and constraint of a cpsolver when using ortools - or-tools

As the topic, when I use ortools, I want to serialize cpsolver, CpSolverSolutionCallback and cpmodel to achieve multithread computing. However, I can't just serialize those objects directly and I think I need to only serialize their configuration and reset configuration in each thread, such as all the constraint and variables in the cpmodel and parameters in cpsolver. This is the question, how can I get all those values using ortools? Is there an api or something? I can't find it when searching on Google.

Every language implements a thin wrapper above a protocol buffer file.
This file is described here
This model is accessible from each CpModel class.
Now you can distribute work using this proto directly. You will need to look at the CpSolver class to understand how the c++ Solve method is called.
See the python solve method.
The way to implement your request.
Create your model normally.
Extract the underlying protocol buffer model underneath and use it for parallelism/distribution.
Solve will returns a CpSolverResponse object. To get the value of a variable in the response, call response.Value(var.Index()), or store the index of the relevant variables and use it in the Value() method call.

Related

How can I read out the "glade ID" of a gtk3 object

In glade it is possible to set an unique ID to an object. In the code one can obtain a pointer to this object by searching for it's "glade ID" via gtk_builder_get_object().
However for my current use-case I just want to read out this ID from an GObject. What's the API to do so ?
You can't. The builder ID is stored in the builder internally, not in the GObject.
The reason for this is that IDs must be unique per builder, which would be impossible to enforce if you were able to get and set them via some GObject API.
You could use gtk_widget_get_name() to identify an object.
It is possible using Gtk.Buildable.get_name(object). This method will return the Glade object id.
This snippet will print all object ids in your Glade XML:
builder = Gtk.Builder()
builder.add_from_file("my-window.glade"))
for obj in builder.get_objects():
print(Gtk.Buildable.get_name(obj))
As stated by #ptomato it's seems not possible.
I found that in that line in the documentation:
All the fields in the GObject structure are private to the
implementation and should never be accessed directly.
But you can circumvent it because at one point in your code you were refering to it by the id that you typed in (or the code you wrote type in) so you just need to store it at that point. And link it somehow (with a variable or a data structure) to the name of the variable holding the object.

AS3 targeting controller class variable using string

I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.
It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.
It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher

In "cache" class, where does directory setup go?

I have a class that is used to store and retrieve image data from a cache using NSFileManager. When an instance of it is created, I want to check whether the image directory already exists, and if not, create it. Where is the most appropriate place to put this code? Is this something one would override the designated initializer for?
Thanks for reading.
The initialiser (init) function would be the best place to do it from a programming perspective because the rest of the instance methods would probably rely on having access to the directory to store/retrieve images.
You'd also want any instances created to know whether the accessing/creating was successful so in your initialiser you may wish to put some error handling which returns a nil instance (or throws an exception) if it can't be accessed which can then be handled by the classes which use the instance of your cache class.

Dont understand the concept of extends in URL.openConnection() in JAVA

Hi I am trying to learn JAVA deeply and so I am digging into the JDK source code in the following lines:
URL url = new URL("http://www.google.com");
URLConnection tmpConn = url.openConnection();
I attached the source code and set the breakpoint at the second line and stepped into the code. I can see the code flow is: URL.openConnection() -> sun.net.www.protocol.http.Handler.openConnection()
I have two questions about this
First In URL.openConnection() the code is:
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
handler is an object of URLStreamHandler, define as blow
transient URLStreamHandler handler;
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right? But there are a lot classes who implement this methods in sun.net.www.protocol (like http.Hanlder, ftp.Handler ) How should the code know which "openConnection" method it should call? In this example, this handler.openConnection() will go into http.Handler and it is correct. (if I set the url as ftp://www.google.com, it will go into ftp.Handler) I cannot understand the mechanism.
second. I have attached the source code so I can step into the JDK and see the variables but for many classes like sun.net.www.protocol.http.Handler, there are not source code in src.zip. I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip? Where can I find a comprehensive version of source code?
Thanks!
First the easy part:
... I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip?
Two reasons:
In the old days when the Java code base was proprietary, this was treated as secret-ish ... and not included in the src.zip. When they relicensed Java 6 under the GPL, they didn't bother to change this. (Don't know why. Ask Oracle.)
Because any code in the sun.* tree is officially "an implementation detail subject to change without notice". If they provided the code directly, it helps customers to ignore that advice. That could lead to more friction / bad press when customer code breaks as a result on an unannounced change to sun.* code.
Where can I find a comprehensive version of source code?
You can find it in the OpenJDK 6 / 7 / 8 repositories and associated download bundles:
http://hg.openjdk.java.net/jdk6/jdk6 - http://download.java.net/openjdk/jdk6/
http://hg.openjdk.java.net/jdk7/jdk7 - http://download.java.net/openjdk/jdk7/
http://hg.openjdk.java.net/jdk8/jdk8
Now for the part about "learning Java deeply".
First, I think you are probably going about this learning in a "suboptimal" fashion. Rather than reading the Java class library, I think you should be reading books on java and design patterns and writing code for yourself.
To the specifics:
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right?
At the point that the handler calls than method, it is calling it on an instance of the subclass. So finding the right method is handled by the JVM ... just like any other polymorphic dispatch.
The tricky part is how you got the instance of the sun.net.www.protocol.* handler class. And that happens something like this:
When a URL object is created, it calls getURLStreamHandler(protocol) to obtain a handler instance.
The code for this method looks to see if the handler instance for the protocol already exists and returns that if it does.
Otherwise, it sees if a protocol handler factory exists, and if it does it uses that to create the handler instance. (The protocol handler factory object can be set by an application.)
Otherwise, searches a configurable list of Java packages to find a class whose FQN is package + "." + protocol + "." + "Handler", loads it, and uses reflection to create an instance. (Configuration is via a System property.)
The reference to handler is stored in the URL's handler field, and the URL construction continues.
So, later on, when you call openConnection() on the URL object, the method uses the Handler instance that is specific to the protocol of the URL to create the connection object.
The purpose of this complicated process is to support URL connections for an open-ended set of protocols, to allow applications to provide handlers for new protocols, and to substitute their own handlers for existing protocols, both statically and dynamically. (And the code is more complicated than I've described above because it has to cope with multiple threads.)
This is making use of a number of design patterns (Caches, Adapters, Factory Objects, and so on) together with Java specific stuff such as the system properties and reflection. But if you haven't read about and understood those design patterns, etcetera, you are unlikely to recognize them, and as a result you are likely to find the code totally bamboozling. Hence my advice above: learn the basics first!!
Take a look at URL.java. openConnection uses the URLStreamHandler that was previously set in the URL object itself.
The constructor calls getURLStreamHandler, which generates a class name dynamically and loads, and the instantiates, the appropriate class with the class loader.
But URLStreamHandler is a abstract class and method openConnection()
is not implement in it so when handler calls this method, it should go
to find a subclass who implement this method, right?
It has to be declared or abstract or implemented in URLStreamHandler. If you then give an instance of a class that extends URLStreamHandler with type URLStreamHandler and call the openConnection() method, it will call the one you have overriden in the instance of the class that extends URLStreamHandler if any, if none it will try to call the one in URLStreamHandler if implemented and else it will probably throw an exception or something.

Setting global variables in working memory in Drools planner

How do I add a global variable to working memory in drools planner's solver to be able to use in scores drool. This is similar to https://issues.jboss.org/browse/JBRULES-2700 but couldn't find a solution though.
What you might be looking for is a #ProblemFactProperty.
Quoting from the documentation:
All objects returned by those [annotated] methods will be inserted into the
ConstraintStreams or Drools session, so the constraint steams or score
rules can access them.
In my own words: You can hold a reference to your global object in your #PlanningSolution class. If you annotate its getter with #ProblemFactProperty you can access it from your drools file.
First some preaching: Using a service (set as a global) to calculate part of the score will break delta based score calculation (read the manual section on that topic), resulting in much less score calculations per second (say 50 instead of 5000 per second on big data sets).
Then a HACK solution: In the StartingSolutionInitializer (soon known as CustomSolverPhaseCommand) do solverScope.getWorkingMemory().setGlobal("key", value).
Then a real, long-term solution: Could you motivate why you need to be able to do this? We can think about adding support for this with something like an optional WorkingMemoryPreperator.
After set the planningProblem:
solver.setPlanningProblem(planningProblem);
You can get access the workingMemory via solutionDirector(HACK) :
DefaultSolutionDirector solutionDirector = ((DefaultSolver)solver).getSolverScope().getSolutionDirector();
solutionDirector.getWorkingMemory().setGlobal("list", new ArrayList<String>());
Cheers!
If you need to use some helper methods in the planner rules, try the following approach which I used in my project:
Create a utility class which includes the helper methods.
Import the utility class in the rule file like importing it in a java class.
Use the helper method in the rule. If you want to use a helper method in the condition, wrap using eval(). If you want to use a helper method in the then part, just use it as normal java method call.
For example, say you have a utility class named PlanningUtil like below:
public class PlanningUtil {
public boolean isGood() {return true;}
public void doSomething() {//...}
}
Then import the utility class in the rule file,
import PlanningUtil;
Use the utility method in the rule
rule "MyRule"
when
eval(PlanningUtil.isGood())
then
PlanningUtil.doSomething(); // note the ';' is a must.
end