Is there any way to define methods for data model when using FMPP? - fmpp

I want to add methods to my datamodel so I need a way to specify them inside my tdd data file(s).
For example having a tdd data file containing two scalars :
a: 1
b: 1
I would like to add a method area which multiplies them.
Is this even possible and if so how do I achieve this?

So let's say you have MyUtils that has a foo() and a bar() methods, and you want to access those in the templates.
You can add an arbitrary Java objects to the model using the eval data loader in data, like myUtils: eval('new com.example.MyUtils()'). Then you can issue myUtils.foo() in the templates. But, you wanted to add the methods at top level. That's also possible. Both in eval and in a custom DataLoader (whichever you want to use) you have access to engine, the fmpp.Engine object. And then you can pull this trick:
// Note: In case you are using eval, use Java 1.2 syntax (no generics).
TemplateHashModel myUtilsModel = (TemplateHashModel) engine.wrap(new MyUtils());
Map<String, TemplateModel> myUtilsMethodModels = new HashMap<>();
myUtilsMethodModels.put("foo", myUtilsModel.get("foo"));
myUtilsMethodModels.put("bar", myUtilsModel.get("bar"));
return myUtilsMethodModels;
Then you add that Map to data without a name. (If you add a Map to data without a name, its keys become top-level variables.)
Certainly it can be polished to be nicer, like find methods you want automatically, etc. Plus I did not try this above (so typos are possible). But this is the basic idea. (I guess it would be practical if FMPP had a data loader that loads the static methods of a class... But, right now it doesn't have that.)

Related

Is there a way to get scrollstate from Lazyrow

I have made a LazyRow that i now want to be able to get the scrollposition from. What i understand Scrollablerow has been deprecated. (correct me if im wrong) The thing is that i cant make a scrollablerow so i thought lets make a lazy one then. but i have no clue how to get scrollposition from the lazyrow. i know how to get index but not position if that eaven exists. here is what i have tried.
val scrollState = rememberScrollState()
LazyRow(scrollState = scrollstate){
}
For LazyScrollers, there are separate LazyStates.
I think there's just one, in fact, i.e. rememberLazyListState()
Pass that as the scroll state to the row and then you can access all kinds of info. For example, you could get the index of the first visible item, as well as its offset. There are direct properties for this stuff in the object returned by the above initialisation. You can also perform some more complex operations using the lazyListState.layoutInfo property that you get.
Also, ScrollableRow may be deprecated as a #Composable, but it is just refactored, a bit. Now, you can use the horozontalScroll() and verticalScroll() Modifiers, both of which accept a scrollState parameter, which expects the same object as the one you've created in the question.
Usually, you'd use LazyScrollers since they're not tough to implement and also are super-performant, but the general idea is that they are used with large datasets whereas non-lazy scrollers are okay for small sized lists and stuff. This is because the lazy ones cache only a small fraction of the entire list, making your UI peformant, which is not something regular scrollers do, and not a problem for small datasets.
They're like equivalents of RecyclerView from the View System

Generic map objects

I am trying to create an Asset Manager (Much like the one that is provided in the Libgdx library) for SFML in C++. But I am running into the age old problem of templates being one of the worst parts of C++.
I am trying to have a map object hold generic types, the key would be a simple string and the data would be any type I want it to be. Note, I don't want to template the map object to simply hold one generic type throughout the entire map (IE, the map being <string, int>). I want to have different types in the same map so I can load many different assets.
Is there any way I can do something like this?
Thank you for your help and consideration, any little tip goes a long way.
I reiterate my comment about a redesign using a map of manager instead.
Then you could have e.g.
class basic_asset_manager { ... };
class image_asset_manager : public basic_asset_manager { ... };
...
std::unordered_map<std::string, basic_asset_manager*> asset_managers;
asset_managers["image"] = new image_asset_manager;
...
// Load an image from a file
asset_managers["image"]->load("some alias for image", "/some/file/name");
...
// Get image
image = asset_manager["image"]->get("some alias for image");
Maybe not exactly like this, but you hopefully get the point.
You could define a struct or in some cases possibly use a union to pass as the second parameter of the map. Might not be the most elegant solution, but can get the job done.

Django Template set of sets

Is it possible to access a set of a set in django template.
ie. a.b_set.c_set.count
so it gets a count of all c objects related to all b objects which are related to c.
I know I can make a query in the backend ie c.objects.filter(b__a=a), however I wish to do it from the template alone.
Cheers,
Emmet
This may not be possible to do from the template, since it was never intended to use "complex" logic. You should do it in the view.
Since what you want to get is a new attribute "per queryset", this is no one-liner.
Example:
as = a.objects.all()
for a in as:
a.b_c_count = c.objects.filter(b__a=a).count()
And use it like that in the template:
a.b_c_count
If you have a lot of a objects, this will be a bottleneck, so you may want to try the extra method (and use as = a.objects.all().extra(*parameters)), or even raw sql.

How can I use lua to create levels and maps in cocos2d

I have this idea, where I want to use lua to create my levels, and the maps inside those levels. I want to simply and explicitly be able to manipulate data and add new levels as buy ins in the app store. How can I use lua to create maps and levels inside those maps? Does lua support OOP so I can make a base Map "class" and a base Level "class" or do I need to hardcode everything? I know for a fact that angry birds uses lua, so can I?
Any directions or samples are much appreciated. Thanks.
Lua does not support classes directly (although there are some libraries which offer class-like functionality), instead it uses data structures called tables. Tables are very versatile because they can contain strings, numbers, functions and other tables.
The big benefit of Lua is that it is scripted, so it can be downloaded as a file and run while the compiled game is running. Here's a possible example of level stored in a .lua file:
return {
name = 'Example level',
score = 80,
map = {
height = 8,
width = 8,
data = 'sssssssssoooooossoooooossoooooossoooooossoooooossbooooesssssssss'
},
ondraw = function (self)
drawmap(self.map)
drawscore(self.score)
end
}
Another feature which you may find useful are metatables. They sort-of allow inheritance to be used with tables. You can read more about implementing classes with metatables here: http://lua-users.org/wiki/SimpleLuaClasses

unit testing a factory method

suppose I have several OrderProcessors, each of them handles an order a little differently.
The decision about which OrderProcessor to use is done according to the properties of the Order object, and is done by a factory method, like so:
public IOrderProcessor CreateOrderProcessor(IOrdersRepository repository, Order order, DiscountPercentages discountPercentages)
{
if (order.Amount > 5 && order.Unit.Price < 8)
{
return new DiscountOrderProcessor(repository, order, discountPercentages.FullDiscountPercentage);
}
if (order.Amount < 5)
{
// Offer a more modest discount
return new DiscountOrderProcessor(repository, order, discountPercentages.ModestDiscountPercentage);
}
return new OutrageousPriceOrderProcessor(repository, order);
}
Now, my problem is that I want to verify that the returned OrderProcessor has received the correct parameters (for example- the correct discount percentage).
However, those properties are not public on the OrderProcessor entities.
How would you suggest I handle this scenario?
The only solution I was able to come up with is making the discount percentage property of the OrderProcessors public, but it seems like an overkill to do that just for the purpose of unit testing...
One way around this is to change the fields you want to test to internal instead of private and then set the project's internals visible to the testing project. You can read about this here: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx
You would do something like this in your AssemblyInfo.cs file:
[assembly:InternalsVisibleTo("Orders.Tests")]
Although you could argue that your unit tests should not necessarily care about the private fields of you class. Maybe it's better to pass in the values to the factory method and write unit tests for the expected result when some method (assuming Calculate() or something similar) is called on the interface.
Or another approach would be to unit test the concrete types (DiscountOrderProcessor, etc.) and confirm their return values from the public methods/properties. Then write unit tests for the factory method that it correctly returns the correct type of interface implementation.
These are the approaches I usually take when writing similar code, however there are many different ways to tackle a problem like this. I would recommend figuring out where you would get the most value in unit tests and write according to that.
If discount percentage is not public, then it's not part of the IOrderProcessor contract and therefore doesn't need to be verified. Just have a set of unit tests for the DiscountOrderProcessor to verify it's properly computing your discounts based on the discount percent passed in via the constructor.
You have a couple of choices as I see it. you could create specializations of DiscountOrderProcessor :
public class FullDiscountOrderProcessor : DiscountOrderProcessor
{
public FullDiscountOrderProcessor(IOrdersRepository repository, Order order):base(repository,order,discountPercentages.FullDiscountPercentage)
{}
}
public class ModestDiscountOrderProcessor : DiscountOrderProcessor
{
public ModestDiscountOrderProcessor (IOrdersRepository repository, Order order):base(repository,order,discountPercentages.ModestDiscountPercentage)
{}
}
and check for the correct type returned.
you could pass in a factory for creating the DiscountOrderProcessor which just takes an amount, then you could check this was called with the correct params.
You could provide a virtual method to create the DiscountOrderProcessor and check that is called with the correct params.
I quite like the first option personally, but all of these approaches suffer from the same problem that in the end you can't check the actual value and so someone could change your discount amounts and you wouldn't know. Even wioth the first approach you'd end up not being able to test what the value applied to FullDiscountOrderProcessor was.
You need to have someway to check the actual values which leaves you with:
you could make the properties public (or internal - using InternalsVisibleTo) so you can interrogate them.
you could take the returned object and check that it correctly applies the discount to some object which you pass in to it.
Personally I'd go for making the properties internal, but it depends on how the objects interact and if passing a mock object in to the discount order processor and verifying that it is acted on correctly is simple then this might be a better solution.