In Vue.js i use this part of code in computed to calculate cumule of amounts. It works good in LocalHost. But when i upload the project to a Web Server, this part of code isn't working.
Code:
personsWithAmount(){
const reducer = (accumulator, currentValue) => accumulator + currentValue.amount;
return this.persons.map((pers)=>{
let p=pers;
if(pers.usercashfloat.length===0){
p.totalAmount=0;
}else if(pers.usercashfloat.length===1){
p.totalAmount=pers.usercashfloat[0].amount;
}else{
window.cashfloat=pers.usercashfloat
p.totalAmount=pers.usercashfloat.reduce(reducer,0);
};
Result in LocalHost :
Array 1 =200
Array2 = 200
Result = 400
Resultat In Server
Array 1 =200
Array2 = 200
Result = 200200
Thanks
It seems like some string concatination is happening. Perhaps this works:
const reducer = (accumulator, currentValue) => Number(accumulator) + Number(currentValue.amount);
Related
I have a costly server ajax request which has one input (full: boolean). If full is false, the server can return either a partial or a full response (response.isFull == true); but if full is true, the server will return a full response. Normally the partial response is good enough, but there are certain conditions that will require a full response. I need to avoid requesting a full response explicitly as much as possible, so I thought I'd start with a BehaviorSubject which I can eventually feed with true and combine it with distinctUntilChanged if I ever need to get the full response. This will give me an observable with false initially and that can give me true if I feed that into it:
const fullSubject = new BehaviorSubject<boolean>(false);
Then I've got a function that takes a boolean parameter and returns an observable with the server request (retried, transformed, etc.). As said, the answer can be partial or full, but it can be full even if the input parameter was false at the server's discretion. For example:
interface IdentityData {
...
isFull: boolean;
}
private getSimpleIdentity(full: boolean): Observable<IdentityData> {
return Axios.get(`/api/identity${full?"?full=true":""}`)
.pipe( ... retry logic ...,
... transformation logic ...,
shareReplay(1) );
}
I need to know how can I combine these so that the following is true:
The server needs to be queried at most twice.
If the first answer is a full answer, no further queries must be performed to the server.
If the first answer is a partial answer, and true is fed into fullSubject, a full answer must be requested.
The expected output from all this is an observable that emits either one full response, or a partial response and, when asked, a full response.
Environment: Vue 2.6.11, RxJS 6.5.5, Axios 0.19.2, TypeScript 3.7.5.
Thanks in advance
Here would be my approach:
const fullSubject = new BehaviorSubject(false);
const src$ = fullSubject.pipe(
switchMap(isFull => Axios.get('...')),
take(2), // Server required at most twice
takeWhile(response => !response.isFull, true), // When `isFull`, it will complete & unsubscribe -> no more requests to the server
shareReplay(1),
);
src$.subscribe(() => { /* ... */ });
function getFullAnswer () {
fullSubject.next(true);
}
takeWhile takes a second argument, inclusive. When set to true, when the predicate function evaluates to false(e.g isFull is true) it will send that value as well. –
if I've got it correctly
private getSimpleIdentity(): Observable<IdentityData> {
return fullSubject.pipe(
switchMap(full => Axios.get(`/api/identity${full ? "?full=true" : ""}`)),
shareReplay(1),
);
}
Uses the retryWhen() operator
const source = of("").pipe(map(() => Math.floor(Math.random() * 10 + 1)));
const example = source
.pipe(
tap((val) => console.log("tap", val)),
map((val) => {
//error will be picked up by retryWhen
if (val !== 5) throw val;
return val;
}),
retryWhen((errors) =>
errors.pipe(
tap(() => console.log("--Wait 1 seconds then repeat")),
delay(1000)
)
)
)
.subscribe((val) => console.log("subscription", val));
/*
output:
tap 3
--Wait 1 seconds then repeat
tap 8
--Wait 1 seconds then repeat
tap 1
--Wait 1 seconds then repeat
tap 4
--Wait 1 seconds then repeat
tap 7
--Wait 1 seconds then repeat
tap 5
subscription 5
*/
I have a DRF model created in h2o flow that is supposed to be binomial and flow indicates that it is binomial
but I am having a problem where, importing it into h2o steam and deploying it to the prediction service, the model does not seem to be recognized as binomial. The reason I think this is true is shown below. The reason this is a problem is because I think it is what is causing the prediction service to NOT show the confidence value for the prediction (this reasoning is also shown below).
In the prediction service, I can get a prediction label, but no values filled in the index-label-probability table.
Using the browser inspector (google chrome), the prediction output seems to depend on a file called predict.js.
In order to get the prediction probability values to show in the prediction service, it seems like this block of code needs to run to get to this line. Opening the predict.js file within the inspector on the prediction service page and adding some debug output statements at some of the top lines (indicated with DEBUG/ENDDEBUG comments in the code below), my showResults() function then looks like:
function showResult(div, status, data) {
////////// DEBUG
console.log("showResult entered")
////////// ENDDEBUG
var result = '<legend>Model Predictions</legend>'
////////// DEBUG
console.log(data)
console.log(data.classProbabilities)
console.log("**showResult: isBinPred=" + isBinaryPrediction)
////////// ENDDEBUG
if (data.classProbabilities) {
////////// DEBUG
console.log("**showResult: data.classProbabilities not null")
////////// ENDDEBUG
// binomial and multinomial
var label = data.label;
var index = data.labelIndex;
var probs = data.classProbabilities;
var prob = probs[index];
result += '<p>Predicting <span class="labelHighlight">' + label + '</span>';
if (probs.length == 2) {
result += ' based on max F1 threshold </p>';
}
result += ' </p>';
result += '<table class="table" id="modelPredictions"> \
<thead> \
<tr> \
<th>Index</th> \
<th>Labels</th> \
<th>Probability</th> \
</tr> \
</thead> \
<tbody> \
';
if (isBinaryPrediction) {
var labelProbabilitiesMapping = [];
outputDomain.map(function(label, i) {
var labelProbMap = {};
labelProbMap.label = outputDomain[i];
labelProbMap.probability = probs[i];
if (i === index) {
labelProbMap.predicted = true;
}
labelProbMap.originalIndex = i;
labelProbabilitiesMapping.push(labelProbMap);
});
labelProbabilitiesMapping.sort(function(a, b) {
return b.probability - a.probability;
});
var limit = labelProbabilitiesMapping.length > 5 ? 5 : labelProbabilitiesMapping.length;
for (var i = 0; i < limit; i++) {
if (labelProbabilitiesMapping[i].predicted === true) {
result += '<tr class="rowHighlight">'
} else {
result += '<tr>'
}
result += '<td>' + labelProbabilitiesMapping[i].originalIndex + '</td><td>' + labelProbabilitiesMapping[i].label + '</td> <td>' + labelProbabilitiesMapping[i].probability.toFixed(4) + '</td></tr>';
}
} else {
for (var label_i in outputDomain) {
if (parseInt(label_i) === index ){
result += '<tr class="rowHighlight">'
} else {
result += '<tr>'
}
result += '<td>' + label_i + '</td><td>' + outputDomain[label_i] + '</td> <td>' + probs[label_i].toFixed(4) + '</td></tr>';
}
}
result += '</tbody></table>';
}
else if ("cluster" in data) {
// clustering result
result = "Cluster <b>" + data["cluster"] + "</b>";
}
else if ("value" in data) {
// regression result
result = "Value <b>" + data["value"] + "</b>";
}
else if ("dimensions" in data) {
// dimensionality reduction result
result = "Dimensions <b>" + data["dimensions"] + "</b>";
}
else {
result = "Can't parse result: " + data;
}
div.innerHTML = result;
}
and clicking the "predict" in the prediction service now generates the console output:
If I were to add a statement isBinaryPrediction = true to forcec the global variable to true (around here) and run the prediction again, the console shows:
indicating that the variable outputDomain is undefined. The variable outputDomain seems to be set in the function showModel. This function appears to run when the page loads, so I can't edit it in the chrome inspector to see what the variable values are. If anyone knows how to fix this problem (getting the prediction probability values to show up for h2o steam's prediction service for binomial models) it would a big help. Thanks :)
The UI has not been updated to handle MOJOs yet and there seems to be a bug. You're welcome to contribute: https://github.com/h2oai/steam/blob/master/CONTRIBUTING.md
My solution is very hacky, but works for my particular case (ie. I have a DRF, binomial model in h2o steam that is not being recognized as a binary model (how I know this is shown in this answer)).
Solution:
In my original post, there was a variable outputDomain that was undefined. Looking at the source code, that variable is set to (what is supposed to be) the domain labels of the output response for the model, here. I changed this line from outputDomain = domains[i1]; to outputDomain = domains[i1-1];. My output after clicking the predict button looks like:
From the official linux download for h2o steam, you can access the prediction service predict.js file by opening steam-1.1.6-linux-amd64/var/master/assets/ROOT.war/extra/predict.js, then saving changes and relaunching the jetty server $ java -Xmx6g -jar var/master/assets/jetty-runner.jar var/master/assets/ROOT.war.
Causes?:
I suspect the problem has something to do with that fact that the global variable isBinaryPrediction in predict.js seems to remain false for my model. The reason that isBinaryPrediction is false seems to be because in the function showInputParameters(), data.m has no field _problem_type. Using console.dir(data, {depth: null}) in the inspector console to see the fields of data.m, I see that the expectedd field data.m._problem_type does not exist and so returns undefined, thus isBinaryPrediction is never set true (here).
Why this is happening, I do not know. I have only used DRF models in steam so far and this may be a problem with that model, but I have not tested. If anyone knows why this may be happening, please let me know.
I am trying to periodically calculate complex top score for all items in post table.
const {log10, max, abs, round} = Math;
const topScore = post => { // from Reddit
const {score, createdAt} = post;
const order = log10(max(abs(score), 1));
const sign = score > 0 ? 1 : (score < 0 ? -1 : 0);
const seconds = Date.now() - createdAt;
return sign * order + seconds / 45000;
};
With the above function, I want to perform something like this:
// Update topScore every 60 seconds.
setInterval(() =>
r.table('post').update(post => post.topScore = topScore(post)).run();
, 60000);
How do I do this with RethinkDB javascript driver?
You can write r.table('post').update(r.js('(function(post) { ... })'), {nonAtomic: true}) where ... is arbitrary JS code. Otherwise you'd either have to translate that code into ReQL or pull down the documents to your client, update them, and then write them back to the server.
This question already has answers here:
Computing Result on server side but session data not isolated per user
(3 answers)
Closed 8 years ago.
I working in a app that i use to compute user details. But somehow, the values of a user alter that of another user.
Below is a fragment of the code
def Compute_UserScore(self, details, ques_no):
try:
if(HomePage.answer_.strip() == ""):
self.response.write("""<script type = "text/javascript">
alert("Dear User, You can not answer same answer twice.. Take test Again !");
</script>""")
self.redirect('/otherPages/subjectSelect.html')
else:
count = 0
HomePage.ans_no = 0
HomePage.unans_no = 0
HomePage.correct_no = 0
HomePage.wrong_no = 0
HomePage.failed_ques = list()
HomePage.answer_ = HomePage.answer_.strip()
question_1 = HomePage.question_.split(" gcdc_split_format ")
while (count != (ques_no)):
user_answer = str(details[count]).strip().capitalize()
real_answer = str(HomePage.answer_[count]).strip().capitalize()
if (len(str(user_answer).strip()) == 1):
HomePage.ans_no = HomePage.ans_no + 1
if(user_answer.strip() == real_answer.strip()):
HomePage.correct_no = HomePage.correct_no + 1
else:
HomePage.wrong_no = HomePage.wrong_no + 1
HomePage.failed_ques.append(str("No. " + str(int((count + 1))) + " " + str(question_1[count])))
else:
HomePage.unans_no = HomePage.unans_no + 1
count = count + 1
HomePage.answer_ = ""
except:
self.redirect('/')
return " "
and this is how my homepage looks like
class HomePage(webapp2.RequestHandler):
percentage = None
subject_answered = None
username_ = None
email_ = None
super_date = None
answer_ = " "
question_ = " "
failed_ques = list()
wrong_no = 0
correct_no = 0
ans_no = 0
unans_no = 0
The problem is, when a user A, take a test, He sees the result of another user B.
Read about Using instance variable, but still have not figure ouut how to make it work
Solution is simple: Stop setting class variables in web development! :)
Web requests are stateless, it's mean you never know what's happen between requests - between setting class variable and redirect.
Use database to store temporary data with user login/name (or use hashing/random for security) or send values by parameters (hidden or after '?') to other html page.
Using database is better, if you don't want this then send values (hidden in html) over http. Here is one version of solution (without database):
1.Use normal html form and write handler for this form - question page.
2.In handler write get method like this:
def post(self, some_parameters):
...
self.render('homepage.html', {'ans_no': ans_no,\
'uans_no': uans_no ...})
3.homepage.html have to be template for showing results
am using KeywordQuery to search and.. the SortList does not affect result, it is always return first 5 results. Any suggestion? The code is bellow...
using (KeywordQuery query = new KeywordQuery(site))
{
var fedManager = new FederationManager(application);
var owner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);
query.SourceId = fedManager.GetSourceByName("NewsRS", owner).Id;
query.QueryText = string.Format("WorkflowStatusOWSCHCS:Approved PublishedUntilDate>=\"{0}\" OR NewsNewsPublishedDate<=\"{0}\"", DateTime.Now);
query.KeywordInclusion = KeywordInclusion.AllKeywords;
query.RowLimit = 5;
query.StartRow = 1;
query.SelectProperties.Add("NewsFriendlyUrl");
query.SelectProperties.Add("NewsNewsTeaser");
query.SelectProperties.Add("NewsNewsDate");
query.SelectProperties.Add("NewsPublishedUntilDate");
query.SelectProperties.Add("NewsNewsContent");
query.SelectProperties.Add("NewsNewsPublishedDate");
query.SelectProperties.Add("NewsNewsImage");
query.SortList.Add("NewsNewsDate", SortDirection.Descending);
var searchExecutor = new SearchExecutor();
var myResults = searchExecutor.ExecuteQuery(query);
}
}
... the NewsNewsDate is marked as Sortable
query.RowLimit = 5; => You are explicitly specifying the Rowlimit to be 5. That is why it returns the first 5 results always. Change the rowlimit and set it to the number of results you need.