Dhall - map on record field - functor

I have a type
let Resource = \(a : Type) ->
{ name : Text
, type : Text
, properties : a
}
and a function foo : InstanceTemplateProperties -> Properties.
I need to create a function Resource InstanceTemplateProperties -> Resource Properties.
I could write it as
\(p : Resource InstanceTemplateProperties) ->
{ name = p.name
, type = p.type
, properties = foo p.properties
} : Resource Properties
but it looks really cumbersome. Is there an easier and more idiomatic way to do this?

You can use // to merge the updated properties into the original.
(\p : Resource InstanceTemplateProperties) ->
p // {properties = foo p.properties)

Related

How to update a field/value inside a model?

If my model looks like:
type alias Application = { id : Int , term : Int , amount : Int }
type alias Model = { application : Application }
and I am trying to update the term value, I have onInput UpdateTerm on an input inside my update case statement how do I update this value?
so far I have UpdateTerm term ->; but unsure how I can update only the term value inside application?
Record field update is described in the guide and also in the reference documentation. Updating a field in a record nested inside another record is simply a matter of doing one after the other. Assuming you have a binding named model:
let
application =
model.application
updatedApplication =
{ application | term = term }
in
{ model | application = updatedApplication }
for a better readability you can make function like this:
update msg model =
case msg of
changeNestedProperty property ->
({ model | record= setNestedProperty property model.record } , Cmd.none)
setNestedProperty : String -> Record-> Record
setNestedProperty property record =
{ record | nestedProperty = property }

Accessing IList<T> inside Alea.Gpu.Default.For

I am trying to access values of System.Collections.Generic.IList<T> which is declared outside Alea.Gpu.Default.For.
[GpuManaged]
private void Evaluate_Caching(IList<TGenome> genomeList)
{
var gpu = Gpu.Default;
gpu.For(0, genomeList.Count - 1, i =>
{
TGenome genome = genomeList[i];
TPhenome phenome = (TPhenome)genome.CachedPhenome;
if (null == phenome)
{ // Decode the phenome and store a ref against the genome.
phenome = _genomeDecoder.Decode(genome);
genome.CachedPhenome = phenome;
}
if (null == phenome)
{ // Non-viable genome.
genome.EvaluationInfo.SetFitness(0.0);
genome.EvaluationInfo.AuxFitnessArr = null;
}
else
{
FitnessInfo fitnessInfo = _phenomeEvaluator.Evaluate(phenome);
genome.EvaluationInfo.SetFitness(fitnessInfo._fitness);
genome.EvaluationInfo.AuxFitnessArr = fitnessInfo._auxFitnessArr;
}
});
}
With reference to one of the questions asked earlier iterate-over-a-collection-of-custom-classes-with-alea-gpu I have also enabled <memory allowNonBlittableMemoryTransfer="true"/> in App.config.
However I am getting an error as
"Cannot get field "genomeList".
Possible reasons:
-> The field type is not supported.
-> In closure class, the field doesn't have [GpuParam] attribute.
Diagnostics:
-> Struct: ref(dyn{ i32 }(m:<Evaluate_Caching>b__0)):_O_
-> FieldName: genomeList
Source location stack:
-> in E:\_turingProjects\_csProjects\Gpu_Project\GpuParallelGenomeListEvaluator.cs(183,17-183,48)
-> at Evaluators.GpuParallelGenomeListEvaluator`2+<>c__DisplayClass17_0[SharpNeat.Genomes.Neat.NeatGenome,SharpNeat.Phenomes.IBlackBox].[Void <Evaluate_Caching>b__0(Int32)]
-> at Alea.Parallel.Device.DeviceFor.[Void Kernel(Int32, Int32, System.Action`1[System.Int32])]
-> at defining runtime64 (sm50,64bit)
Loading method as kernel:
-> Method: Alea.Parallel.Device.DeviceFor.[Void Kernel(Int32, Int32, System.Action`1[System.Int32])]
-> InstanceOpt: <None>
-> Argument.#0: 0
-> Argument.#1: 1999
-> Argument.#2: System.Action`1[System.Int32]
What could be the possible reason of error? What is the correct way to use values inside Gpu.For ?
Currently, AleaGPU only works with array. List usually require dynamic memory allocation, such as add element, which is not efficient in GPU.

Scala Generics - Overloaded method

Considering the given code:
val repository =
context.getBean(
Introspector.decapitalize(t.getClass.getSimpleName).replace("C", "E").concat("Repository"))
and that my repositories have a String as Serializable.
I'm trying to do the following:
repository.asInstanceOf[ElasticsearchRepository[_, String]].save(getObject(t))
This one works fine:
repository.asInstanceOf[ElasticsearchRepository[_, String]].findAll()
But I don't know how to put that above to work.
Assuming the method getObject(t) is retuning the correct object to be persisted and since it's a Spring Data Repository, there are 2 save method. One that accept a single entity and another for a list of entities and it says overloaded method value save.
What I have tried so far:
I saw in another thread to force the method with a type, something like this:
repository.asInstanceOf[ElasticsearchRepository[_, String]].save(getObject(t) : TYPE)
This is ok if I knew the type and also my method getObject should return that same type.
Here is my getObject method which I return the object itself without any specific type:
#throws[IOException]
def getObject[T](t : T) = {
objectMapper.readValue(objectMapper.writeValueAsString(t), getClazz(t))
}
So I was trying to get the type like this:
val m = Manifest.classType(getClazz(t))
type TYPE = m.type
Looks good if I force my object to this type using getObject(t) : TYPE but I don't know how to use this same type in my getObject method to be returned.
Anyway, I don't even know if this is the best approach to do this, invoking a generic repository and save a generic object.
Just to understand what I'm trying to do, I'm using a aspect to intercept a Cassandra entity to be persisted, then get it and turn into a ElasticSearch entity to save a json(thats why the getObject(t)) and replicate into ElasticSearch.
Here is the full aspect class:
#Component
#Aspect
class ElasticAop {
#Autowired val context : ApplicationContext = null
val objectMapper : ObjectMapper = new ObjectMapper()
#Pointcut("execution(* com.test.service.cassandra.*.post(..)) && args(t)")
def getPointcutPost[T](t : T) : Unit = {}
#throws[Throwable]
#Before("getPointcutPost(t)")
def elasticSaveAspect[T](joinPoint: JoinPoint, t: T) = {
val m = Manifest.classType(getClazz(t))
type TYPE = m.type
val repository =
context.getBean(
Introspector.decapitalize(t.getClass.getSimpleName).replace("C", "E").concat("Repository"))
repository.asInstanceOf[ElasticsearchRepository[_, String]].findAll()
repository.asInstanceOf[ElasticsearchRepository[_, String]].save(getObject(t))
}
#throws[ClassNotFoundException]
def getClazz[T](t : T) = {
val className = t.getClass.getName.replace("cassandra", "elastic").replace("C", "E")
Class.forName(className)
}
#throws[IOException]
def getObject[T](t : T) = {
objectMapper.readValue(objectMapper.writeValueAsString(t), getClazz(t))
}
}
EDITED
Even setting up a type return in my getObject to Address and then setting the save method as follow save(getObject(t) : Address) give me the same overloaded error.
EDITED
I just figured out it's a limitation and a possible work around is to create a factory or something like this.
Then I created a service with a saveOrUpdate method:
trait ElasticGenericService[T <: ElasticGenericKey, R <: ElasticsearchRepository[T, String]] {
var r : R = _
def saveOrUpdate(t: T) = r.save(t)
}
and now I'm getting a cast exception:
java.lang.ClassCastException: Address cannot be cast to scala.runtime.Nothing$
What i can see here:
getObject[T](t : T) returns existential type _1 and actually kills all type checks, as you choosing the class in runtime
ElasticsearchRepository[_, String].save require existential type _2 to be passed to the save method, so _1 doesn't fit
Possible solution:
repository.asInstanceOf[ElasticsearchRepository[Any, String]].save(getObject(t).asInstanceOf[Any]) //getClass will work with runtime class instead of Any, so should be fine
Another solution (saving existential type):
def getObject[T](t : T) = {
objectMapper.readValue(objectMapper.writeValueAsString(t), getClazz(t)).asInstanceOf[T]
} //assuming T is an existential - it will return same existential as you passed

mandatory property in return object of an EF linq query

In my application, i have several linq queries who must return the same object type with the same properties in the same order.
So, how can i define mandatory properties of a return object ?
Queries are like this :
from foo in bar
select new myobject {
myprop1 = foo.x, //This one must be filled everytime
myprop2 = foo.y
}
Thank's by advance !
Assuming foo.x is a nullable integer, how about something like
from foo in bar
select new myobject {
myprop1 = foo.x ==null ? 0 : foo.x ,
myprop2 = foo.y
}

If else condition in LINQ to XML query in c#

this is xml let say:
<.Sections>
<.SECTION ID ="4" NAME="GetStudents" CONTROL-TYPE="Button" LINK="WebForm2.aspx">
</SECTION>
<.SECTION ID="5" NAME="SelectStudent" CONTROL-TYPE="Drowpdown" METHOD ="selectList_MethodName">
</SECTION>
Observe this xml, I am generating the UI controls base on "CONTROL-TYPE" Attributes. but there are different attributes are there in both sections elements. as LINK and METHOD . I want to query like this , if section's CONTROL-TYPE=="Button" then get value of LINK attribute Else If CONTROL-TYPE=="Drowpdown" then get value of METHOD attribute Else If.
I am trying to write code in c# +ASP.net. how to achieve this? is there way get such data ?
NOTE: please don't go on dot inside tag as <.SECTION>. it is for this forum page understanding.
Well, the simplest way is either an explicit if/else:
string value;
string controlType = (string) element.Attribute("CONTROL-TYPE");
if (controlType == "Button")
{
value = (string) element.Attribute("LINK");
}
else if (controlType == "Dropdown")
{
value = (string) element.Attribute("METHOD");
}
else
{
// What do you want to happen if it's neither of these?
}
... or use the conditional operator if you're happy with a simple default value for other control types:
string controlType = (string) element.Attribute("CONTROL-TYPE");
string value = controlType == "Button" ? (string) element.Attribute("LINK")
: controlType == "Dropdown" ? (string) element.Attribute("METHOD")
: "default value";
EDIT: Within a query expression, there are two reasonable ways to do this. First, you could use the conditional operator and a let clause to fetch the control type just once:
var query =
from element in elements
let controlType = (string) element.Attribute("CONTROL-TYPE")
select new {
ID = (string) element.Attribute("ID"),
XYZ = controlType == "Button" ? (string) element.Attribute("LINK")
: controlType == "Dropdown" ? (string) element.Attribute("METHOD")
: "default value"
};
Alternatively - and preferrably, IMO - put this logic into a method, and then call the method from the select clause:
var query =
from element in elements
let controlType = (string) element.Attribute("CONTROL-TYPE")
select new {
ID = (string) element.Attribute("ID"),
XYZ = GetXyz(element);
};
...
private static void GetXyz(XElement element)
{
...
}

Resources