how to convert initialization code that requires an action to F# - f#

I have the following C# code:
var client = new RestClient(url);
client.ConfigureWebRequest((r) =>
{
r.ServicePoint.Expect100Continue = false;
r.KeepAlive = true;
});
in F#, after I initialize the rest client, how can I structure the ConfigureWebRequest call? I don't know the syntax to use.

client.ConfigureWebRequest(fun r ->
r.ServicePoint.Expect100Continue <- false
r.KeepAlive <- true
)

Related

Can milo generate the cutomized datatype using uamodeler/

I have tried milo, but I found it hard to create the data object one by one.
Can milo just generate the corresponding codes by reading the xml files? And how?
Many Thanks!
yes you can
private void addCustomStructTypeVariable(UaFolderNode rootFolder) throws Exception {
NodeId dataTypeId = CustomStructType.TYPE_ID
.localOrThrow(getServer().getNamespaceTable());
NodeId binaryEncodingId = CustomStructType.BINARY_ENCODING_ID
.localOrThrow(getServer().getNamespaceTable());
UaVariableNode customStructTypeVariable = UaVariableNode.builder(getNodeContext())
.setNodeId(newNodeId("HelloWorld/CustomStructTypeVariable"))
.setAccessLevel(AccessLevel.READ_WRITE)
.setUserAccessLevel(AccessLevel.READ_WRITE)
.setBrowseName(newQualifiedName("CustomStructTypeVariable"))
.setDisplayName(LocalizedText.english("CustomStructTypeVariable"))
.setDataType(dataTypeId)
.setTypeDefinition(Identifiers.BaseDataVariableType)
.build();
CustomStructType value = new CustomStructType(
"foo",
uint(42),
true
);
ExtensionObject xo = ExtensionObject.encodeDefaultBinary(
getServer().getSerializationContext(),
value,
binaryEncodingId
);
customStructTypeVariable.setValue(new DataValue(new Variant(xo)));
getNodeManager().addNode(customStructTypeVariable);
customStructTypeVariable.addReference(new Reference(
customStructTypeVariable.getNodeId(),
Identifiers.Organizes,
rootFolder.getNodeId().expanded(),
false
));
}

Translating C# code for ZMQ socket polling to F#

My question concerns translating to F# the answer for this stackoverflow question. I am using the ZeroMQ C# CLR package.
Here is part of the C# (from the answer to the linked post):
ZSocket[] sockets = { receiver1, receiver2 };
ZPollItem[] pollItems = { ZPollItem.CreateReceiver(), ZPollItem.CreateReceiver() };
ZError error;
ZMessage[] msg;
while (true)
{
if (sockets.PollIn(pollItems, out msg, out error, timeout))
{
if (msg[0] != null)
{
// The first message gotten from receiver1
}
if (msg[1] != null)
{
// The second message gotten from receiver2
}
}
}
Here is my attempt at the translation:
let ctx = new ZeroMQ.ZContext()
let sub1 = new ZeroMQ.ZSocket(ctx, ZeroMQ.ZSocketType.SUB)
sub1.SubscribeAll()
sub1.Connect("tcp://localhost:3001")
let sub2 = new ZeroMQ.ZSocket(ctx, ZeroMQ.ZSocketType.SUB)
sub2.SubscribeAll()
sub2.Connect("tcp://localhost:3002")
let timeout = System.TimeSpan.FromMilliseconds(10.)
let sockets = [|sub1; sub2|]
let pollItems = [|ZeroMQ.ZPollItem.CreateReceiver(); ZeroMQ.ZPollItem.CreateReceiver()|]
let mutable error = ZeroMQ.ZError
let mutable msg = Array.init<ZeroMQ.ZMessage> 2 // ??? C#: ZMessage[] msg;
while true do
if ZeroMQ.ZPollItems.PollIn(pollItems, &msg, &error, timeout) then // no overloads match
if msg.[0] <> null then
() // work
if msg.[1] <> null then
() // work
()
Maybe the no overload error on the PollIn method line resolves if the ZMessage[] msg is properly defined in F#. I think the library itself is besides the point but happy to provide further details if needed. My main problem is I don't understand C# and barely understand F#.
As the compiler wrote - there is no such overload. Just look at what the function expects to receive:
You forgot to specify the socket as the first parameter.
Timeout must be of type Nullable:
So...
open ZeroMQ
open System
let ctx = new ZContext()
let sub1 = new ZSocket(ctx, ZSocketType.SUB)
sub1.SubscribeAll()
sub1.Connect("tcp://localhost:3001")
let sub2 = new ZSocket(ctx, ZSocketType.SUB)
sub2.SubscribeAll()
sub2.Connect("tcp://localhost:3002")
let timeout = TimeSpan.FromMilliseconds(10.) |> Nullable
let sockets = [|sub1; sub2|]
let pollItems = [|ZPollItem.CreateReceiver(); ZPollItem.CreateReceiver()|]
let mutable error = null
let mutable msg = null
while true do
if ZPollItems.PollIn(sockets, pollItems, &msg, &error, timeout) then
if msg.[0] <> null then
() // work
if msg.[1] <> null then
() // work
()

DART Editor, "Dead code" statement

I'm trying to toggle my menu upon clicking menuicon (defined as #lines) in my code below.
In execution, everything is fine, I mean, once I run the code in DARTIUM it works as I want, the menu is toggled upon the click.
but in Dart editor, I got the error msg in the attached pic, am I doing something wrong in my code?
void main() {
....
var menuToggle =querySelector('#lines')
..onClick.listen((e)=>fonixMenu.hidden=true ? !fonixMenu.hidden : false);
....
}
I think it's telling you that the false in your code will never be reached, because the true causes the first part of the expression to be returned.
You can simplify it to:
onClick.listen((e) => fonixMenu.hidden = !fonixMenu.hidden);
I think what you actually wanted to do was
void main() {
....
var menuToggle =querySelector('#lines')
..onClick.listen((e) => fonixMenu.hidden = fonixMenu.hidden == true ? = false : fonixMenu.hidden = true);
// ^ 2nd =
....
}
but Danny's solution is more elegant when you ensure that fonixMenu.hidden is never null because
var x = null;
var Y = !x
causes an exception:
type 'Null' is not a subtype of type 'bool' of 'boolean expression'.
A simple null-safe variant
var menuToggle =querySelector('#lines')
..onClick.listen((e) => fonixMenu.hidden = fonixMenu.hidden == true ? false : true);

Why am I getting this error in a basic Rails+Ember app?

I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)

using the Advanced Compilation in google closure compiler

I am new in google closure compiler,and after read the documents in the closure tools site,I create a js and make the test.
However I found that even I use the Advanced Compilation level,the compiled codes are still easy to decompilated.
For example,this is the codes:
//2
window["_NameSpace_"]={};
window["_NameSpaceInternal_"]={};
(function() {
_NameSpaceInternal_.Class = function() {
var clazz = function() {
this["init"] && this["init"].apply(this, arguments);
};
var pros = {}, arg;
for(var c = 0, k = arguments.length; c < k; ++c) {
arg = arguments[c];
if( typeof arg === 'function') {
if(c == 0 && k > 1) {
var F = function() {
};
F.prototype = arg.prototype;
pros = new F;
arg = arg.prototype;
}
} else {
if(arg.init) {
clazz = arg["init"];
delete arg["init"]
}
}
}
for(var p in arg)
pros[p] = arg[p]
clazz.prototype = pros;
return clazz;
};
})();
(function(d){
d["Person"]=_NameSpaceInternal_.Class({
"init":function(name){
this.name=name;
},
"whatever":function(aaa){
}
});
})(_NameSpace_);
After compiled(I make a pretty format for human reading):
window.__MapNS__ = {};
window.__MapNSImpl__ = {};
__MapNSImpl__.a = function() {
function c() {
this.init && this.init.apply(this, arguments)
}
for (var b = {}, a, d = 0, e = arguments.length; d < e; ++d) if (a = arguments[d], "function" === typeof a) 0 == d && 1 < e && (b = function() {}, b.prototype = a.prototype, b = new b, a = a.prototype);
else {
a.b && (c = a.init, delete a.init)
}
if (!b || !a) throw Error("You must provide an object to copy from and to");
for (var f in a) b[f] = a[f];
c.prototype = b;
return c
};
(function(c) {
c.Person = __MapNSImpl__.a({
init: function(b) {
this.name = b
},
whatever:function(x){
}
})
})(__MapNS__);
Now,taks the class defination for "Person" for example, after compiled,all the methods for "Person" are clearly for hacker even these method have to be exposed.
But I wonder if I can make the compiled codes like this;
...........
var xx="init",xxx="whatever",xxxx=="Person";
c[xxxx] = __MapNSImpl__.a({
xx: function(b) {
this.name = b
},
xxx:function(x){
}
})
...........
Just like the google map's compress.
Any idea?
The exact answer you are looking for is to enable the AliasStrings pass in the compiler by either using the Java API or by making a custom build of the compiler. The pass is not enabled by default as it tends to produce larger code when accounting for gzip.
To actually get the same effect that most google products achieve, you'll need to make substantial changes to your code.
Define your objects and methods in the global scope. Assign them to namespaces after declaring them globally. You can use the output_wrapper flag to wrap the compiled code in a function to prevent global scope collisions. Example:
function a() {}; window['Namespace']['obj'] = a;
Define your objects directly - don't use a helper method. So instead of
var a = _NameSpaceInternal_.Class({"init":function(name){ this.name=name; });
You would use something like:
function a(){}; a.prototype.name = ""; a.prototype.init = function(name) { this.name=name; };
This avoids using quoted syntax and allows the compiler to rename your properties and methods.
For many more examples of coding style that compiles/renames optimally with Closure-compiler, see the Closure Library.

Resources