Realm very slow for adding/updating records - react-native

I have this react native application which imports the phone contacts to database. I have about 100 contacts in my phone and it's taking ages...like 1 import per second which is. I'm sure, a mistake I'm doing somewhere even though the code is simple.
realm.write(() => {
for (let i = 0, len = contacts.length; i < len; i++) {
Contact.saveOrUpdate(contacts[i].name, contacts[i].recordID, contacts[i].phoneNumbers);
}
});
saveOrUpdate method:
class Contact {
static saveOrUpdate(name, recordId, phones) {
const save = () => {
let c;
try {
// try an update first
c = realm.create('Contact', {
name: name.toString(),
recordID: recordId.toString()
}, true);
} catch (e) {
// if that fails, create a new contact
console.log("Created " + recordId);
c = realm.create('Contact', {
name: name.toString(),
recordID: recordId.toString()
});
}
c.phones = [];
for (let i = 0, len = phones.length; i < len; i++) {
c.phones.push({
number: phones[i].toString()
});
}
// now run an update with the phone numbers
return realm.create('Contact', c, true);
};
return save();
}
}
My realm schema:
const PhoneNumberSchema = {
name: 'PhoneNumber',
properties: {
number: 'string'
}
};
const ContactSchema = {
name: 'Contact',
primaryKey: 'recordID',
properties: {
recordID: 'string',
name: {
type: 'string',
indexed: true
},
phones: {
type: 'list',
objectType: 'PhoneNumber'
}
}
};
Can anyone spot what am I doing wrong here that it takes so long for 100 contacts to be stored?

Related

Vue js MQTT connection problems

I want to put 'mqtt' value in span. But it doesn't work.
I think the loading method is wrong, but I don't know how to do it.
I don't know if the code below will suffice. Any help would be greatly appreciated.
Someone else coded similar to one page. Someone else's code has a value in 'detail', but my code doesn't. Why?
HTML
span{{ detail }}span //empty with nothing
Front script1
export default {
props: {
detail: {
type: Object
},
isAdd: {
type: Boolean,
default: false
},
},
data() {
return {};
},
mounted() {
this.$mqtt.subscribe('#');
},
methods: {
SendData() {
var temp = [];
var name = Number(document.getElementsByClassName('name').innerHTML);
temp.push(name);
var temp_current = data.payload.Temp_Current;
var error = data.payload.Error;
var data = {
//workcd: this.detail.namemodel,
Temp_Current: temp_current,
Error: error,
};
data = JSON.stringify(data);
var pub_name_arr = this.detail.name.split(' ');
var pub_name = 'CCComandTopic';
this.$mqtt.publish(
pub_name + '/' + pub_name_arr[1] + '/' + pub_name_arr[2],
data,
);
},
}
}
Front script 2
showHotrunner(namemodel, name, data) {
this.$modal.show(
Hotrunner,
{detail: {namemodel, name, data}, isAdd: true},
{width: '1040', height: '700', draggable: true},
);
const canvas = document.getElementById('three-canvas');
canvas.classList.add('noclick');
}
Back
var device = msg.topic.split("/")[2]
if(device == "hopper")
{
var temp_current = msg.payload.Temp_Current
var error = msg.payload.error
msg = {
topic : "CCComandTopic/hopper/1",
payload : {
ID: id,
"Error": error,
Temp_Current: temp_current,
}
}.
node.send(msg)
}

How to Load data dynamically to multiselect Option in VueJs

I need to load the data dynamically to multi select option using VueJs.
I tried lot of ways but nothing is worked for me. this is my codes
<multiselect id="webbrand" v-model="upallwebbrand" data-validation="required" data-validate-name="WebBrand"
:options="webbrands"
:multiple="true"
track-by="code"
:custom-label="websites"
placeholder="Please select deafult website first">
</multiselect>
Vue Function
showdata: function (staffid) {
axios.post("/HR/Showdata/", null, { params: { staffid } }).then(function (response)
{
hrform.oripassword = response.data.password;
hrform.upusername = response.data.userdata.UserName;
hrform.staffid = response.data.userdata.EmployeeId;
hrform.upselectedteam = response.data.userdata.TeamId;
hrform.upaccesslevel = response.data.userdata.AccessLevel;
hrform.upselectedstatus = response.data.userdata.Status;
hrform.upemail = response.data.userdata.Email;
**//hrform.upallwebbrand = response.data.userdata.BrandId**
hrform.upallwebbrand = [{ name: 'Travelcenter', code: 'TCUK' },
{ name: 'Tour Center', code: 'TOUR' },
{ name: 'World Airfairs', code: 'WAFR' },
{ name: 'Mabuhay', code: 'MABU' }];
hrform.upselectdesignation = response.data.userdata.Designation;
});
},
websites: function (option) {
return `${option.name} - ${option.code}`
},
In bove function BrandId is coming like this TCUK,WAFR,TOUR,MABU, only code with comma separated
I want to make it like below
[
{ name: 'Travelcenter', code: 'TCUK' },
{ name: 'Tour Center', code: 'TOUR' },
{ name: 'World Airfairs', code: 'WAFR' },
{ name: 'Mabuhay', code: 'MABU' }
]
If assigned values manually like above it's working fine.
I have to do it dynamically How can I achieve this??
Lets assume you have 2 arrays, one for name and one for code which is in the right order. You can create an array of objects like this
var name_arr = ['name1', 'name2', 'name3']
var code_arr = ['code1', 'code2', 'code3']
var upallwebbrand = []
for(var i=0; i<name_arr.length; i++){
upallwebbrand.push({
name: name_arr[i],
code: code_arr[i]
});
}
I'm Posting this for future viewers..
var hrform = new Vue({
el: '#hrform',
data: {
upselectdesignation:'',
upallwebbrand : [] //I defined the array like this
},
});
And while updating the upallwebbrand getting the codes from database and did the for loop to push the data to array upallwebbrand like below
showdata: function (staffid) {
axios.post("/HR/Showdata/", null, { params: { staffid } }).then(function (response) {
hrform.oripassword = response.data.password;
hrform.upusername = response.data.userdata.UserName;
hrform.staffid = response.data.userdata.EmployeeId;
hrform.upselectedteam = response.data.userdata.TeamId;
hrform.upaccesslevel = response.data.userdata.AccessLevel;
hrform.upselectedstatus = response.data.userdata.Status;
hrform.upemail = response.data.userdata.Email;
hrform.upselectdesignation = response.data.userdata.Designation;
//hrform.branss = response.data.userdata.BrandId;
var codes = response.data.userdata.BrandId.split(","); // Spliting the brand Id
var obj = { 'TCUK': 'Travel Center', 'MABU': 'Mabuhai', 'WAFR': 'World AirFares', 'TOUR': 'Tour Center' }
hrform.upallwebbrand = [];
for (var i = 0; i < codes.length; i++)
{
if (codes[i] in obj) {
hrform.upallwebbrand.push({ code: codes[i], name: obj[codes[i]] })
}
}
});
}

Fine Uploader - objectProperties - Key

I have 1 page whick give to user add new car to his cars collection.
User MUST to add minimum 1 image to this car item.
In AWS S3 service I save images in this path architecture:
bucket_name/cars/HERE_IS_USER_ID/HERE_IS_CAR_ID/and here photos
I use fine uploader.
ANd If i do add car in 2 step - all is going good
In 1 step I add to my database car - and send from server side userId and new car Id.
And then in step 2 I init Fine uploader with this id:
Below Code:
(function () {
'use strict';
angular
.module('cars.services.fineUploader', ['ngResource'])
.factory('FineUploader', ['$resource', '$http', 'AppConfig', function ($resource, $http, AppConfig) {
return function (divId, templateName, autoUpload, foldersBtn, uploadSuccessCallback, type, parentId, id) {
var key = '';
var keyExist = false;
getKey();
if (!qq.supportedFeatures.folderSelection) {
document.getElementById(foldersBtn).style.display = "none";
}
var uploader = new qq.s3.FineUploader({
element: document.getElementById(divId),
template: templateName,
autoUpload: autoUpload,
request: {
endpoint: 'carsbucket.s3.amazonaws.com',
accessKey: 'ACCESS',
},
extraButtons: [
{
element: document.getElementById(foldersBtn),
folders: true
}
],
signature: {
endpoint: AppConfig.apiUrl + 'api/AmazonS3/GetSignature'
},
uploadSuccess: {
endpoint: uploadSuccessCallback()
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
objectProperties: {
key: function (id) {
var fileName = uploader.getName(id);
var ext = qq.getExtension(fileName);
return key+ '/' + fileName + "." + ext;
}
}
});
return {
Uploader: function () {
return uploader;
},
StartUpload: function () {
uploader.uploadStoredFiles();
},
InitUploader: function () {
while (!keyExist) {
getKey();
}
}
};
function getKey() {
var itemRequest = {
"ItemType": type,
"ParentId": parentId,
"ItemId": id
};
$http.post("http://localhost:42309/api/AmazonS3/GetItemKey", itemRequest).success(function (data, status) {
key = data;
keyExist = true;
});
}
}
}]);
})();
And this is code how I init this service:
function Uploader(shopId, shopItemId) {
vm.step = 2;
uploader = FineUploader('s3FU', 'qq-template-gallery', false, 'foldersButton', testCallback, 1, shopId, shopItemId);
}
Now I want to do all ADD ITEM logic in 1 step
But I dont know how do it - because I need init FineUploader - but I dont have carId and UserId
.........

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);
}
});

On my cardboard app trying to show total of all features actual points for each column(Release) on the header, but that is not getting displayed

On my cardboard app trying to show total of all features actual points for each column(Release) on the header, but that is not getting displayed.
See the image below the cards are my portfolioitem/feature, in particular release.
On each header with release information, below progress-bar I want to show total of all features actual points in that release.
Below is the code for that, I am not getting why actual_points are not getting displayed. I am doing something wrong, but I don't know where exactly it is
Ext.override(Rally.ui.cardboard.CardBoard,{
_buildColumnsFromModel: function() {
var me = this;
var model = this.models[0];
if (model) {
if ( this.attribute === "Release" ) {
var retrievedColumns = [];
retrievedColumns.push({
value: null,
columnHeaderConfig: {
headerTpl: "{name}",
headerData: {
name: "Backlog"
}
}
});
this._getLocalReleases(retrievedColumns, this.globalVar);
}
}
},
_getLocalReleases: function(retrievedColumns, today_iso) {
var me = this;
if (today_iso == undefined) {
today_iso = Rally.util.DateTime.toIsoString(new Date(),false);
}
var filters = [{property:'ReleaseDate',operator:'>',value:today_iso}];
var iteration_names = [];
Ext.create('Rally.data.WsapiDataStore',{
model:me.attribute,
autoLoad: true,
filters: filters,
context: { projectScopeUp: false, projectScopeDown: false },
sorters: [
{
property: 'ReleaseDate',
direction: 'ASC'
}
],
//limit: Infinity,
pageSize: 4,
//buffered: true,
//purgePageCount: 4,
fetch: ['Name','ReleaseStartDate','ReleaseDate','PlannedVelocity'],
listeners: {
load: function(store,records) {
Ext.Array.each(records, function(record){
console.log("records values", records);
var start_date = Rally.util.DateTime.formatWithNoYearWithDefault(record.get('ReleaseStartDate'));
var end_date = Rally.util.DateTime.formatWithNoYearWithDefault(record.get('ReleaseDate'));
//this._getMileStones(record.get('ReleaseStartDate'), record.get('ReleaseDate'), this.project);
iteration_names.push(record.get('Name'));
//iteration_names.push(record.get('ReleaseDate'));
retrievedColumns.push({
value: record,
_planned_velocity: 0,
_actual_points: 0,
_missing_estimate: false,
columnHeaderConfig: {
headerTpl: "{name}<br/>{start_date} - {end_date}",
headerData: {
name: record.get('Name'),
start_date: start_date,
end_date: end_date,
planned_velocity: 0,
actual_points: 0,
missing_estimate: false
}
}
});
});
this._getAllReleases(retrievedColumns,iteration_names);
},
scope: this
}
});
},
_getAllReleases: function(retrievedColumns,iteration_names, today_iso) {
var me = this;
if (today_iso == undefined) {
today_iso = Rally.util.DateTime.toIsoString(new Date(),false);
}
var filters = [{property:'ReleaseDate',operator:'>',value:today_iso}];
Ext.create('Rally.data.WsapiDataStore',{
model:me.attribute,
autoLoad: true,
filters: filters,
sorters: [
{
property: 'ReleaseDate',
direction: 'ASC'
}
],
fetch: ['Name','Project','PlannedVelocity'],
listeners: {
load: function(store,records) {
Ext.Array.each(records, function(record){
var planned_velocity = record.get('PlannedVelocity') || 0;
var actual_points = record.get('LeafStoryPlanEstimateTotal') || 0;
var index = Ext.Array.indexOf(iteration_names[0],record.get('Name'));
if (planned_velocity == 0 ) {
retrievedColumns[index+1]._missing_estimate = true;
}
retrievedColumns[index+1]._actual_points += actual_points;
retrievedColumns[index+1]._planned_velocity += planned_velocity;
});
this.fireEvent('columnsretrieved',this,retrievedColumns);
this.columnDefinitions = [];
_.map(retrievedColumns,this.addColumn,this);
this._renderColumns();
},
scope: this
}
});
}
});
Ext.define('Rally.technicalservices.plugin.ColumnHeaderUpdater', {
alias: 'plugin.tscolumnheaderupdater',
extend: 'Ext.AbstractPlugin',
config: {
/**
*
* #type {String} The name of the field holding the card's estimate
*
* Defaults to c_FeatureEstimate (try LeafStoryPlanEstimateTotal)
*/
field_to_aggregate: "planned_velocity",
/**
* #property {Number} The current count of feature estimates
*/
total_feature_estimate: 0,
fieldToDisplay: "actual_points",
/**
* #property {String|Ext.XTemplate} the header template to use
*/
headerTpl: new Rally.technicalservices.template.LabeledProgressBarTemplate({
fieldLabel: 'Features Planned vs Planned Velocity: ',
calculateColorFn: function(data) {
if ( data.percentDone > 0.9 ) {
return '#EDB5B1';
}
return '#99CCFF';
},
showDangerNotificationFn: function(data) {
return data.missing_estimate;
},
generateLabelTextFn: function(data) {
if ( data.percentDone === -1 ) {
return "No Planned Velocity";
} else {
var text_string = "";
if ( data.field_to_aggregate === "planned_velocity" ) {
text_string = this.calculatePercent(data) + '%';
} else {
text_string = 'By Story: ' + this.calculatePercent(data) + '%';
}
return text_string;
}
}
})
//headerTpl: '<div class="wipLimit">({total_feature_estimate} of {planned_velocity})</div>'
},
constructor: function(config) {
this.callParent(arguments);
if(Ext.isString(this.headerTpl)) {
this.headerTpl = Ext.create('Ext.XTemplate', this.headerTpl);
}
},
init: function(column) {
this.column = column;
if ( column.value === null ) {
this.headerTpl = new Ext.XTemplate('');
}
this.planned_velocity = this.column._planned_velocity;
this.missing_estimate = this.column._missing_estimate;
this.actual_points = this.column._actual_points;
this.column.on('addcard', this.recalculate, this);
this.column.on('removecard', this.recalculate, this);
this.column.on('storeload', this.recalculate, this);
this.column.on('afterrender', this._afterRender, this);
this.column.on('ready', this.recalculate, this);
this.column.on('datachanged', this.recalculate, this);
},
destroy: function() {
if(this.column) {
delete this.column;
}
},
_afterRender: function() {
if ( this.feature_estimate_container ) {
this.feature_estimate_container.getEl().on('click', this._showPopover, this);
}
},
recalculate: function() {
this.total_feature_estimate = this.getTotalFeatureEstimate();
this.refresh();
},
refresh: function() {
var me = this;
if (this.feature_estimate_container) {
this.feature_estimate_container.update(this.headerTpl.apply(this.getHeaderData()));
} else {
this.feature_estimate_container = Ext.widget({
xtype: 'container',
html: this.headerTpl.apply(this.getHeaderData())
});
this.column.getColumnHeader().getHeaderTitle().add(this.feature_estimate_container);
}
if ( this.feature_estimate_container && this.feature_estimate_container.getEl()) {
this.feature_estimate_container.getEl().on('click', this._showPopover, this);
}
},
_showPopover: function() {
var me = this;
if ( me.planned_velocity > 0 ) {
if ( this.popover ) { this.popover.destroy(); }
this.popover = Ext.create('Rally.ui.popover.Popover',{
target: me.column.getColumnHeader().getHeaderTitle().getEl(),
items: [ me.getSummaryGrid() ]
});
this.popover.show();
}
},
getSummaryGrid: function() {
var me = this;
var estimate_title = "Feature Estimates";
if ( this.field_to_aggregate !== "c_FeatureEstimate") {
estimate_title = "Story Estimates";
}
var store = Ext.create('Rally.data.custom.Store',{
data: [
{
'PlannedVelocity': me.planned_velocity,
'ActualPoints': me.actual_points,
'TotalEstimate': me.getTotalFeatureEstimate(),
'Remaining': me.getCapacity(),
'MissingEstimate': me.missing_estimate
}
]
});
var grid = Ext.create('Rally.ui.grid.Grid',{
store: store,
columnCfgs: [
{ text: 'Plan', dataIndex:'PlannedVelocity' },
{ text: estimate_title, dataIndex: 'TotalEstimate' },
{ text: 'Remaining', dataIndex: 'Remaining' },
{ text: 'Team Missing Plan?', dataIndex: 'MissingEstimate' }
],
showPagingToolbar: false
});
return grid;
},
getHeaderData: function() {
var total_feature_estimate = this.getTotalFeatureEstimate();
actual_points = 0;
var percent_done = -1;
planned_velocity = 20;
if ( planned_velocity > 0 ) {
percent_done = total_feature_estimate / 4;
}
return {
actual_points: actual_points,
total_feature_estimate: total_feature_estimate,
planned_velocity: planned_velocity,
percentDone: percent_done,
field_to_aggregate: this.field_to_aggregate,
missing_estimate: this.missing_estimate
};
},
getCapacity: function() {
return this.planned_velocity - this.getTotalFeatureEstimate();
},
getTotalFeatureEstimate: function() {
var me = this;
var total = 0;
var total_unaligned = 0;
var records = this.column.getRecords();
Ext.Array.each(records, function(record){
var total_points = record.get('AcceptedLeafStoryPlanEstimateTotal');
var feature_estimate = record.get(me.field_to_aggregate) || 0;
var unaligned_estimate = record.get('UnalignedStoriesPlanEstimateTotal') || 0;
total += parseFloat(total_points,10);
});
if ( me.field_to_aggregate !== "planned_velocity" ) {
total = total
}
return total;
}
});