dart gRPC: what the meaning of the function? - flutter

I'm new in flutter(dart) gRPC. I'm learing the tutorial given by https://grpc.io/docs/languages/dart/basics/. But I got confused about the dart syntax in this function.
Future<Feature> getFeature(grpc.ServiceCall call, Point request) async {
return featuresDb.firstWhere((f) => f.location == request,
orElse: () => Feature()..location = request);
}
Actually, I don't understand what argument f means and why there is an orElse. I have found => means arrow function and it can be simply understood as return sentence, but I can't say I figure it out toally. Any explanation would be appreciated.

firstWhere method takes a Predicate. A Predicate is just a function that takes in an object, and returns true or false. So basically it's saying "give me the first object from this list where the function I'm giving you returns true. The orElse is an optional, named parameter that says, if you've gotten to the end of the list and not a single object returned true when passed through the function I just supplied, then execute this function as a last resort and return whatever value it produces. You can think of a Predicate like a filter. It takes an object and returns true if it should pass through the filter, or false if it should not pass through the filter. firstWhere basically goes through each element checking to see if it passes through the filter, and the first time something does, it returns that element. If nothing makes it through the filter, it uses the orElse producer function to generate some value to return, since nothing made it through on it's own.
(f) => f.location == request is a function that returns true or false based on it's argument - it's a Predicate
() => Feature()..location = request is a Producer. A function that has no argument, but produces a value. In this case, a value that is equal to a new Feature with a location value equal to request. An assignment evaluates to the value that was assigned. The cascade .. ensures that the Feature will be returned, instead of the Point object, request.
So basically you can think of it like this:
list.giveMeTheFirstObjectWhere(thisFunctionReturnsTrue, orElse: giveMeTheValueThisFunctionProvidesIfNoneOfTheElementsReturnedTrueUsingTheOtherFunction)
So the purpose of this code seems to be, checking if a Feature already exists, and if it does, it returns the first such Feature. If it doesn't exist, it creates a new Feature and returns it (however, this newly created one isn't automatically added to the list/db)

Related

Using Gio.SimpleAction argument in stateless action

The documentation for Gio.SimpleAction.new says that I can specify a name, which is a string, and a parameter type, which is a GLib.VariantType (or None). If I specify a GLib.VariantType for the second argument, how do I specify its value?
I know that I can specify an argument in the connect call for the action, but then the first argument in the handler gets None. It seems as if it could be useful to specify a value for that argument, but I am not seeing how that is done.
You specify it's value in g_action_activate.
Thus, you do the following, e.g. for boolean:
vtype = GLib.VariantType.new("b")
action = Gio.SimpleAction.new("name", vtype)
# action.connect ("activate", handler, *args)
value = GLib.Variant.new_boolean (True)
a.activate(value)

ECMAScript 5.1 internal method [[Call]]

I need help in understanding that algorithm:
[[Call]]
When the [[Call]] internal method for a Function object F is called with a this value and a list of arguments, the following steps are taken:
Let funcCtx be the result of establishing a new execution context for function code using the value of F's [[FormalParameters]] internal property, the passed arguments List args, and the this value as described in 10.4.3.
Let result be the result of evaluating the FunctionBody that is the value of F's [[Code]] internal property. If F does not have a [[Code]] internal property or if its value is an empty FunctionBody, then result is (normal, undefined, empty).
Exit the execution context funcCtx, restoring the previous execution context.
If result.type is throw then throw result.value.
If result.type is return then return result.value.
Otherwise result.type must be normal. Return undefined.
https://www.ecma-international.org/ecma-262/5.1/#sec-13.2.1
Exactly I need in explanation in 2,4,5,6 clauses.
About 2: First, what does the result of the FunctionBody calculation mean? How is it calculated? What does it mean there is no [[Code]] property when this happens? And most importantly, what does this record mean (normal, undefined, empty).
About 4,5,6: What does result.type mean, result.value? Where does this value come from? Explain for each point
P.S If you vote down, explain why you do that!
First, the [[Call]] is propabily about Function.prototype.call(), so it's better to understand call() first because it's easier than algorithm.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
I get this sample code from the MDN, and try to answer the question roughly. (If you want to understand in detail, you and I have to understand the whole specification, but I don't!)
function greet() {
var reply = [this.person, 'Is An Awesome', this.role].join(' ');
console.log(reply);
}
var obj = {
person: 'Douglas Crockford', role: 'Javascript Developer'
};
greet.call(obj); // Douglas Crockford Is An Awesome Javascript Developer
About 2
First, what does the result of the FunctionBody calculation mean?
FunctionBody is function's code. From the sample, FunctionBody is below.
var reply = [this.person, 'Is An Awesome', this.role].join(' ');
console.log(reply);
the result of the FunctionBody calculation is the result of the code execution. The result is expressed by Completion Specification Type(explain below). It includes the function return value, but has more wider information.
What does it mean there is no [[Code]] property when this happens?
It's mean empty function as below.
function greet() {
// empty
}
And most importantly, what does this record mean (normal, undefined, empty).
It's Completion Specification Type. This is an expression for value or statement in specification.
Values of the Completion type are triples of the form (type, value, target).
About 4,5,6
What does result.type mean, result.value? Where does this value come from? Explain for each point
result is Completion Specification Type, and the form is (type, value, target).

When does Chapel pass by reference and when by constant?

I am looking for examples of Chapel passing by reference. This example works but it seems like bad form since I am "returning" the input. Does this waste memory? Is there an explicit way to operate on a class?
class PowerPuffGirl {
var secretIngredients: [1..0] string;
}
var bubbles = new PowerPuffGirl();
bubbles.secretIngredients.push_back("sugar");
bubbles.secretIngredients.push_back("spice");
bubbles.secretIngredients.push_back("everything nice");
writeln(bubbles.secretIngredients);
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
bubbles = kickAss(bubbles);
writeln(bubbles.secretIngredients);
And it produces the output
sugar spice everything nice
sugar spice everything nice Chemical X
What is the most efficient way to use a function to modify Bubbles?
Whether Chapel passes an argument by reference or not can be controlled by the argument intent. For example, integers normally pass by value but we can pass one by reference:
proc increment(ref x:int) { // 'ref' here is an argument intent
x += 1;
}
var x:int = 5;
increment(x);
writeln(x); // outputs 6
The way that a type passes when you don't specify an argument is known as the default intent. Chapel passes records, domains, and arrays by reference by default; but of these only arrays are modifiable inside the function. ( Records and domains pass by const ref - meaning they are passed by reference but that the function they are passed to cannot modify them. Arrays pass by ref or const ref depending upon what the function does with them - see array default intent ).
Now, to your question specifically, class instances pass by "value" by default, but Chapel considers the "value" of a class instance to be a pointer. That means that instead of allowing a field (say) to be mutated, passing a class instance by ref just means that it could be replaced with a different class instance. There isn't currently a way to say that a class instance's fields should not be modifiable in the function (other than making them to be explicitly immutable data types).
Given all of that, I don't see any inefficiencies with the code sample you provided in the question. In particular, here:
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
the argument accepting b will receive a copy of the pointer to the instance and the return b will return a copy of that pointer. The contents of the instance (in particular the secretIngredients array) will remain stored where it was and won't be copied in the process.
One more thing:
This example works but it seems like bad form since I am "returning" the input.
As I said, this isn't really a problem for class instances or integers. What about an array?
proc identity(A) {
return A;
}
var A:[1..100] int;
writeln(identity(A));
In this example, the return A in identity() actually does cause a copy of the array to be made. That copy wasn't created when passing the array in to identity(), since the array was passed by with a const ref intent. But, since the function returns something "by value" that was a reference, it's necessary to copy it as part of returning. See also arrays return by value by default in the language evolution document.
In any case, if one wants to return an array by reference, it's possible to do so with the ref or const ref return intent, e.g.:
proc refIdentity(ref arg) ref {
return arg;
}
var B:[1..10] int;
writeln(refIdentity(B));
Now there is no copy of the array and everything is just referring to the same B.
Note though that it's currently possible to write programs that return a reference to a variable that no longer exists. The compiler includes some checking in that area but it's not complete. Hopefully improvements in that area are coming soon.

Correct way to return function value instead of binding in Coffeescript

I can't seem to find a concise answer to this question. What is the correct coffeescriptic way to return the value from _otherInstanceMethod when calling #_instanceMethod instead of the function binding itself?
x = _instanceMethod: () ->
#_otherInstanceMethod key: 'value'
Edit (thanks commenters)
This returns:
x = function () {
[...] # function body omitted
});
Instead of
x = 'some value returned by _otherInstanceMethod'
I would like the value to be returned instead of the function binding to _otherInstanceMethod
Being totally new to Coffeescript, this was my fault. I was calling the instance method like:
#_instanceMethod
instead of
#_instanceMethod()
Sorry for the trouble, voting to delete
In CoffeeScript #something translated into this.something regardless of the underlying variable type. This means you can use # only in conjuction with properties, with methods you still ought to use good old this.

How to bind parameters in replaced expression nodes in Entity Framework on the fly

I'm trying to replace a function call like (simplified) Utility.GetString(MyEntity.SomePropertyWithRelatedEntity)=="abc" with an expression visitor into something like p => p.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag==true).SomePropertyWithRelatedEntity.
It means, the datamodel goes like:
MyEntity -> RelatedEntity -> SubRelatedEntity
I'm trying to return a string value from the SubRelatedEntity, based on some rules in the RelatedEntity, so I don't have to re-write / copy/paste the whole filtering rules in every usage; that's why I put inside a "call-signature", so my expression visitor can identify it and replace the fake-call to Utility.GetString to some complicated lambda expressions.
My expression visitor contains something like:
public override Expression Visit(Expression node)
{
if (node == null)
return null;
Expression result = null;
if (node.NodeType == ExpressionType.Call)
{
MethodCallExpression mce = node as MethodCallExpression;
if (mce.Method.DeclaringType == typeof(Utility) && mce.Method.Name == "GetString")
{
Expression<Func<RelatedEntity, string>> exp = re => re.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag == true).SomeStringValue;
result = exp.Body;
}
else
result = base.Visit(node);
}
else
result = base.Visit(node);
return result;
}
Now, the problem is, the "sre" parameter is not bound when called the injected lambda expression. After much research, I see the lambda parameters should be replaced with another expression visitor, specifically searching for the new parameters and replacing them with the old ones. In my situation, however, I don't have an "old parameter" - I have the expression MyEntity.SomePropertyWithRelatedEntity (e.g. an property filled with the related entities) which I need to insert somehow in the generated lambda.
I hope my problem is understandable. Thank you for any insights!
After getting no answers for long time and trying hard to find a solution, I've solved it at the end :o)! It goes like this:
The newly injected lambda expression gets an ParameterExpression - well, this is a 'helper', used when directly calling the lambda, what I don't want (hence, 'parameter not bound' exception when ToEnumerable is called). So, the clue is to make a specialized ExpressionVisitor, which replaces this helper with the original expression, which is of course available in the Arguments[] for the method call, which I try to replace.
Works like a charm, like this you can reuse the same LINQ expressions, something like reusable sub-queries, instead of writing all the same LINQ stuff all time. Notice as well, that expression calling a method is not allowed in EF, in Linq2Sql it worked. Also, all the proposed web articles only replace the parameter instances, when constructing/merging more LINQ expressions together - here, I needed to replace a parameter with an faked-method-call argument, e.g. the method should not be called, it only stands for a code-marker, where I need to put my LINQ sub-query.
Hope this helps somebody, at the end it's pretty simple and logical, when one knows how the expression trees are constructed ;-).
Bye,
Andrej