I'm new to Motoko and this code is giving me errors - motoko

actor {
type Post = {
id : Int;
creater : String;
};
stable var Posts : [Post] = [];
func addPost(id : Int, creater : String) : () {
Posts.push(id, creater);
};
};
How can I push an object in that mutable array that is defined as Posts?

It seems that you are looking for Array.append, however as it is deprecated, you should use Buffers with preupgrade and postupgrade instead of the following:
import Array "mo:base/Array";
actor {
type Post = {
id : Int;
creator : Text;
};
stable var Posts = Array.init<Post>(1, { id = 0; creator = "" });
func addPost(id : Int, creator : Text) : () {
let NewPosts = Array.init<Post>(1, { id; creator });
Posts := Array.thaw(Array.append(Array.freeze(Posts), Array.freeze(NewPosts)));
};
};

Related

How to implement Custom Material Data Source for Data Table?

I'm trying to implement DataSource for Material DataTable with pagenator, sorting etc.
An example of implementation is described here: https://blog.angular-university.io/angular-material-data-table/
From service i'm get following model:
export interface IResult {
results: Flat[];
currentPage: number;
pageCount: number;
pageSize: number;
length: number;
firstRowOnPage: number;
lastRowOnPage: number;
}
Method in service looks following:
getObjects(sort: string, order: string,
pageNumber = 1, pageSize = 20): Observable<IResult> {
return this.http.get<IResult>(this.serviceUrl,
{
params: new HttpParams()
.set("sort", sort)
.set("order", order)
.set('pageNumber', pageNumber.toString())
.set('pageSize', pageSize.toString())
});
}
DataSource realization:
export class OtherDataSource implements DataSource<Flat> {
private flatSubject = new BehaviorSubject<Flat[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(private service: ObjectsService) {
}
connect(collectionViewer: CollectionViewer): Observable<Flat[]> {
return this.flatSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.flatSubject.complete();
this.loadingSubject.complete();
}
loadData(filter = '',
sortDirection = 'asc', pageIndex = 1, pageSize = 20) {
this.loadingSubject.next(true);
this.service.getObjects(filter, sortDirection,
pageIndex, pageSize).pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false))
)
.subscribe(obj => this.flatSubject.next(obj));
}
}
In subscribe(obj => this.flatSubject.next(obj)) i'm getting following error: IResult is not assignable to type Flat[]. I have no error when casting obj to <Flat[]>obj, also i see that's backend return data but result in UI is empty.
I think that error here subscribe(obj => this.flatSubject.next(<Flat[]>obj)) but have no ideas how it fixing. What I'm doing wrang?
I implemented an DataSource differently. Realization looks following:
export class NmarketDataSource extends DataSource<Flat> {
resultsLength = 0;
isLoadingResults = true;
isRateLimitReached = false;
cache$: Flat[];
constructor(private nmarketService: ObjectsService,
private sort: MatSort,
private paginator: MatPaginator) {
super();
}
connect(): Observable<Flat[]> {
const displayDataChanges = [
this.sort.sortChange,
this.paginator.page
];
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 1);
return merge(...displayDataChanges)
.pipe(
startWith(null),
switchMap(() => {
return this.nmarketService.getObjects(
this.sort.active,
this.sort.direction,
this.paginator.pageIndex+1,
this.paginator.pageSize);
}),
map(data => {
this.isLoadingResults = false;
this.isRateLimitReached = false;
this.resultsLength = data.rowCount;
this.cache$ = data.results;
return data.results;
}),
catchError(() => {
this.isLoadingResults = false;
this.isRateLimitReached = true;
return of([]);
})
);
}
disconnect() { }
}
It works but doesn't match in my case.
replace this code
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;">
</mat-row>
at the end of table
this is the error

React Native: how can I achieve the dynamic keys with multiple objects

Here is my code I tried,
var array=[];
var list = this.state.list;
var getList = function(i){
var add = +i + 1;
return {
["value"+add]:{
Description:list[i].Description,
Length:list[i].Length,
Height:list[i].Height,
Weight:list[i].Weight,
VolumeWeight:list[i].VolumeWeight,
ActualWeight:list[i].ActualWeight,
}
}
}.bind(this)
for(var i in list){
array.push(getList(i));
}
var dataArray = array.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
data1 = {
ConsigneeBranchName:this.state.searchText,
ConsigneeBranchCode:this.state.code,
ConsigneeBranchFullAddress:this.state.DAddress,
SenderBranchCode:this.state.code1,
SenderBranchName:this.state.searchTexts,
SenderBranchFullAddress:this.state.Address,
CreatedByEmployeeCode:id,
CreatedByEmployeeFullName:userName,
jsonString:{
JsonValues:{
id:"MyID",
values:dataString
}
}
}
But I want the result is exactly this
var result = {
"ConsigneeBranchName":"",
"ConsigneeBranchCode":"",
"ConsigneeBranchFullAddress":"",
"SenderBranchCode":"",
"SenderBranchName":"",
"SenderBranchFullAddress":"",
"CreatedByEmployeeCode":"",
"CreatedByEmployeeFullName":"",
"jsonString":"{
"JsonValues": {
"id": "MyID",
"values": {
"value1":{
"Description”:"testSmarter1",
"Length”:"60",
"Height”:"50",
"Weight”:"70",
"VolumeWeight”:"75",
"ActualWeight”:”78"
},
"value2:{
"Description":"Documents",
"Length":"120",
"Height":"68",
"Weight":"75",
"VolumeWeight":"122.4",
"ActualWeight":"123"
},
}
}
}
};
Please any one help me
I want the object with dynamic keys within a single object {key1:{des:1,value:as},key2:{des:2,value:aw},key3:{des:3,value:au}}
can you please help me I have tried so many times
see this below image I want this part, inside the single object, I can join multiple objects with dynamic keys
lodash already has a function called keyBy, you can use it to get this functionality. If adding lodash doesn't make sense in your project.
I have implemented a vanilla JS version.
function keyBy(array, mapperFn) {
const resultObj = {};
array.map(item => resultObj[mapperFn(item)] = item);
return resultObj;
}
function arrayToObject (array, keyName = 'id') {
return keyBy(array, function(element) {return element[keyName]});
}
API:
arrayToObject(targetArray, stringNameOfThePorpertyYouWantToUseAsKey);
USAGE:
const listOfUsers = [{name: 'Jenitha', reputation: 6}, {name: 'Chandan', reputation: 3}];
const mapOfUsersByName = arrayToObject(listOfUsers, 'name');

How to join two collections in a json store?

I am working on IBM Worklight. I need to access data from two collections. Is there any solution for joining the 2 collections and get the required fields ?
JSONSTORE does not have the ability to combine collections.
However the follow blog post details one way to achieve this: https://mobilefirstplatform.ibmcloud.com/blog/2015/02/24/working-jsonstore-collections-join/
Create a collection:
var OrdersCollection = {
orders: {
searchFields: {
order_id: 'integer',
order_date: 'string'
},
additionalSearchFields: {
customer_id: 'integer'
}
}
};
var CustomerCollection = {
customers: {
searchFields: {
customer_name : 'string',
contact_name : 'string',
country : 'string'
},
additionalSearchFields : {
customer_id : 'integer'
}
}
};
Add data using additional search fields:
var data = [
{order_id : 462, order_date : '1-1-2000'},
{order_id: 608, order_date : '2-2-2001'},
{order_id: 898, order_date : '3-3-2002'}
];
var counter = 0;
var q = async.queue(function (task, callback) {
setTimeout(function () {
WL.JSONStore.get('orders').add(task.data, {additionalSearchFields: {customer_id: task.customer_id}});
callback(++counter);
},0);
},1);
for(var i = 0; i < data.length; i++){
q.push({data : data[i], customer_id: i+1}, function(counter){
console.log("Added Order Doc " + counter);
});
}
q.drain = function(){
setTimeout(function() {
console.log("Finished adding order documents");
WL.JSONStore.get("orders").findAll({filter : ["customer_id", "order_id", "order_date"]})
.then(function (res) {
ordersCollectionData = res;
document.getElementById("orders").innerHTML = JSON.stringify(res, null, "\t");
})
.fail(function (err) {
console.log("There was a problem at " + JSON.stringify(err));
});
},0);
};
Find the documents to merge:
WL.JSONStore.get('orders').findAll({filter : ['customer_id', 'order_id', 'order_date']})
.then(function (res) {
ordersCollectionData = res;
});
Merge
var shared_index = 'customer_id';
var mergedCollection = [];
mergedCollection =_.merge(customerCollectionData, ordersCollectionData, function(a, b){
if(_.isObject(a) && (a[shared_index] == b[shared_index])) {
return _.merge({}, a, b);
}
});

node orm2 hasmany association

I have a question regarding node orm2 hasMany association, my model definition is like this.
schemas/Channel.js
var model = db.define('channels', Channel, ChannelOptions);
var Channel = {
channel_name : String,
channel_email : String,
channel_id : String,
views : Number
};
var ChannelOptions = {
id : "channel_id",
methods: {
my_details : function (err) {
return this.channel_id +' '+ this.channel_name + ' ' + this.views;
}
}
};
schemas/network.js
var model = db.define('networks', Network, NetworkOptions);
var Channel = require('../schemas/Channel')(db);
model.hasMany('channels', Channel, {}, {autoFetch:true});
model.sync()
db.sync(function(){
console.log('DB SYNCHED');
});
var Network = {
network_id : Number,
name : String,
username : String,
logo : String,
website : String
};
var NetworkOptions = {
id : "network_id",
methods: {
}
};
It created a networks_channels table and I have filled it with a networkID and channelID. it is responding with the property (channels) but it is empty.
Is there something missing?
Just figured out what was wrong.
Its becauset I have set up the database table definitions before doing db.sync(). Turns out that its doing all the work for me. Clearing up the tables and refilling it with data did the trick.

dojo ItemFileReadStore.getValue mixed return value is not handled as string

I'am using dojo.data.ItemFileReadStore to query a json file with data. the main purpose is finding translations at Js level.
The Json data has "id" the word and "t" the translation
function translate(word)
{
var json = '/my/language/path/es.json';
var reader = new dojo.data.ItemFileReadStore({
url: json
});
var queryObj = {};
queryObj["id"] = word;
reader.fetch({
query: queryObj,
onComplete: function(items, request){
if (items.length > 0) {
var t = reader.getValue(items[0], 't');
if (dojo.isString(t)) {
return t;
}
}
return word;
},
onError: function(error, request){
return word;
}
});
}
The return value is always a undefined wether there is a translation or not. any ideas?
I tried typecasting with no success.
You can do it like this:
function translate(wordId) {
var translatedWord= wordId;
var store = new dojo.data.ItemFileReadStore({ data: storeData });
store.fetch({ query: { id: wordId },
onItem: function (item) {
translatedWord= (store.getValue(item, 't'));
}
});
return translatedWord;
}