How to write a simple JQuery integer division function - html

My webpage displays realtime data that is updated every 10 seconds from our PI server(historian server). I was recently tasked to take two peices of data that are allready displayed on my page and divide them, displaying the new result on a graph. I have very little experience with AJAX/JQuery, so I was wondering if someone out there can lend me a hand?
Clarification:
Hypethetically-
Say I have "Number of Grades" and "Sum of Grades" displayed on my page as basic integers. They are updated every 10 seconds from the server. I want to take those two pieces of live data, divide them, and display the result (in this case it would be the overall average grade). So, my page will display Number of Grades, Sum of Grades, and Average Grade all updated in real time, every 10 seconds.
I am unclear as to whether JQuery can simply take those values off the server and perform division on them and return a value, or if other steps need to be taken to achieve this. I'm completely shooting in the dark here so sorry in advance for any vagueness or lack of required information.Thank you. Some example code is given below:
<span class = 'PIdata' data-tag = 'NumOfGrades' data-on_pi_change = 'NumOfGradeChange'></span>
<span class = 'PIdata' data-tag = 'SumOfGrades' data-on_pi_change = 'SumOfGradeChange'></span>
I want to display a value that divides NumOfGrades by SumOfGrades.

var sumOfGrades = parseFloat($.('#SumOfGradesId').text());
var numberOfGrades = parseFloat($.('#NumberOfGradesId').text());
var result = fn(sumOfGrades , numberOfGrades);
$.('#AverageGradeId').text(result);
This will set the required value.

Simple Maths with jQuery - division
The above link seems to have the answer to your question! Basically just access numbers by their id you set, get the value, parse them into integers or floats, perform your calculation, then store the value into the spot you would like it to appear!

Related

How do I count specific characters/integers in a string in html?

I'm a beginner in html and new to coding as a whole -- I'm currently taking a class and I've been okay up to this point, but I'm having trouble with this specific assignment. We're supposed to create a program that can tell you how many integers are in a string. The user should be asked to input some numbers, for example "123123123", to which the output would tell the user "There are three 3s", essentially. I'm lost so anything helps!
It look like you have to break it to char array and then
Do sorting using for loop just like take distinct value from that and make temp array and return the temp array length

Create a TextItem for each product in a spreadsheet and to set the title of this item as "(Name of the product) (remains : (number remaining))"

I want to make a Google Form for online order which would display the number of remaining units for each product, updated every time an order is passed.
As a first step, I try to create a TextItem for each product in a spreadsheet and to set the title of this item as "(Name of the product) (remains : (number remaining))"
var wsStocks = SpreadsheetApp.openById(ssID).getSheetByName("Stocks");
var form = FormApp.openById(formID);
function myFunction(){
var Products = wsStocks.getRange(1,1,wsStocks.getLastRow(),1).getValues();
for(j=1;j<Products .length+1;j++){
form.addTextItem().setTitle(wsStocks.getRange(j,1).getValue().toString()+" (remains: "+wsStocks.getRange(j,2).getValue().toString()+")");
};
}
When I run the code, the correct number of items are created, but the title seems to be attributed randomly: sometimes it is the expected title, sometimes it remains blank ("Question"). If I run several times the code, the distribution of correct and blank titles changes (sometimes the first and fourth are correct, the other ones are blank, sometimes it's just the second...)
I can check with Logger.log that "Products" does contain the list of products' names, and that the expression given as argument to SetTitle is indeed what I expect. I have no clue what's going on : /
Explanation / Issue:
It is not a good practice to use getRange and getValue within a for loop. You can construct the 2D array Products to include both column A and B and then you can just index both columns directly. I also used template literals to simplify your string expression:
var Products = wsStocks.getRange(1,1,wsStocks.getLastRow(),2).getValues();
for(j=0;j<Products.length;j++){
form.addTextItem().setTitle( `${Products[j][0]} (remains: ${Products[j][1]})` );
};
To answer your question, the issue with your current solution is that you are iteratively adding questions and setting their titles. However, this process needs some time to be completed and the for loop is always faster. You just need to slow down the requests.
Unlike SpreadsheetApp, FormApp does not support the flush method. But there is a workaround which you can use to slow down the requests and that is the sleep method. Of course, this approach will overall slow down your algorithm and if you specify a big enough time interval, your script might not be able to finish in time.
You need to choose the time interval wisely. In the following example, I used 4 seconds, but feel free to try a smaller or bigger time interval depending on the number of requests you need to process. For example, if you still see that you are getting wrong titles, increase that number.
Solution / Workaround:
var wsStocks = SpreadsheetApp.openById(ssID).getSheetByName("Stocks");
var form = FormApp.openById(formID);
function myFunction(){
var Products = wsStocks.getRange(1,1,wsStocks.getLastRow(),2).getValues();
for(j=0;j<Products.length;j++){
form.addTextItem().setTitle( `${Products[j][0]} (remains: ${Products[j][1]})` );
Utilities.sleep(4*1000); // 4 second delay
};
}

Why does my Apps Script reference the wrong row?

The Goal
I am trying to create a spreadsheet using some custom functions. The purpose for the sheet is to keep score in a quizzing competition. The top row has the question number, the second row the score, and the third number the number of fouls for that question.
The Problem
After noticing some problems with the score calculation, I was able to narrow the problem down to the part of the code where I add up the fouls that occurred prior to the current question. It seems that no matter what I do, the code sums over the question row, not the foul row.
Attempted Solutions
The extremely strange thing is that no matter what I change the reference cells to, it always produces the same result (i.e. it still references the question row same as it always has).
Example
I'm not sure if that makes any sense, but I've made an example sheet here so you can see what I'm talking about and try to figure out what is going on. Keep in mind that I'm well aware that I could accomplish what I'm trying to do in the example sheet with a simple built-in formula, but since there's no way to use worksheet formulas on the Apps Script side, I have to create my own version of it. I've made the example editable for anyone with the link, so you should have full access to it; but if you have problems, just let me know, and I'll see what I can do to fix it.
In your For loop, you are summing the indexes rather than the values:
Try:
for (var PrevValue in PrevValues[0]) {
Sum = Sum + Number(PrevValues[0][PrevValue]);
}
EDIT:
You'll also need to account for the case where you pass in a single cell rather than a range (=mySum($B4:B4)), because in that case the value is passed directly instead of an array.
if(PrevValues instanceof Array){
for (var PrevValue in PrevValues[0]) {
Sum = Sum + Number(PrevValues[0][PrevValue]);
}
}else
Sum = PrevValues;

Rows count of Couchbase view subset

When I query some view in Couchbase I get the response that has following structure:
{
"total_rows":100,
"rows":[...]
}
'total_rows' is very useful property that I can use for paging.
But lets say I select only a subset of view using 'start_key' and 'end_key' and of course I don't know how big this subset will be. 'total_rows' is still the same number (as I understand it's just total of whole view). Is there any easy way to know how many rows was selected in subset?
You can use the in-built reduce function _count to get the total count of your query.
Just add _count as reduce function for your view. After that, you will need to make two calls to couchbase:
In one call, you'll set the query param reduce=true (along with either group=true or group_level=n, depending upon how you're sending your key(s)). This will give you the total count of your filtered rows.
In the other call, you'll disable the reduce function with reduce=false because you now need the actual rows.
You can find more details about map and reduce at http://docs.couchbase.com/admin/admin/Views/views-writing.html
You can just use an array count/total/length in whatever language you are using.
For example in PHP:
$result = $cb->view("dev_beer", "beer_by_name", array('startkey' => 'O', 'endkey'=>'P'));
echo "total = >>".count($result["rows"])
If you're actually wanting to paginate your data then you should use limit and skip:
http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-writing-querying-pagination.html
If you have to paginate the view in the efficient way, you actually don't need to specify both start and the end.
Generally it is possible to use startkey/startkey_id and limit. In this case the limit will tell you that the page won't be bigger than known size.
Both cases are described in CouchDB book: http://guide.couchdb.org/draft/recipes.html#pagination
Here is how it works:
Request rows_per_page + 1 rows from the view
Display rows_per_page rows, store + 1 row as next_startkey and next_startkey_docid
As page information, keep startkey and next_startkey
Use the next_* values to create the next link, and use the others to create the previous link

way around the if loops.. actionscript 3

I am making a choice based game.. where I have given the user different objects each time and ones that they click gets a specific value....
this is where the problem comes in when I have to export this into showing their choices I have to write an if statement for everysingle object asking to check it's value.. if it's the one user picked then draw the object on to the stage.. now this gets really messy does anybody know a way around this? can u please explain it to me step by step since I am fairly new at this...
Depending on how many different items you have, you might be able to save a bitmask, like this:
items = 00001101110011
Where 1 represents an item the user has, and 0 one they don't have.
Then, you just need one loop, iterating i, and then check if (1<<i) & items and get the item's data from an array.