I can not remove data validation with 2 criterias - Function onEdit(e) - validation

I would like to run function onEdit(e) to remove Data validation with these 2 criterias as below:
Remove for columns G,H,I,K if L is "no need".
Remove for columns M,N,O,Q if R is "no need<2>"
My script runs well for the first criteria.
However, it does not work for the second.
I can not figure out the solution.
Pls help me to correct the script.
function onEdit(e) {
var range = e.range;
var sheet = range.getSheet();
var row = range.getRow();
var values = sheet.getRange(`L${row}`).getValues()[0];
var r = sheet.getRangeList(["G", "H", "I", "K"].map(f => `${f}${row}`));
if (values.includes("no need")) {
r.clearDataValidations().setValue("no need");
} else {
var rules = ["'Data validation'!$G$5:$G$1003", "'Data validation'!$H$5:$H$1003", "'Data validation'!$I$5:$I$1003", "'Data validation'!$K$5:$K$1003"];
r.getRanges().forEach((rr, i) => rr.setDataValidation(SpreadsheetApp.newDataValidation().requireValueInRange(e.source2.getRange(rules[i]), true).build()));
}
var values1 = sheet.getRange(`R${row1}`).getValues()[0];
var r1 = sheet.getRangeList(["M", "N", "O", "Q"].map(f1 => `${f1}${row1}`));
if (values1.includes("no need<2>")) {
r1.clearDataValidations().setValue("no need<2>");
} else {
var rules1 = ["'Data validation'!$M$5:$M$1003", "'Data validation'!$N$5:$N$1003", "'Data validation'!$O$5:$O$1003", "'Data validation'!$Q$5:$Q$1003"];
r1.getRanges().forEach((rr1, i) => rr1.setDataValidation(SpreadsheetApp.newDataValidation().requireValueInRange(e.source.getRange(rules1[i]), true).build()));
}
}
Many thanks
Here is my GG sheet link:
https://docs.google.com/spreadsheets/d/1osCKdZsvaKTFJyD2wfcCoQtIfGxTR6ovt9eE7zabyzs/edit?usp=sharing

Related

dc.numberDisplay showing count for single group, not count of number of groups

I have data that looks like this:
var records = [
{id: '1', cat: 'A'},
{id: '2', cat: 'A'},
{id: '3', cat: 'B'},
{id: '4', cat: 'B'},
{id: '5', cat: 'B'},
{id: '6', cat: 'C'}
];
I want to create a dc.numberDisplay that displays the count of the number of unique categories, 3 in the example data above (A, B, & C).
This is what I'm currently doing:
var ndx = crossfilter(data); // init crossfilter
// create dimension based on category
var categoryDimension = ndx.dimension(
function (d) {
return d.category;
}
);
// Group by category
var categoryGroup = categoryDimension.group();
var categoryCount = dc.numberDisplay('#category-count'); // An empty span
categoryCount
.group(categoryGroup)
.valueAccessor(
function (d) { return d.value; }
);
The problem is that the numberDisplay displays 2 instead of 3. When debugging, I found that when the valueAccessor is called, d is the count of the number of elements of category A instead of the count of the number of categories.
How can I solve this problem?
UPDATE: Thanks to Nathan's solution, here is a working code snippet (ES2016 style)
const categoryDimension = claims.dimension(
(d) => {
return d.cat;
}
);
const categoryGroup = categoryDimension.groupAll().reduce(
(p, v) => { // add element
const cat = v.cat;
const count = p.categories.get(cat) || 0;
p.categories.set(cat, count + 1);
return p;
},
(p, v) => { // remove element
const cat = v.cat;
const count = p.categories.get(cat);
if (count === 1) {
p.categories.delete(cat);
} else {
p.categories.set(cat, count - 1);
}
return p;
},
() => { // init
return {
categories: new Map()
};
});
categoryCount
.group(categoryGroup)
.valueAccessor(
(d) => {
return d.categories.size;
}
);
You will need to use groupAll() since the number-display only looks at the top group. Then provide custom reduce functions to track unique categories. Finally, when DC.js pulls the value from the top group (there is only one) - just return the number of categories (which is the number of keys in the p object).
var categoryGroup = categoryDimension.groupAll().reduce(
function (p, v) { //add
if(p[v.cat]) {
p[v.cat]++;
} else {
p[v.cat] = 1;
}
return p;
},
function (p, v) { //remove
p[v.cat]--;
if(p[v.cat] === 0) {
delete p[v.cat];
}
return p;
},
function () { //init
//initial p - only one since using groupAll
return {};
}
);
console.debug("groups", categoryGroup.value());
dc.numberDisplay('#category-count')
.group(categoryGroup)
.valueAccessor(
function (d) { return Object.keys(d).length; }
);

Update multiple tags rowchart in dc.js

I am looking for how to create a rowchart in dc.js to show and filter items with multiple tags. I've summed up a few answers given on stack overflow, and now have a working code.
var data = [
{id:1, tags: [1,2,3]},
{id:2, tags: [3]},
{id:3, tags: [1]},
{id:4, tags: [2,3]},
{id:5, tags: [3]},
{id:6, tags: [1,2,3]},
{id:7, tags: [1,2]}];
var content=crossfilter(data);
var idDimension = content.dimension(function (d) { return d.id; });
var grid = dc.dataTable("#idgrid");
grid
.dimension(idDimension)
.group(function(d){ return "ITEMS" })
.columns([
function(d){return d.id+" : "; },
function(d){return d.tags;},
])
function reduceAdd(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) + 1; //increment counts
});
return p;
}
function reduceRemove(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) - 1; //decrement counts
});
return p;
}
function reduceInitial() {
return {};
}
var tags = content.dimension(function (d) { return d.tags });
var groupall = tags.groupAll();
var tagsGroup = groupall.reduce(reduceAdd, reduceRemove, reduceInitial).value();
tagsGroup.all = function() {
var newObject = [];
for (var key in this) {
if (this.hasOwnProperty(key) && key != "") {
newObject.push({
key: key,
value: this[key]
});
}
}
return newObject;
}
var tagsChart = dc.rowChart("#idtags")
tagsChart
.width(400)
.height(200)
.renderLabel(true)
.labelOffsetY(10)
.gap(2)
.group(tagsGroup)
.dimension(tags)
.elasticX(true)
.transitionDuration(1000)
.colors(d3.scale.category10())
.label(function (d) { return d.key })
.filterHandler (function (dimension, filters) {
var fm = filters.map(Number)
dimension.filter(null);
if (fm.length === 0)
dimension.filter(null);
else
dimension.filterFunction(function (d) {
for (var i=0; i < fm.length; i++) {
if (d.indexOf(fm[i]) <0) return false;
}
return true;
});
return filters;
}
)
.xAxis().ticks(5);
It can be seen on http://jsfiddle.net/ewm76uru/24/
Nevertheless, the rowchart is not updated when I filter by one tag. For example, on jsfiddle, if you select tag '1', it filters items 1,3,6 and 7. Fine. But the rowchart is not updated... I Should have tag '3' count lowered to 2 for example.
Is there a way to have the rowchart tags counts updated each time I filter by tags ?
Thanks.
After a long struggle, I think I have finally gathered a working solution.
As said on crossfilter documentation : "a grouping intersects the crossfilter's current filters, except for the associated dimension's filter"
So, the tags dimension is not filtered when tag selection is modified, and there is no flag or function to force this reset. Nevertheless, there is a workaround (given here : https://github.com/square/crossfilter/issues/146).
The idea is to duplicate the 'tags' dimension, and to use it as the filtered dimension :
var tags = content.dimension(function (d) { return d.tags });
// duplicate the dimension
var tags2 = content.dimension(function (d) { return d.tags });
var groupall = tags.groupAll();
...
tagsChart
.group(tagsGroup)
.dimension(tags2) // and use this duplicated dimension
as it can been seen here :
http://jsfiddle.net/ewm76uru/30/
I hope this will help.

How to create a tooltip with custom value

i use NVD3 for a scatter chart but when hovering for the tooltip i want the label instead of the key.
this is my json:
long_data = [
{
key: 'PC1',
color: '#00cc00',
values: [
{
"label" : "Lichtpuntje" ,
"x" : 11.16,
"y" : -0.99,
"size":1000,
"color": '#FFCCOO'
} ,
{ ....
this is the js
nv.addGraph(function() {
chart = nv.models.scatterChart()
.showDistX(true)
.showDistY(true)
.useVoronoi(true)
.color(d3.scale.category10().range())
.transitionDuration(300)
...
chart.xAxis.tickFormat(d3.format('.02f'));
chart.yAxis.tickFormat(d3.format('.02f'));
chart.tooltipContent(function(i) { return labelArray[i]; });
d3.select('#test1 svg')
.datum(long_data)
.call(chart);
...
how i can i get the tooltip to have the label value? or how can i have i as index parameter?
ok, not a clean solution, but works:
chart.tooltipContent(function(key, y, e, graph) {
labelIndex=arrayContains(resultYVal, e);
return resultLabel[labelIndex];
});
function arrayContains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] == obj) {
return i;
}
}
return false;
}
You can access your label variable like this:
chart.tooltipContent(function(graph) {
console.log(graph); //examine the graph object in the console for more info
return graph.point.label;
});
Newer NVD3 versions use tooltipGenerator. Also I don't understand why shev72 is iterator over the whole series, we're getting the index in the series by NVD3 directly, e.g. if our data looks like this:
data = [{"key": "Group 0", "values": [{"y": 1.65166973680992, "x": 0.693722035658137, "z": "SRR1974855"}, {"y": 1.39376073765462, "x": -0.54475764264808, "z": "SRR1974854"}]
then you can get your z values like this:
chart.tooltip.contentGenerator(function (d) {
var ptIdx = d.pointIndex;
var serIdx = d.seriesIndex;
z = d.series[serIdx].values[ptIdx].z
return z;
});
For anyone here having issues trying to show a custom tooltip with InteractiveGuideline enabled, you must use the following:
chart.interactiveLayer.tooltip.contentGenerator(function (obj) { ... });
As a bonus, here's the code for the default table layout with an added custom value 'z':
chart.interactiveLayer.tooltip.contentGenerator(function (obj) {
var date = obj.value; // Convert timestamp to String
var thead = '<thead><tr><td colspan="4"><strong class="x-value">'+ date +'</strong></td></tr></thead>';
var table = '<table>' + thead + '<tbody>';
// Iterate through all chart series data points
obj.series.forEach(dataPoint => {
// Get all relevant data
var color = dataPoint.color;
var key = dataPoint.key;
var value = dataPoint.value;
var string = dataPoint.data.z; // Custom value in data
var row = '<tr><td class="legend-color-guide"><div style="background-color: '+ color +';"></div></td><td class="key">'+ key +'</td><td class="string">'+ string +'</td><td class="value">'+ value +'</td></tr>';
table += row;
});
// Close table & body elements
table += '</tbody></table>';
return table;
});
I found the answer from davedriesmans quite useful, however note that in the code
chart.tooltipContent(function(key, y, e, graph)) is not for a scatterPlot.
This looks like the function for a pie chart. In that case you can use the e.pointIndex directly to allow you to index into the series by graph.series.values[e.pointIndex].
However, I built on the function davedriesmans suggested for a scatterplot as follows.
function getGraphtPt(graph, x1, y1) {
var a = graph.series.values;
var i = a.length;
while (i--) {
if (a[i].x==x1 & a[i].y==y1) {
return a[i];
}
}
return null;
}
the main chart call to insert the tooltip is just
chart.tooltipContent(function (key, x, y, graph) {
s = "unknown";
pt = getGraphtPt(graph, x, y);
if (pt != null) {
//below key1 is a custom string I added to each point, this could be 'x='+pt.x, or any custom string
// I found adding a custom string field to each pt to be quite handy for tooltips
s = pt.key1;
}
return '<h3>' + key + s + '</h3>';
});

How to pivot a table with d3.js?

Consider the following tabular data (just an example):
A,B,C,D,x,y,z
a0,b0,c0,d0,0.007,0.710,0.990
a0,b0,c0,d1,0.283,0.040,1.027
a0,b0,c1,d0,0.017,0.688,2.840
a0,b0,c1,d1,0.167,0.132,2.471
a0,b1,c0,d0,0.041,0.851,1.078
a0,b1,c0,d1,0.235,1.027,1.027
a0,b1,c1,d0,0.037,0.934,2.282
a0,b1,c1,d1,0.023,1.049,2.826
a1,b0,c0,d0,0.912,0.425,1.055
a1,b0,c0,d1,0.329,0.932,0.836
a1,b0,c1,d0,0.481,0.681,0.997
a1,b0,c1,d1,0.782,0.595,2.294
a1,b1,c0,d0,0.264,0.918,0.857
a1,b1,c0,d1,0.053,1.001,0.920
a1,b1,c1,d0,1.161,1.090,1.470
a1,b1,c1,d1,0.130,0.992,2.121
Note that each combination of distinct values for columns A, B, C, and D occurs exactly once in this table. Hence, one can think of this subset of columns as the "key columns", and the remaining columns as the "value columns".
Let's say this data is in some file data.csv, and that we read this file in with d3.csv, into the callback argument data, like so:
d3.csv('data.csv', function (error, data) {
...
});
I'm looking for a convenient d3.js manipulation to transform data so that the C column is "pivoted". By this I mean that the "value" columns of the transformed table are those obtained by "crossing" the values of the C column with the original "value" columns, x, y, and z. In other words, in csv format, the transformed table would look like this:
A,B,D,x_c0,x_c1,y_c0,y_c1,z_c0,z_c1
a0,b0,d0,0.007,0.017,0.710,0.688,0.990,2.840
a0,b0,d1,0.283,0.167,0.040,0.132,1.027,2.471
a0,b1,d0,0.041,0.037,0.851,0.934,1.078,2.282
a0,b1,d1,0.235,0.023,1.027,1.049,1.027,2.826
a1,b0,d0,0.912,0.481,0.425,0.681,1.055,0.997
a1,b0,d1,0.329,0.782,0.932,0.595,0.836,2.294
a1,b1,d0,0.264,1.161,0.918,1.090,0.857,1.470
a1,b1,d1,0.053,0.130,1.001,0.992,0.920,2.121
In case there's no easy way to do this, a simpler (but still useful) variant would be to do a similar transformation after first discarding all but one of the "value" columns. For example, after discarding the x and y columns, pivoting the C column would produce (in csv format):
A,B,D,c0,c1
a0,b0,d0,0.990,2.840
a0,b0,d1,1.027,2.471
a0,b1,d0,1.078,2.282
a0,b1,d1,1.027,2.826
a1,b0,d0,1.055,0.997
a1,b0,d1,0.836,2.294
a1,b1,d0,0.857,1.470
a1,b1,d1,0.920,2.121
The simplification lies in that now the original value column (z) can be simply replaced by a set of columns named after the values (c0 and c1 in this case) in the column that was pivoted (C).
You are looking for d3.nest:
d3.csv('data.csv', function (data) {
var nester = d3.nest()
.key(function (d) { return d.A; })
.key(function (d) { return d.B; })
.key(function (d) { return d.D; })
.rollup(function (values) {
var sortedValues = values.sort(function (x, y) {
return x.C < y.C ? -1 : x.C > y.C ? 1 : 0;
});
var mkKey = function (c, name, v) {
return {
name: 'C_' + c + '_' + name,
value: v
};
}
var pivotedX = sortedValues.map(function (d) { return mkKey(d.C, 'x', d.x); }),
pivotedY = sortedValues.map(function (d) { return mkKey(d.C, 'y', d.y); }),
pivotedZ = sortedValues.map(function (d) { return mkKey(d.C, 'z', d.z); });
return Array.prototype.concat.apply([], [pivotedX, pivotedY, pivotedZ]);
});
var nestedData = nester.entries(data);
var pivotedData = [];
nestedData.forEach(function (kv1) {
var a = kv1.key;
kv1.values.forEach(function (kv2) {
var b = kv2.key;
kv2.values.forEach(function (kv3) {
var d = kv3.key;
var obj = {
A: a,
B: b,
D: d
};
kv3.values.forEach(function (d){
obj[d.name] = d.value;
})
pivotedData.push(obj);
})
})
})
console.log(JSON.stringify(pivotedData, null, ' '));
});
The result in nestedData would be of the following form:
[
{
"A": "a0",
"B": "b0",
"D": "d0",
"C_c0_x": "0.007",
"C_c1_x": "0.017",
"C_c0_y": "0.710",
"C_c1_y": "0.688",
"C_c0_z": "0.990",
"C_c1_z": "2.840"
},
...,
{
"A": "a1",
"B": "b1",
"D": "d1",
"C_c0_x": "0.053",
"C_c1_x": "0.130",
"C_c0_y": "1.001",
"C_c1_y": "0.992",
"C_c0_z": "0.920",
"C_c1_z": "2.121"
}
]
Demo Look at script.js and the output on the console.

how to pass to or more list of series to set series

Hi I am trying to implement a combined highchart using dotnet highcharts.So I have a column chart+pie chart.
I made List allSeries = new List()for column Chart and List pieSeries = new List()for pie chart.
I dont know how to pass this two series to to the .SetSeries() wich accepts SetSeries(Series series);
or SetSeries(Series[] seriesArray);
public ActionResult Profit()
{
DBContext.Current.Open();
List<RoomType> result = new List<RoomType>();
result = RoomType.Selectcount();
List<Series> allSeries = new List<Series>();
List<Series> pieSeries = new List<Series>();
List<DotNet.Highcharts.Options.Point> puncte = new List<DotNet.Highcharts.Options.Point>();
string[] categories = new[] { "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" };
object[] pointnum = new object[12];
foreach (var j in result)
{
for (int i = 0; i < pointnum.Length; i++)
{
pointnum[i] = Roomtypereservations.RoomTypeByDate(j.RoomType_ID, i + 1).FirstOrDefault().NumRezervari;
}
allSeries.Add(new Series
{
Type=ChartTypes.Column,
Name = j.Room_Type,
//Data = new Data(myData)
Data = new Data(pointnum.ToArray())
});
pieSeries.Add(new Series
{
Type = ChartTypes.Pie,
Name = "Total rooms",
Data = new Data(puncte.ToArray())
});
puncte.Add(new DotNet.Highcharts.Options.Point
{
Name = j.Room_Type,
Y=13
//Data = new Data(myData)
});
}
Highcharts chart = new Highcharts("chart")
.SetTitle(new Title { Text = "Combination chart" })
.SetTooltip(new Tooltip { Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; }" })
.SetXAxis(new XAxis { Categories =categories} )
.SetTooltip(new Tooltip { Formatter = "TooltipFormatter" })
.AddJavascripFunction("TooltipFormatter",
#"var s;
if (this.point.name) { // the pie chart
s = ''+
this.point.name +': '+ this.y +' fruits';
} else {
s = ''+
this.x +': '+ this.y;
}
return s;")
.SetLabels(new Labels
{
Items = new[]
{
new LabelsItems
{
Html = "Total fruit consumption",
Style = "left: '40px', top: '8px', color: 'black'"
}
}
})
.SetPlotOptions(new PlotOptions
{
Pie = new PlotOptionsPie
{
Center = new[] { "100", "80" },
Size = "100",
ShowInLegend = false,
DataLabels = new PlotOptionsPieDataLabels { Enabled = false }
}
})
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());
return View(chart);
When i am working with only one series like in my sample
its working:
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());
how can i pas both pieSeries and all Series to .SetSeries?
You don't need both allSeries and pieSeries. I would get rid of pieSeries. You can assign as many series to your allSeries List as you need and they can be of any type. So change your pieSeries.Add to the following:
allSeries.Add(new Series
{
Type = ChartTypes.Pie,
Name = "Total rooms",
Data = new Data(puncte.ToArray())
})
Then the following statement will work and all of your required Series to the chart:
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());

Resources