Trying to pull a list of ratings from a collection of Reviews and then average them to come up with an aggregated average rating for a Plate. When I look at the data output from the ratings variable I get nothing but "undefined undefined undefined".
averageRating: function() {
var reviews = Reviews.findOne({plateId: this._id});
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = sum / ratings.length;
//Testing output
var test = "";
var x;
for (x in reviews) {
text += reviews[x] + ',';
}
return test;
}
Sorry if this is a super newbie question, but I've been at this for hours and cannot figure it out.
I figured out the issue. As listed above var reviews gets set to a cursor which apparently .pluck does not work on. By first converting the cursor to an array of objects I was then able to use .pluck. So updated code looks like this:
averageRating: function() {
var reviewsCursor = Reviews.find({plateId: this._id});
//Converts cursor to an array of objects
var reviews = reviewsCursor.fetch();
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = (sum / ratings.length).toPrecision(2);
return avg;
}
Related
In Google Earth Engine, is it possible to extract the annual second largest and second smallest value and construct an imagecollection?
Apparently, there is no build-in reducer for this purpose.
Here is my code for getting the min, please guide me on how to get the second max and min.
Thank you!
Here is the code:
var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis
// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));
//init a time band
var createTimeBand= function(image) {
return image.addBands(image.metadata('system:time_start')
.divide(1e18))
// .divide(1000*60*60*24*365))
}
var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
.filterDate(startDate, endDate)
.map(createTimeBand)
var byyearMin = ee.ImageCollection(
// map over each month
ee.List.sequence(0,nyears).map(function (n) {
// calculate the offset from startDate
var ini = startDate.advance(n,'year');
// advance just one month
var end = ini.advance(1,'year');
// filter and reduce
return sst.filterDate(ini,end)
.select(0).min()
// .sort('LST_Day_1km').reverse().first()
.multiply(0.02)
.subtract(273.15)
.set('system:time_start', ini.millis());//convert time to number
}));
var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis
// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));
//init a time band
var createTimeBand= function(image) {
return image.addBands(image.metadata('system:time_start')
.divide(1e18))
// .divide(1000*60*60*24*365))
}
var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
.filterDate(startDate, endDate)
//.map(createTimeBand)
var byyearMin = ee.ImageCollection(
// map over each month
ee.List.sequence(0,nyears).map(function (n) {
// calculate the offset from startDate
var ini = startDate.advance(n,'year');
// advance just one month
var end = ini.advance(1,'year');
var sortedDays = sst.filterDate(ini,end)
.sort('LST_Day_1km')
.toList(sst.size())
var secondLargest = ee.List(sortedDays.get(1))
var secondSmallest = ee.List(sortedDays.get(-1))
var collection = ee.Image(secondLargest)
.addBands(secondSmallest).rename(['secondLargest', 'secondSmallest'])
.multiply(0.02)
.subtract(273.15)
return collection
.set('system:time_start', ini.millis()) //convert time to number
.set('Date', ee.Date(ini))
}));
print(byyearMin)
Hi I'm using this script to rename every sheet by inserting 'Copy of' in front of the existing sheet name where the text in cell 'B36' = 'SAFETY ANALISIS' and the date from cell 'K3'is older then 30 days. My issue is having to do with the date I can't quite figure how to do it. Cell 'K3' cell are in this format "1-Aug-2021" I think I need to convert the date in 'K3' to a number format.
Any help would be greatly appreciated
function getSheet() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sum = 0;
for (var i = 0; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var date = new Date();
var ageInDays = 30;
var threshold = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - ageInDays)
.getTime();
var val = sheet.getRange('K3').getValue();
var val2 = sheet.getRange('B36').getValue();
if (val >= threshold && val2 == 'SAFETY ANALYSIS') {
var sheetName = sheet.getName()
sheet.setName('Copy Of '+sheetName)
}
}
}
You may want to wrap the value you get from cell K3 in a Date() constructor. That should work with spreadsheet dates as well as text strings that look like dates.
I think you have the comparison in val >= threshold the wrong way around. Try something like this:
function renameOldSafetyAnalysisSheets() {
const timeLimit = 30 * 24 * 60 * 60 * 1000; // 30 days
const now = new Date();
const sheets = SpreadsheetApp.getActive().getSheets();
sheets.forEach(sheet => {
if (sheet.getRange('K3').getValue() !== 'SAFETY ANALYSIS') {
return;
}
const date = new Date(sheet.getRange('B36').getValue());
if (!date.getTime()
|| now.getTime() - date.getTime() < timeLimit) {
return;
}
try {
sheet.setName('Copy of ' + sheet.getName());
} catch (error) {
;
}
});
}
function getSheet() {
const shts = SpreadsheetApp.getActive().getSheets();
let d = new Date();
let ageInDays = 30;
let threshold = new Date(d.getFullYear(),d.getMonth(),d.getDate() - ageInDays).valueOf();
shts.forEach(sh => {
let val = new Date(sh.getRange('K3').getValue()).valueOf();
let val2 = sh.getRange('B36').getValue();
if (val <= threshold && val2 == 'SAFETY ANALYSIS') {
sh.setName('Copy Of ' + sh.getName())
}
});
}
How I can extract index vegetation points over collections by adapting this beautiful code by #Rodrigo E. Principe:
Extract pixel values by points and convert to a table in Google Earth Engine
I try extract all values mas GEE is crashing, so only NDVI or EVI can works fine.
I did it with this tutorial https://developers.google.com/earth-engine/tutorial_api_06
// Dataset do sensor LS8
var dataset = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
.filterDate('2018-04-01', '2019-03-31')
.select('B5', 'B4')
.filterBounds(aoi6010)
.filter(ee.Filter.lt('CLOUD_COVER', 20));
var addNDVI = function(image) {
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
return image.addBands(ndvi);
};
var withNDVI = dataset.map(addNDVI);
print(withNDVI);
// Empty Collection to fill
var ft = ee.FeatureCollection(ee.List([]))
var fill = function(img, ini) {
// type cast
var inift = ee.FeatureCollection(ini)
// gets the values for the points in the current img
var ft2 = img.reduceRegions(p601018, ee.Reducer.first(),30)
// gets the date of the img
var date = img.date().format()
// writes the date in each feature
var ft3 = ft2.map(function(f){return f.set("date", date)})
// merges the FeatureCollections
return inift.merge(ft3)
}
// Iterates over the ImageCollection
var newft = ee.FeatureCollection(withNDVI.iterate(fill, ft))
I would like to put week numbers into an Array. Can anybody help me?
I tried this:
var week = [];
var now = moment().week();
while(now) {
var current = moment().week();
week.push(moment().week());
now--;
}
console.log("Week:" + week);
The output is always:
Week:43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43
But I would like 1,2,3,4,5, ... 50,51,52,53
var current = moment().weeksInYear();
var week = [];
for(var i=1;i<=current;i++)
{
week.push(i);
}
console.log(week);
Try this one. You have to use moment().weeksInYear(); out of loop
I am using jquery easyui edatagrid, where one column is of datebox type editor.
I want to auto select today date so that data entry is faster.
Code :
<th field="date" width="50" editor="{type:'datebox',options:{formatter:myformatter,parser:myparser,required:true}}">Date</th>
function myformatter(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return (d<10?('0'+d):d)+'/'+(m<10?('0'+m):m)+'/'+ y;
}
function myparser(s){
if (!s) return new Date();
var ss = (s.split('/'));
var d = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var y = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
}
You can set the date as soon as the grid data is loaded. For example, something like
$('.datebox input').each( function(){ $(this).val(formatDate(new Date())) });
It is a matter of getting the input fields. For me the above works, you can adjust it according to your code. Then you need a function that does the date formatting, for example
function formatDate(value) {
return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getYear();
}