How to iterate over an array of class objects in Handlebar? - handlebars.js

I have an animal array:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
How do I pass it to the handlebar and iterate it ? Basically, I want to display all animals, with each of animal, display all of its properties.
Thanks
Minh

I have figured it out myself, in order to do what I want. I need to do:
Server.js:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
// Routes:
app.get("/allpets",function(req,res){
res.render("allpets", {pets: animals});
};
app.get("/pets/:id",function(req,res){
var type = req.params.id;
var index = -1
for(var i = 0; i < animals.length; i++){
if(animals[i].type === type){
index = i;
break;
}
res.render("animal", animals[index]);
});
Then, we will need to create 2 handlebar views. One is called allpets.hbs, the other one is called animal.hbs
allpets.hbs:
<ul>
{{#each pets}}
<li>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</li>
{{/each}}
</ul>
============================================================
animal.hbs:
<ul>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</ul>

Related

ElasticSearch 7 nest 7 return attribute from result all result

I'm using ElarsticSearch 7.7 & NEST 7.7 and on my web page, I'm getting 9 search result documents per page. Even I'm showing the first 9 results on the page, I need to return some property values from all the results for side filtration on the web page.
Eg: if I'm searching "LapTop", my page will show 9 results on the first page. Also, I need to show all the "Manufactures" from all the search results. Not only manufacturers in the first-page result. Then customers can filter by manufacture not only display on the first page.
I have tried GlobalAggregation but it returns categories and manufactures only items in selected page.
public SearchResult Search(SearchType searchType, string searchQuery, int storeId, int pageNumber = 1, int pageSize = 12, IList<SearchFilter> requestFilter = null, decimal? priceFrom = 0, decimal? priceTo = 100000000, string sortBy = null, int totalCount = 0)
{
var queryContainer = new QueryContainer();
var sorts = new List<ISort>();
sorts.Add(new FieldSort { Field = "_score", Order = SortOrder.Descending });
switch (sortBy)
{
case "z-a":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Descending });
break;
case "a-z":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Ascending });
break;
}
var aggrigations = new AggregationDictionary
{
{"average_per_child", new
AverageAggregation("average_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"max_per_child", new MaxAggregation("max_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"min_per_child", new MinAggregation("min_per_child", Field<ElasticIndexGroupProduct>(d => d.Price))},
{
"globle_filter_aggrigation", new GlobalAggregation("globle_filter_aggrigation")
{
Aggregations =new AggregationDictionary
{
{"category_flow", new TermsAggregation("category_flow"){Field = Field<ElasticIndexGroupProduct>(p => p.CategoryFlow)} },
{"manufacturers", new TermsAggregation("manufacturers"){Field = Field<ElasticIndexGroupProduct>(p => p.Manufacturer)} }
}
}
}
};
var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
{
Profile = true,
From = (pageNumber - 1) * pageSize,
Size = pageSize,
Version = true,
Sort = sorts,
//Scroll = Time.MinusOne,
Aggregations = aggrigations
};
var multiMatch = new QueryStringQuery
{
Query = searchQuery,
Fields = GetSearchFields(searchType),
Boost = 1.1,
Name = "named_query",
DefaultOperator = Operator.Or,
Analyzer = "standard",
QuoteAnalyzer = "keyword",
AllowLeadingWildcard = true,
MaximumDeterminizedStates = 2,
Escape = true,
FuzzyPrefixLength = 2,
FuzzyMaxExpansions = 3,
FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
Rewrite = MultiTermQueryRewrite.ConstantScore,
Fuzziness = Fuzziness.Auto,
TieBreaker = 1,
AnalyzeWildcard = true,
MinimumShouldMatch = 2,
QuoteFieldSuffix = "'",
Lenient = true,
AutoGenerateSynonymsPhraseQuery = false
};
searchRequest.Query = new BoolQuery
{
Must = new QueryContainer[] { multiMatch },
Filter = new QueryContainer[] { queryContainer }
};
var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
var categoryFlowsGlobe = new List<string>();
var allAggregations = searchResponse.Aggregations.Global("globle_filter_aggrigation");
var categories = allAggregations.Terms("category_flow");
foreach (var aggItem in categories.Buckets)
{
if (!categoryFlowsGlobe.Any(x => x == aggItem.Key))
{
categoryFlowsGlobe.Add(aggItem.Key);
}
}
}
This is the exact use case for Post filter - to run a search request that returns hits and aggregations, then to apply filtering to the hits after aggregations have been calculated.
For Manufacturers, these can be retrieved with a terms aggregation in the search request - you can adjust the size on the aggregation if you need to return all manufacturers, otherwise you might decide to return only the top x.

How to get the difference image of this month and the previous month in Google Earth Engine with a smart way?

How to get the difference image of this month and the previous month in Google Earth Engine with a smart way?
study area 25E-75E,5S-35N。
// study area 25E-75E,5S-35N。
var geometry =
ee.Geometry.Polygon(
[[[25, 35],
[25, 5],
[75, 5],
[75, 35]]], null, false);
var regions = ee.FeatureCollection([
ee.Feature(geometry)
]);
// imgCol
var now = ee.Date(Date.now());
var NDVICollection=ee.ImageCollection('MODIS/006/MOD13Q1')
.filterDate('2010-01-01',now)
.filterBounds(regions)
.select('NDVI');
var col = NDVICollection.map(function(img){
return img.multiply(0.0001)
.copyProperties(img,['system:time_start','system:time_end']);
});
// grouped by month
var months = ee.List([11,12,1,2]);
var byMonth = ee.ImageCollection.fromImages(
months.map(function (m) {
return col.filterDate('2019-11-01',now).filter(ee.Filter.calendarRange(m, m, 'month'))
.select('NDVI').mean()
.set('month', m);
}));
mask
var meanNDVI = byMonth.reduce(ee.Reducer.mean());
var mask = meanNDVI.gt(0.1);
Create difference image
**var img12 = byMonth.filter(ee.Filter.eq('month', ee.Number(12))).first().updateMask(mask);
var img11 = byMonth.filter(ee.Filter.eq('month', ee.Number(11))).first().updateMask(mask);
var img1 = byMonth.filter(ee.Filter.eq('month', ee.Number(1))).first().updateMask(mask);
var img2 = byMonth.filter(ee.Filter.eq('month', ee.Number(2))).first().updateMask(mask);
var ndviChange_12 = img12.subtract(img11).set('name','ndviChange_12');
var ndviChange_1 = img1.subtract(img12).set('name','ndviChange_1');
var ndviChange_2 = img12.subtract(img1).set('name','ndviChange_2');
var ndviChange = ee.ImageCollection([ndviChange_12,ndviChange_1,ndviChange_2]);**
I want make it much more smart, what should I do? make a function or something else?
Show the image
Map.centerObject(regions);
Map.addLayer(byMonth);
Map.addLayer(ndviChange);
I think the solution is to use iterate on your byMonth collection . Check this example in the documentations.
https://developers.google.com/earth-engine/ic_iterating

How do I format values in my lua table to be: t = {['foo'] = true, ['bar'] = true}?

This is in relation to a previous question: Checking values across multiple location and returning a match only if the sources are unique.
Essentially, the function relys on the data being in the format:
local vendors = {
Asda = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true, Pampers = true, Simple = true},
Tesco = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true},
Spar ={Nestle = true, Johnsons = true, Pampers = true, Simple = true}
}
However, I am collecting the data by cycling through path locations and adding them into a table, which just creates a list such as:
Asda = {"Kellogg", "Cadbury", "Nestle", "Johnsons", "Pampers", "Simple"}
There is another way I can add them:
local Asda = {}
for index = 1, 9 do
local pathAsda = factReference -- some path location which changes by index increasing
if pathAsda ~= "" then
Asda[#Asda+1] = {[Asda] = true} -- table.insert(Asda, pathAsda), for the previously mentioned format
end
Which would leave me with:
Asda= {{Kellogg = true}, {Cadbury = true}, {Nestle = true}, {Johnsons = true}, {Pampers = true}, {Simple = true}}
I'd then use:
table.insert(vendorSources,Asda)
Neither of these formats work with the function in the answer and I can't seem to figure out how to amend any section to enable this to work.
function intersection(s1, s2) -- finds out if two sets (s1 & s2) overlap
local output = {}
for key in pairs(s1) do
output[#output + 1] = s2[key]
end
return output
end
Is there a way to edit either list (Asda) to be in the correct format?
You'd need to use Asda[pathAsda] = true instead of Asda[#Asda+1] = {[pathAsda] = true}, but keep in mind that the order elements is not guaranteed in this case.

How to use notanyof in nlobjSearchFilter

var ids = ['1', '2', '3'];
var filters = new Array();
filters[0] = new nlobjSearchFilter('mainline', null, 'is', 'T');
filters[4] = new nlobjSearchFilter('entity', null, 'notanyof', ids);
var searchResult = nlapiSearchRecord('creditmemo', null, filters, columns);
Hello I'm trying to list all credit memos but where the customer ID is not 1,2 or 3?
Can you help me? Thanks
The proper operator is "noneof".
new nlobjSearchFilter('entity',null,'noneof',[1,2,3]);

FLEX: Actionscript: Can I create new objects from inside an ArrayColletion?

I have a syntax problem using Actionscript. Can I create new objects from inside an ArrayColletion ?
var tagsList:TagsListModel = new TagsListModel(new ArrayCollection([
{new TagModel("News", 36, yearPopularity, false, true)},
{new TagModel("Information", 18, yearPopularity, false, true)}
]);
This is the error I get:
1084: Syntax error: expecting colon before rightbrace.
thanks
You don't need curly braces when creating objects with new keyword.
var tagsList:TagsListModel = new TagsListModel(new ArrayCollection([
new TagModel("News", 36, yearPopularity, false, true),
new TagModel("Information", 18, yearPopularity, false, true)
]);
Curly braces are for creating objects of type Object
var tagsList:TagsListModel = new TagsListModel(new ArrayCollection([
{tag:"News", x:36, yp:yearPopularity},
{tag:"Information", x:18, yp:yearPopularity}
]);
The following are one and the same:
var a:Object = {value:10};
trace(a.value);//10
var b:Object = new Object();
b.value = 10;
trace(b.value);//10

Resources