Run _.each inside while PARSE - javascript

I have a table named "circle" and it represents mailing list.
Circle can contain user id in invitedUser or circle id in invitedCircle.
I need to get all circles id that contain specific user (in the code: 1-9).
For example if studantA is in CircleA
CircleA is in CircleB
so i need to get for studantA as output CircleA and CircleB.
I try to find all circles who conect each others by while and each, but the status of the job is : Could not connect to Cloud Code.
How can I run this query until no result found?
Parse.Cloud.job("fillMemberInCircles", function (request, status) {
var studentId = "123456789";
var output = [];
var lowLayer = [];
var highLayer = [];
// Get circles when the student appears in column invitedUsers
var invitedUsers = new Parse.Query("circles");
invitedUsers.equalTo("invitedUsers", studentId);
invitedUsers.find({
success: function (invitedUsersResults) {
if (invitedUsersResults.length > 0) {
for (var i = 0; i < invitedUsersResults.length; i++) {
output.push(invitedUsersResults[i].id);
lowLayer.push(invitedUsersResults[i].id);
}
var counter = lowLayer.length;
var _ = require('underscore.js');
while (counter > 0) {
//var _ = require('underscore.js');
_.each(lowLayer, function (currCircle) {
var invitedCirclesQuery = new Parse.Query("circles");
invitedCirclesQuery.equalTo("invitedCircles", currCircle);
invitedCirclesQuery.find().then(function (results) {
if (results.length != 0) { // item exists
for (var j = 0; j < results.length; j++) {
if (output.indexOf(results[j].id) == -1) {
output.push(results[j].id);
highLayer.push(results[j].id);
}
}
}
}).then(function () {
counter--;
if (counter == 0) {
if (highLayer.length == 0) {
console.log("OK");
lowLayer = [];
status.success("SUCSESS: " + output.length.toString());
} else {
lowLayer = highLayer;
counter = lowLayer.length;
highLayer = [];
}
}
});
});
}
}
//status.success("SUCSESS: " + output.length.toString());
},
error: function () {
status.error("[fillMemberInCircles] There was some error with queryMajors");
}
});
});

Related

How do I raise alert message in multiple file uploads

I have multiple selects, where in case user selects same file twice I should display alert message saying that "This file has been already selected". In the example below, file is not added (which is ok) but the alert box does not popup.
$.fn.fileUploader = function(filesToUpload) {
this.closest(".files").change(function(evt) {
var index;
for (var i = 0; i < evt.target.files.length; i++) {
index = filesToUpload.indexOf(evt.target.files[i]);
if (index > -1) {
filesToUpload.splice(index, 1);
}
}
for (i = 0; i < evt.target.files.length; i++) {
var filename = evt.target.files[i].name;
var valid_extensions = /(\.pdf|\.doc|\.docx)$/i;
if (valid_extensions.test(filename)) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\""+ i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name),"</strong> - ", removeLink,"</li> ");
}
$(this).children(".fileList").append(output.join(""));
} else {
alert('Invalid File');
return false;
}
}
});
};
var filesToUpload = [];
$(document).on("click", ".removeFile", function(e) {
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches
// FileName
// and get the index of the match
for (i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].name == fileName) {
// console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
// console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function(e) {
e.preventDefault();
});

$.when apply for single request

I am trying to use $.when apply in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
This is what i do not want to do.
if (apiRequestList.length === 1) {
$.ajax({
});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
}
You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {
var _arguments = Array.prototype.slice.call(arguments);
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
});
Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
return $.post("/echo/html/", {
html: "a = " + a,
delay: Math.random()
});
}
function doIt(apiRequestList) {
$.when.apply(null, apiRequestList).then(function() {
var _arguments = arguments;
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
console.log("----");
});
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);
Example output (it'll vary because of the Math.random()):
a = 4
----
a = 1
a = 2
a = 3
----

azure asynchronous javascript backend - wait function

I'm using Azure Mobile Services and a javascript backend. My problem is that the function don't wait the end of an other function.
I'm trying to choose an item (word) with a particolar rules. i want to pick the item with highest item.wordnumber. If there are few item with the same item.wordnumber i want to pick who has a highest avarage of votes associated at that item (in the other table "votes").
This script don't wait the return of function CalcolateMaxAvg.
I would do as I did in c # with await.
var tableWords = tables.getTable('Word');
var tableVotes = tables.getTable('Votes');
var avgVotesActualWord = 0;
var maxItem = null;
var maxItemVote = 0;
function WordChoice() {
var select = tableWords.orderByDescending('wordnumber').read({success:
function (results)
{
results.forEach(function(item)
{
if(maxItem == null)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber > maxItem.wordnumber)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber == maxItem.wordnumber)
{
//chack who have more votes
avgVotesActualWord = 0;
avgVotesActualWord = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
//the problem is avgVoteActualWord that is always NaN
console.log('Word: %s with avg: %d', item.word, avgVotesActualWord);
if(avgVotesActualWord > maxItemVote)
{
//take the actualword because have more votes
maxItem = item;
maxItemVote = avgVotesActualWord;
}
}
})
if(maxItem != null)
{
console.log('parola: %s', maxItem.word);
maxItem.selected = true;
tableWords.update(maxItem);
}
else
{
console.log('null');
}
}
});
}
function CalcolateMaxAvg(resultsVote)
{
var sum = 0;
var count = 0;
var avg = 0;
resultsVote.forEach(function(itemVote)
{
sum = sum + itemVote.vote;
count = count + 1;
})
if(count > 0)
{
avg = sum / count;
}
//this is a correct value of avgVoteActualWord, but he don't wait the return of this value
console.log('avg: %d', avg);
return avg;
}
The problem is that a call to table.where(...).read(...) is asynchronous - it won't return a number returned by the CalcolateMaxAvg function (it won't return anything). You need to rewrite your code to embrace the asynchronicity of JavaScript, something along the lines of the code below.
var tableWords = tables.getTable('Word');
var tableVotes = tables.getTable('Votes');
var avgVotesActualWord = 0;
var maxItem = null;
var maxItemVote = 0;
function WordChoice() {
var select = tableWords.orderByDescending('wordnumber').read({
success: function (results)
{
function processNextResult(index) {
if (index >= results.length) {
// All done
if(maxItem != null)
{
console.log('parola: %s', maxItem.word);
maxItem.selected = true;
tableWords.update(maxItem);
}
else
{
console.log('null');
}
return;
}
var item = results[index];
if (maxItem == null) {
maxItem = item;
tableVotes.where({ idword: item.id }).read({ success: simpleProcessVotesResult });
} else if (item.wordnumber > maxItem.wordnumber) {
maxItem = item;
tableVotes.where({ idword: item.id }).read({ success: simpleProcessVotesResult });
} else if (item.wordnumber == maxItem.wordnumber) {
//check who have more votes
avgVotesActualWord = 0;
tableVotes.where({idword: item.id}).read({
success: function(resultsVote) {
avgVotesActualWord = CalcolateMaxAvg(resultsVote);
//the problem is avgVoteActualWord that is always NaN
console.log('Word: %s with avg: %d', item.word, avgVotesActualWord);
if(avgVotesActualWord > maxItemVote)
{
//take the actualword because have more votes
maxItem = item;
maxItemVote = avgVotesActualWord;
}
processNextResult(index + 1);
}
});
} else {
processNextResult(intex + 1);
}
}
function simpleProcessVotesResult(resultsVote) {
maxItemsVote = CalcolateMaxAvg(resultsVote);
processNextResult(intex + 1);
}
processNextResult(0);
}
});
}
function CalcolateMaxAvg(resultsVote)
{
var sum = 0;
var count = 0;
var avg = 0;
resultsVote.forEach(function(itemVote)
{
sum = sum + itemVote.vote;
count = count + 1;
})
if(count > 0)
{
avg = sum / count;
}
//this is a correct value of avgVoteActualWord, but he don't wait the return of this value
console.log('avg: %d', avg);
return avg;
}

add an object or edit if exist (indexeddb)

I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
var elements = document.getElementsByClassName('layers');
for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
index = object.index("by_Name");
request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));
request.onsuccess = function (e) {
var result = e.target.result;
if (result === undefined) {
var resultPut = object.put({
Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
Count: 1,
Type: String(elements[i].getAttribute("src").split("/")[4])
});
resultPut.onerror = function (e) {
alert(resultPut.error.name + '\n\n' + resultPut.error.message);
};
} else {
result.Count++;
var requestUpdate = object.put(result);
requestUpdate.onerror = function (event) {
alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
};
}
}(event);
}
}
alert("Finish");
})
The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
(function(myElement) {
if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
...
}
})(elements[i]);
}

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Categories

Resources