new transaction is waiting for open operation - ios

I'm creating mobile app using cordova+angular.js+onsenui.
What I want to do is to open pre-populated database, execute select statement and display result as list.
I use litehelpers/cordova-sqlite-ext plugin to manipulate database.
But when I run the app with iOS simulator and see the log in Safari console, "new transaction is waiting for open operation" is logged.
Console log is as below:
database already open: test.db
test1
new transaction is waiting for open operation
DB opened: test.db
My code(index.js) is the following.
angular.module('app').controller('listController', function ($scope) {
var items = [];
ons.ready(function() {
db = sqlitePlugin.openDatabase({name: "test.db", location: 2, createFromLocation: 1});
console.log('test1');
db.readTransaction(function(tx) {
console.log('test2');
var sql = "SELECT id, title, status FROM items";
tx.executeSql(sql, [], function(tx, response) {
for (var i = 0; i < response.rows.length; i++) {
var row = response.rows.item(i);
items.push({title:"Item Title", label:"6h", desc:row.title});
}
}, function(error) {
console.log('SELECT error: ' + error.message);
});
}, errorCB, successCB);
});
function successCB() {
$scope.itemTable = items;
$scope.$apply();
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
$scope.showDetail = function(item) {
console.log('showDetail');
myNavigator.pushPage("detail.html", {item: item});
};
});
Does anyone know how to resolve this?
I appreciate any suggestion and hint.

For someone who has encountered same problem,
I write my solution.
I changed plugin to the following.
litehelpers/Cordova-sqlite-storage
an-rahulpandey/cordova-plugin-dbcopy
And my code is like below.
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
dbcopy();
}
function dbcopy()
{
window.plugins.sqlDB.copy("test.db", 0, copysuccess, copyerror);
}
function copysuccess()
{
//open db and run your queries
//alert('copysuccess');
openDatabase();
}
function openDatabase()
{
db = window.sqlitePlugin.openDatabase({name: "test.db"});
}
function copyerror(e)
{
//db already exists or problem in copying the db file. Check the Log.
console.log("Error Code = "+JSON.stringify(e));
//e.code = 516 => if db exists
if (e.code == '516') {
openDatabase();
}
}
angular.module('app').controller('listController', function ($scope) {
var items = [];
ons.ready(function() {
if (db === null) {
openDatabase();
}
db.transaction(function(tx) {
var sql = "SELECT * FROM items;";
tx.executeSql(sql, [], function(tx, response) {
for (var i = 0; i < response.rows.length; i++) {
var row = response.rows.item(i);
items.push({title:row.title, label:row.label, desc:row.desc});
}
console.log("res.rows.item(0).title: " + response.rows.item(0).title);
}, errorCB);
}, errorCB, successCB);
});
function successCB() {
$scope.itemTable = items;
$scope.$apply();
}
function errorCB(err) {
alert("Error processing SQL: "+err.message);
}
$scope.showDetail = function(item) {
console.log('showDetail');
myNavigator.pushPage("detail.html", {item: item});
};
});

Related

WebRTC - how to switch between getUserMedia and getDisplayMedia tracks inside RTCPeerConnection

I'm trying to develop an app where users can can video call to each other and share their screens using WebRTC technology. I have succeed with either video call or screen sharing app and now I'm trying to make it to be able to switch between getUserMedia and getDisplayMedia on button click during a call inside the same RTCPeerConnection but it doesn't work.
This is how I thought it could work:
function onLogin(success) {
var configuration = { offerToReceiveAudio: true, offerToReceiveVideo: true, "iceServers" : [ { "url" : "stun:stun.1.google.com:19302" } ] };
myConnection = window.RTCPeerConnection ? new RTCPeerConnection(configuration, { optional: [] }) : new RTCPeerConnection(configuration, { optional: [] });
myConnection.onicecandidate = function (event) {
console.log("onicecandidate");
if (event.candidate) send({ type: "candidate", candidate: event.candidate });
};
myConnection.ontrack=function(e){
try{remoteVideo.src = window.webkitURL?window.webkitURL.createObjectURL(e.streams[0]):window.URL.createObjectURL(e.streams[0])}
catch(err){remoteVideo.srcObject=e.streams[0]}
}
myConnection.ondatachannel=openDataChannel
openDataChannel();
startAVStream();
//startSStream()
};
function startAVStream(enable){
if(sStream)sStream.getTracks().forEach( function (track) {
try{myConnection.removeTrack( track, sStream );}
catch(e){}
} );
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(s => {
if(!avStream){
avStream = s;
avStream.getTracks().forEach( function (track) {
myConnection.addTrack( track, avStream );
} );
}
}, function (error) { console.log(error); });
}
function startSStream(enable){
if(avStream)avStream.getTracks().forEach( function (track) {
try{myConnection.removeTrack( track, avStream );}
catch(e){}
} );
navigator.mediaDevices.getDisplayMedia({ video: true }).then(s => {
if(!sStream){
sStream = s;
sStream.getTracks().forEach( function (track) {
myConnection.addTrack( track, sStream );
} );
}
}, function (error) { console.log(error); });
}
Can anyone tell me how I can switch between tracks inside the same RTCPeerConnection or should I create 2 separate RTCPeerConnection - one for video/audio streaming and another for screen sharing?
Any help appreciated! Thanks!
You could use RTCRtpSender.replaceTrack to splice the screen capture track. This doesn't require renegotiation, and therefore has very low latency.
let newstream = navigator.mediaDevices.getDisplayMedia({});
let newtrack = newstream.getTracks()[1];
if(newtrack.kind !== 'video')
throw new Error('Eek!?');
pc.getSenders().forEach(async s => {
if(s.track && s.track.kind === 'video')
await s.replaceTrack(newtrack);
});
The test for s.track not being null deals with the case where you previously called replaceTrack(..., null).
shareScreen = () =>{
const success = (stream) => {
window.localStream = stream
// this.localVideoref.current.srcObject = stream
// localStream.replaceStream(stream);
this.setState({
localStream: stream
})
Object.values(this.state.peerConnections).forEach(pc => {
pc.getSenders().forEach(async s => {
console.log("s.track ",s.track);
if(s.track && s.track.kind === 'video'){
stream.getTracks().forEach(track => {
// pc.addTrack(track, this.state.localStream)
s.replaceTrack(track);
});
}
});
});
}
const failure = (e) => {
console.log('getUserMedia Error: ', e)
}
navigator.mediaDevices.getDisplayMedia({ cursor: true }).then(success).catch(failure)}

cloud functions return error when using local parse database: "fail Error: The server returned an invalid response."

using parse dashboard in local system, implemented cloud functions and getting an error when call cloud function
main.js:
Parse.Cloud.define('cloudFunctions', function (req, res) {
const query = new Parse.Query("Test");
if (req.params.Name) {
query.equalTo('Name', req.params.Name);
}
query.find()
.then((results) => {
var testArray = new Array();
for (let i = 0; i < results.length; i++) {
testArray[i] = {
id: results[i].id,
Name: results[i].get("Name"),
Description: results[i].get("Description")
};
}
var obj={
result:testArray
}
res.success(obj);
}, (error) => {
res.success("Save failed! " + error);
});
});
client side:
var gettestparams = {
Name: ""
}
Parse.Cloud.run('cloudFunctions', gettestparams).then(function (callback) {
console.log("get test call", callback);
}).catch((error) => {
console.log("fail", error);
});

Select2 doesn't work change value from jQuery (dataAdapter)

I have a huge json data source (over 50,000 + lines) loaded in memory from a static file.
Note: It's not important why I have it in a static file.
I use select2 (v 4.0.5) that initializes as:
function initSelect2(selectName, dataSelect) {
var pageSize = 20;
$.fn.select2.amd.require(["select2/data/array", "select2/utils"],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var data = {};
data.results = dataSelect.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < dataSelect.length;
callback(data);
};
$('#mySelect3').select2({
ajax: {},
dataAdapter: CustomData,
width: '100%'
});
});
}
I have one big problem. I can not set the value to select from jQuery. If I try like this:
$ ("#mySelect3").val(17003).trigger("change");
nothing will happen. But I think I'm doing it badly. If I understand the documentation I think I should implement function:
CustomData.prototype.current = function (callback) {}
that should create the data, and then function:
CustomData.prototype.query = function (params, callback) {}
should only filter them.
Can you please help me, how do I implement select2 initialization, that can work with many options and can by set from jQuery?
With custom data adapter you don't need pagination :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
callback(data);
};
return CustomData;
}
);
//
$('#mySelect3').select2({
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
And with search you can do like this :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
if ($.trim(params.term) === '') {
callback(data);
} else {
if (typeof data.results === 'undefined') {
return null;
}
var filteredResults = [];
data.results.forEach(function (el) {
if (el.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
filteredResults.push(el);
}
});
if (filteredResults.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.results = filteredResults;
callback(modifiedData);
}
return null;
}
};
return CustomData;
}
);
//
$('#mySelect3').select2({
minimumInputLength: 2,
tags: false,
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
I had the same issue and this is how I solved it.
Note: We are using dataAdapter because we dealing with large that, so I am assuming your drop-down will contain large amount of data.
After implementing your DataAdapter with a query use this example to initialize your select2.
if(selectedValue !== null )
{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
data: [{ id: selectedValue, text: selectedValue }],
dataAdapter: customData
});
$("#item_value").val(selectedValue).trigger('change');
}else{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
dataAdapter: customData
});
}
To set selected value in select2 you need to pass some data into data option, but as we are dealing with large amount of data. You can't pass the complete array of large data you have as it's going to cause your browser window to freeze and lead to a bad user performance.
But instead set the data option only with the selected value you got from db or variable.
I hope this helps.

Highcharts columns height in phantomjs generated pdf

I am trying to generate a pdf with phantomjs from a page that's using highcharts. This is the script I am using
var port, server, service
system = require('system');
var page = require('webpage').create();
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
})
}
var fs = require('fs');
function loadFile(name){
if(fs.exists(name)){
console.log(name+ " File exist");
return fs.open(name,"r");
}else {
console.log("File do not exist");
}
}
if (system.args.length !== 2) {
console.log('Usage: serverkeepalive.js <portnumber>');
phantom.exit(1);
} else {
port = system.args[1];
console.log('port: ' + port);
server = require('webserver').create();
service = server.listen(port, { keepAlive: true }, function (request, response) {
console.log('Request at ' + new Date());
console.log(JSON.stringify(request, null, 4));
console.log('ProjectId:' + request.headers.projectId)
var projectReportPage = 'http://localhost:55073/' + request.headers.projectId;
console.log(projectReportPage);
console.log(JSON.stringify(request.cookies, null, 4));
phantom.cookiesEnabled = true;
phantom.addCookie({
'name': 'hello', /* required property */
'value': 'helloFromPhantomJS', /* required property */
'domain': 'localhost', /* required property */
'expires': (new Date()).getTime() + 3600 /* <- expires in 1 hour */
});
console.log(JSON.stringify(phantom.cookies, null, 4));
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin:'1cm' };
page.open(projectReportPage, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
console.log('Page obtained');
var reportName = 'report_' + request.headers.projectId + '.pdf';
page.evaluate( function(){$('h1').css('color', 'red');});
page.render(reportName);
var body = fs.absolute(reportName);
//var body = page.renderBase64('pdf');
// var fi = loadFile(reportName);
// var body = fi.read();
// var rawBody = fs.read(reportName);
// console.log(rawBody);
// var body = base64Encode(rawBody);
console.log(body);
response.statusCode = 200;
response.headers = {
'Cache': 'no-cache',
'Content-Type': 'application/pdf',
'Connection': 'Keep-Alive',
'Content-Length': body.length
};
response.write(body);
response.close();
}
});
console.log('After page open handler');
});
if (service) {
console.log('Web server running on port ' + port);
} else {
console.log('Error: Could not create web server listening on port ' + port);
phantom.exit();
}
}
When viewing the page, the chart looks like this:
http://i.imgur.com/kVImodv.png
This is what it looks like on the pdf:
http://i.imgur.com/vGon6vb.png
Any insights on why this happens would be appreciated!
The problem is that PhantomJS immediately takes a snapshot when the page is loaded. However, the Highcharts graph has an animation which builds up the graph.
This means the graph is not completely built up when PhantomJS is taking the snapshot. There are two possible solutions.
1. Skip the Highcharts animations
Add this to your graph configuration object.
plotOptions: {
series: {
animation: false
}
}
Source
2. Add a delay when taking a snapshot
page.open(address, function (status) {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
Source

How to change the value of a JQueryUI progressbar dynamically?

In my import photos script, I try to update a progressbar (Jquery UI) following a while loop with Ajax requests.
The JQueryUI progressbar, which is supposed to be displayed before the launch of ajax requests do it after. So I have the user feedback at the end of the execution of my while loop ... (The console shows me that these applications are running well, in the right order)
I thought about using live () or bind (), but I do not know how to test it ...
Here is my jquery code:
$(function() {
var percent_progressbar=0;
$('#myform').submit(function() {
$('#myform').hide();
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show(10, function() {
$("#myprogressbar").progressbar({value:percent_progressbar});
$("#myprogressbar").show(10, function() {
if (jQuery.trim($("#id_src").val()).length!=0) {
// Total number of photos to import
$.ajax({
type : 'POST',
async : false,
url : '/nbphotos.php',
data : 'chem=mydir',
success : function(nbphotos){
if (nbphotos>0){
$(".progression").html("0"+" / "+nbphotos);
var finish=false;
var nb_photos_imported=0;
var ajax_done = false;
var resultat_ajax="";
// Variables envoyées en Ajax
var datas = desvariables;
while (nb_photos_imported < nbphotos) {
ajax_done = false;
$.ajax({
type : 'GET',
async : false,
url : '/traitement.php',
data : datas,
success : function(resultat){
resultat_ajax=resultat;
ajax_done=true;
nb_photos_imported++;
}
});
if (ajax_done==true){
if (resultat_ajax=="ok") {
percent_progressbar = Math.floor(nb_photos_imported*100/nbphotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Succès ajax (resultat : OK) : "+percent_progressbar);
$(".progression").html(nb_photos_imported+" / "+nbphotos);
} else {
finish=true;
$("#text_result").html(ajax_done);
return false;
}
} else {
// ajax error => exit the while
console.info("Ajax execution error "+nb_photos_imported);
return false;
}
} // While
if (finish==true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of "+nb_photos_imported+" photos done.");
}
} else{
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#myform').show("slow");
}
}
});
}
});
}); // callback #text_result.show()
return false;
});
});
Here is my new code. The console log show the progression of the percentage, the photos are imported, but I still have the display at the end. If I put a breakpoint with me debugging tool somewhere in the loop, the display is refreshing and everything is OK...
$(function () {
$("#myprogressbar").show();
var RetourNbPhotos = "";
var RetourImported = "";
var fini = false;
var percent_progressbar = 0;
var nb_photos_imported = 0;
var datas = desvariables; // datas sent with ajax
// Number of photos to import
function NbPhotoAjax() {
return $.ajax({
type: 'POST',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-nbphotos.php',
data: 'chem=$cheminimport',
success: function (nbphotos) {
RetourNbPhotos = nbphotos;
}
});
}
// Photo Ajax Import
function ImportPhotoAjax() {
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show();
// RetourImported = "";
return $.ajax({
type: 'GET',
async: false,
url: '/boutique/modules/importimageswithiptc/ajax-traitement.php',
data: datas,
success: function (resultat) {
RetourImported = resultat;
}
});
}
$("#myprogressbar").progressbar({
value: percent_progressbar
});
$('#generator').submit(function () {
$('#generator').hide();
if (jQuery.trim($("#id_product_src").val()).length != 0) {
$.when(NbPhotoAjax()).then(function () {
if (RetourNbPhotos > 0) {
while (nb_photos_imported < RetourNbPhotos) {
$.when(ImportPhotoAjax()).then(function () {
nb_photos_imported++;
if (RetourImported == "ok") {
percent_progressbar = Math.floor(nb_photos_imported * 100 / RetourNbPhotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Success : " + percent_progressbar + "%");
$(".progression").html(nb_photos_imported + " / " + RetourNbPhotos);
} else {
fini = true;
$("#text_result").html("ajax_reussi");
return false;
}
}).fail(function () {
// ajax error => exit the while
console.info("Ajax execution error " + nb_photos_imported);
return false;
});
} // While
if (fini == true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of " + nb_photos_imported + " photos done.");
}
} else {
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#generator').show("slow");
}
});
}
return false;
});
});

Resources