R6 Error, When Function in Function - r6

library(R6)
pre <- R6Class("pre",
public = list(
dbl = NULL,
initialize = function(){},
functionA = function(){},
functionB = function() {}
) )
Here is the code I want:
FunctionA ()
{
    FunctionB ()
}
But there is an error here.
Error: could not find function "functionB"
Please let me know how to fix it.

FunctionA = function()
{
self$FunctionB ()
}
should do the trick. It is necessary to put self before the name of the memberfunction unless you make your class non-portable. Here is a complete example
library(R6)
pre <- R6Class(public = list(
functionA = function(){self$functionB()},
functionB = function(){"output from B"}
))
obj <- pre$new()
obj$functionA()
# "output from B"
obj$functionB()
# "output from B"

Related

"The second data argument, does not decode to a context" when mintin with Mesh on Cardano

This my script for minting NFT:
{-# INLINABLE mkPolicy #-}
mkPolicy :: BuiltinData -> PlutusV2.ScriptContext -> Bool
mkPolicy _ ctx = traceIfFalse "wrong amount minted" checkNFTAmount
where
info :: PlutusV2.TxInfo
info = PlutusV2.scriptContextTxInfo ctx
-- hasUTxO :: Bool
-- hasUTxO = any (\i -> PlutusV2.txInInfoOutRef i == mpTxOutRef r) $ PlutusV2.txInfoInputs info
checkNFTAmount :: Bool
checkNFTAmount = case Value.flattenValue (PlutusV2.txInfoMint info) of
[(cs, tn', amt)] -> cs == ownCurrencySymbol ctx && tn' == PlutusV2.TokenName "" && amt == 1
_ -> False
{-
As a Minting Policy
-}
compiledCode :: PlutusTx.CompiledCode (BuiltinData -> BuiltinData -> ())
compiledCode = $$(PlutusTx.compile [|| wrap ||])
where
wrap = Scripts.mkUntypedMintingPolicy mkPolicy
policy :: Scripts.MintingPolicy
policy = PlutusV2.mkMintingPolicyScript compiledCode
script :: PlutusV2.Script
script = PlutusV2.unMintingPolicyScript policy
{-
As a Short Byte String
-}
scriptSBS :: SBS.ShortByteString
scriptSBS = SBS.toShort . LBS.toStrict $ serialise script
{-
As a Serialised Script
-}
serialisedScript :: PlutusScript PlutusScriptV2
serialisedScript = PlutusScriptSerialised scriptSBS
writeSerialisedScript :: IO ()
writeSerialisedScript = void $ writeFileTextEnvelope "nft-mint-V2.plutus" Nothing serialisedScript
I'm using Mesh to minting NFT with that script
const walletAddr = wallet.getPaymentAddress();
const addressUtxo: UTxO[] = await provider.fetchAddressUTxOs(walletAddr);
const redeemer: Partial<Action> = {
tag: "MINT",
data: {
alternative: 0,
fields: [],
},
};
const assetMetadata: AssetMetadata = {
name: "MyNFT",
image: "https://picsum.photos/200",
mediaType: "image/jpg",
description: "This NFT is minted by me.",
};
const asset: Mint = {
assetName: "MyNFT",
assetQuantity: "1",
metadata: assetMetadata,
label: "721",
recipient: walletAddr,
};
// Mint NFT
const tx = new Transaction({ initiator: wallet });
tx.mintAsset(script, asset, redeemer);
tx.setCollateral([addressUtxo[0]]);
const unsignedTx = await tx.build();
const signedTx = await wallet.signTx(unsignedTx, true);
try {
const txHash = await wallet.submitTx(signedTx);
console.log(txHash);
} catch (e) {
console.log(e);
}
Unfortunately, it returned with this error:
transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage
(ApplyTxError
[UtxowFailure
(UtxoFailure
(FromAlonzoUtxoFail
(UtxosFailure
(ValidationTagMismatch
(IsValid True)
(FailedUnexpectedly
(PlutusFailure \\\"\\\\nThe 2 arg plutus script (PlutusScript PlutusV2 ScriptHash \\\\\\\"77f807bc9403ef0177cc2a9956bfd5628ee649680041ccf48a198fc0\\\\\\\") fails.
\\\\nCekError An error has occurred:
User error:\\\\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
\\\\nThe protocol version is: ProtVer {pvMajor = 7, pvMinor = 0}\\\\nThe redeemer is: Constr 0 []\\\\
nThe second data argument, does not decode to a context
Does anyone faced this error before? As the error said "The second data argument, does not decode to a context" and I specify context in my script like this, I think the problem is with the context param. Or what is wrong with my script.

Web Application ArcGIS JS API error adding layer

I'm developing a custom widget for WebApp Builder. The widget calls a Geoprocessing service and the result must be added to map, but when I call a function this.map.addLayer() I receive the error message:
TypeError: this.map.addLayer is not a function
at Widget.js?wab_dv=2.6:839
at Object._successHandler (init.js:2238)
at Object._getResultDataHandler (Geoprocessor.js:11)
at init.js:63
at Object.load (Geoprocessor.js:12)
at init.js:1042
at c (init.js:103)
at d (init.js:103)
at b.Deferred.resolve.callback (init.js:105)
at c (init.js:104) "TypeError: this.map.addLayer is not a function
This is the snippet of my code:
submitGpLr: function (tab1) {
let params = {
json: tab1
};
// lancia il geoprocessing, i callback sono sotto
this.gpLr.submitJob(params, lang.hitch(this, this.gpLrJobComplete), this.gpLrJobStatus, this.gpLrJobFailed);
},
gpLrJobComplete: function (jobinfo) {
this.gpLr.getResultData(jobinfo.jobId, "Output_Layer", function (results) {
console.log(results);
let jsonResult = results.value;
// function addResultToMap
let SR = jsonResult.spatialReference;
let GT = "esriGeometryPolyline";
let layerDefinition = {
"geometryType": GT,
"spatialReference": SR,
"fields": jsonResult.fields
};
let featureCollection = {
layerDefinition: layerDefinition,
featureSet: {
"geometryType": GT,
"spatialReference": SR,
"features": jsonResult.features
}
};
let resultLayer = new FeatureLayer(featureCollection, {
showLabels: true,
spatialReference: SR
});
let sls = new esri.symbol.SimpleLineSymbol(
esri.symbol.SimpleLineSymbol.STYLE_SOLID,
new esri.Color([255, 0, 0]), 3.5
);
this.map.addLayer(resultLayer);
});
},
gpLrJobFailed: function (err) {
console.log("error");
console.log(err);
},
gpLrJobStatus: function () {
}
This is my setEventHandler:
this.own(on(this.gpLr_Submit, "click", () => {
let id = this.selectedMainTabId;
let tabNewStr = JSON.stringify(this.grids[id + '_IN']['_originalData']);
this.submitGpLr(tabNewStr);
}));
How can I fix this error? I don't try the error in my code.
I think, "this" reference to "Window" object. Your this should reference to, your widget class.You should set instance like this when, onstartup event in widget.Then you can use instance.map like this:
startup: function () {
console.log('YourCustomWidget::startup');
YourCustomWidget.SetInstance(this);
}
//Singleton design
YourCustomWidget.Instance = undefined;
YourCustomWidget.GetInstance = function () {
return this.Instance;
}
YourCustomWidget.SetInstance = function (instance) {
AkkrFiltrelemeVeRaporlama.Instance = instance;
}
...
...
...
...
gpLrJobComplete: function (jobinfo) {
var instance = YourCustomWidget.Instance;
//
//
//
instance .map.addLayer(resultLayer);
}

Update ListView with db-models data

I would like to generate my view with my data created with db-models :
https://www.npmjs.com/package/react-native-db-models
But there is the problem : nothing appends, my view stay empty.
1 ) The size of db (for loop) is equal to 0 (but it must be 8 after my DB.bills.get_all().
Constructor
constructor(props) {
super(props);
var bdd = [];
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(bdd)
};
}
ComponentDidMount()
componentDidMount() {
console.log("START");
let self = this;
var db = [];
DB.bills.get_all(function(result) {
db = result;
console.log(db);
});
let newArray = self.state.dataSource._dataBlob.s1.slice();
for(var i = 0; i<Object.keys(db).length ; i++){
newArray[i] = {
...self.state.dataSource[i],
field: JSON.stringify(db),
};
console.log("i : " + i + " db : " + db);
}
self.setState({dataSource: self.state.dataSource.cloneWithRows(newArray),
});
console.log("DS : ", this.state.dataSource);
console.log("END");
}
There is the console.log(db) in my DB.bills.get_all()
Object {totalrows: 7, autoinc: 8, rows: Object}
autoinc : 8
rows : Object
1 : Object
creditor:"M. Alixe"
month:"Décembre"
picture:"https://cdn.pbrd.co/images/8YftpB3rQGA5S.png"
price:"700"
type:"Maquettes UI"
year:"2016"
_id:1
__proto__:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
__proto__:Object
totalrows:7
__proto__:Object
I'm on it since 2 days. Please help me ^^"
That's because your DB.bills.get_all function is asynchronous. By the time you get result, you have already calculated newArray and set your state. You need to wait for the result before calculating newArray and cloning your dataSource. Try putting the code after DB.bills.get_all inside the callback function.

TVOS: Race condition at startup

Using the templates and TVML, I start my app with my own loading page, and then call a service to create the main page for the user.
If I initiate the call to the server inside didFinishLaunchingWithOptions, I get the error ITML <Error>: undefined is not an object - undefined - line:undefined:undefined.
From this I assume my asynchronous call to the server is finishing before the javascript App.onLaunch function has completed, and I can only get it to work if I force a wait time before the server is called.
Here is the AppDelegate method:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let appControllerContext = TVApplicationControllerContext()
// our "base" is local
if let jsBootUrl = NSBundle.mainBundle().URLForResource("application", withExtension: "js") {
appControllerContext.javaScriptApplicationURL = jsBootUrl
}
let jsBasePathURL = appControllerContext.javaScriptApplicationURL.URLByDeletingLastPathComponent
baseUrl = jsBasePathURL?.absoluteString
appControllerContext.launchOptions["BASEURL"] = jsBasePathURL?.absoluteString
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
// initiate conversation with the server
myPageCreator = PageCreator()
myPageCreator?.delegate = self
myPageCreator?.startDataCall(baseUrl!)
return true
}
Here is the (somewhat boilerplate) javascript function:
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}ResourceLoader.js`,
`${options.BASEURL}Presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if (success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}myLoadingPage.xml.js`,
function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
navigationDocument.pushDocument(doc);
});
} else {
/* handle error case here */
}
});
}
Now, if I change the call to the server in the didFinishLaunchingWithOptions, and force it to wait, like this:
...
// race condition hack:
_ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "testing", userInfo: nil, repeats: false)
return true
}
// initiate conversation with the server
func testing() {
myPageCreator = PageCreator()
myPageCreator?.delegate = self
myPageCreator?.startDataCall(baseUrl!)
}
.. it will work. But I don't like that solution! What can I do to stop this race condition from happening?
You need a way for Javascript to communicate with Swift so that you know when App.onLaunch has finished running it's scripts.
Run this code in your didFinishLaunchingWithOptions method. It will allow you to call onLaunchDidFinishLoading() in Javascript and handle the callback in Swift.
appController.evaluateInJavaScriptContext({(evaluation: JSContext) -> Void in
let onLaunchDidFinishLoading : #convention(block) () -> Void = {
() -> Void in
//when onLaunchDidFinishLoading() is called in Javascript, the code written here will run.
self.testing()
}
evaluation.setObject(unsafeBitCast(onLaunchDidFinishLoading, AnyObject.self), forKeyedSubscript: "onLaunchDidFinishLoading")
}, completion: {(Bool) -> Void in
})
func testing() {
myPageCreator = PageCreator()
myPageCreator?.delegate = self
myPageCreator?.startDataCall(baseUrl!)
}
Inside App.onLaunch just add onLaunchDidFinishLoading() when the template is done being loaded.
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}ResourceLoader.js`,
`${options.BASEURL}Presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if (success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}myLoadingPage.xml.js`,
function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
navigationDocument.pushDocument(doc);
//ADD THE FOLLOWING LINE
onLaunchDidFinishLoading();
});
} else {
/* handle error case here */
}
});
}

MVC model binder issues when posting data from knockout

I have a knockout model that I'm trying to post to an MVC4 controller. A simplified version looks like this:
var ItemModel = function (id, name) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
};
var Entry = function () {
var self = this;
self.Id = ko.observable();
self.areas = ko.observableArray([]);
};
var EntryModel = function () {
var self = this;
self.entry = new Entry();
self.save = function () {
$.post("/Edit", ko.toJS(self.entry), function (data) {
...
})};
};
};
If I add two areas to my model, like this:
viewModel.entry.areas.push(new ItemModel(1, "A"));
viewModel.entry.areas.push(new ItemModel(2, "B"));
and post it using viewModel.save I get two areas from the model binder, but no data in them (i.e. id = 0, name = "").
After some research I found that I'm posting data like this:
id = 1
name = test
area[0][id] = 1
area[0][name] = "A"
area[1][id] = 2
area[1][name] = "B"
and that MVC expects this:
id = 1
name = test
area[0].id = 1
area[0].name = "A"
area[1].id = 2
area[1].name = "B"
How do I get this posted as expected?
Your model contains the array so you have to stringify your model and send the resultant string to the controller. You can try this:
var EntryModel = function () {
var self = this;
self.entry = new Entry();
//toJSON function produce the JSON string representing entry model
var dataToSend = ko.toJSON(self.entry);
self.save = function () {
$.post("/Edit", dataToSend, function (data) {
...
})};
};
};