Bubble chart and rowchart are not sync, dc.js - reduce

There is a simple bubble chart (dimension by level1, level2) and row chart(dimension by level_1)
see
https://codepen.io/shakraz/pen/dyYXxJy
var houseDim = ndx.dimension(d=>[d.district, d.name, d.price, d.flat_rate, d.building_rate]);
var districtDim = ndx.dimension(d=>[d.district])
When i click on row chart i expect to see only filtered bubbles, right? But it doesn't work.
But it works vice versa, clicking on bubble filters rowchart, why is that?
For sure it somehow related with reduce function.
Thank you for any advance.

It's a better practice to keep any measures in the value part of the crossfilter group, and leave only the index in the key.
Crossfilter will bin the groups according to the group and dimension key functions. Your instinct was correct that you should be able to use d.name because you want a bubble per row of your data, and d.name is a unique key.
var houseDim = ndx.dimension(d=>d.name);
Here is one simple way to copy each row into a group value:
var houseGroup=houseDim.group().reduce(
(p, d) => ({...p, ...d, count: (d.count || 0) + 1}), // add
(p, d) => ({...p, count: p.count - 1}), // remove
() => {} // init
);
When adding a row, it will copy the data from the row, adding a field called count. Since the keys are unique, the count will be either 1 or 0, depending whether the row is filtered in or out.
Now we can use descriptive field names instead of indexing arrays in the code:
.keyAccessor(function (p) {
return p.value.flat_rate;
})
.valueAccessor(function (p) {
return p.value.building_rate;
})
// ...
.title(function (p) {
return p.key + "\n"
+ "Индекс квартиры: " + p.value.flat_rate + "\n"
+ "Индекс дома: " + p.value.building_rate + " \n"
+ "Район: " + p.value.district + "\n"
+ "Цена: " + p.value.price
})
We also need to visually encode being excluded, by using d.value.count in some of the accessors. I like to send both radius and opacity to zero, but leaving the radius and only using opacity has a calm effect too.
.radiusValueAccessor(function (p) {
console.log('radius', p)
return p.value.count * priceScale(p.value.price);
})
// .colors(colorScale)
// .colorAccessor(function(p) {return p.value.district})
.colorCalculator(p => p.value.count ? colorScale(p.value.district) : 'rgba(0,0,0,0)')
The bubble chart doesn't expose opacity in its public api, but this colorCalculator trick sends opacity to zero when count is 0, and invokes the ordinary colorScale on the value otherwise.
I also had to point to correct dc.css URL in order to get selection behavior to work.
<link rel="stylesheet" href="https://unpkg.com/dc/dist/style/dc.css">
Working fork of your codepen

Related

How to undo changes made from script on contenteditable div

Let's have contenteditable div. Browser itself manage undo on it.
But when additional content changes (or touching selection ranges) are made from script (in addition to user action) then it stops behave as user expected.
In other words when user hit Ctrl+Z then div content is not reverted to previous state.
See following simplified artificial example:
https://codepen.io/farin/pen/WNEMVEB
const editor = document.getElementById("editor")
editor.addEventListener("keydown", ev => {
if (ev.key === 'a') {
const sel = window.getSelection()
const range = window.getSelection().getRangeAt(0)
const node = range.startContainer;
const value = node.nodeValue
node.nodeValue = value + 'aa'
range.setStart(node, value.length + 2)
range.setEnd(node, value.length + 2)
ev.preventDefault()
}
})
All written 'a' letters are doubled.
Undo is ok as long as there is no 'a' typed.
When user typed 'a' (appended to text as double 'aa') and hits Ctrl+Z, then he expects both 'a' will be removed and cursor moves back to original position.
Instead only one 'a' is reverted on undo and second one added by script remain.
If event is also prevented by preventDefault() (which is not needed in this example, but in my real world example i can hardly avoid it) then all is worse.
Because undo reverts previous user action.
I could images that whole undo/redo stuff will be managed by script, but it means implementation of whole undo/redo logic. That's too complicated, possible fragile and with possible many glitches.
Instead I would like tell browser something like that there is atomic change which should be reverted by one user undo. Is this possible?
You can store the "revisions" in an array, then push the innerHTML of the div to it whenever you programmatically change the innerHTML of it.
Then, you can set the innerHTML of the div to the last item in the revisions array whenever the user uses the Ctrl + Z shortcut.
const previousRevisions = []
function saveState() {
previousRevisions.push(editor.innerHTML)
}
function undoEdit() {
if (previousRevisions.length > 0) {
editor.innerHTML = previousRevisions.pop();
}
}
const editor = document.getElementById("editor")
editor.addEventListener("keydown", ev => {
if (ev.key === 'a') {
saveState()
const sel = window.getSelection()
const range = window.getSelection().getRangeAt(0)
const node = range.startContainer;
const value = node.nodeValue
node.nodeValue = value + 'a'
range.setStart(node, value.length + 1)
range.setEnd(node, value.length + 1)
} else if (ev.ctrlKey && ev.key == 'z') {
undoEdit()
}
})
#editor{width:600px;min-height:250px;border:1px solid black;font-size:24px;margin:0 auto;padding:10px;font-family:monospace;word-break:break-all}
<div id="editor" contenteditable="true">type here </div>
The benefit of this solution is that it will not conflict with the browser's native Ctrl + Z shortcut behavior.
Make the parent a div (if it isn't) and make it so it adds spans inside of it every time the user taps a so the new span and set it's id to span-keyword will have aa as the value / text. Then check if the users cursor is at the beginning of it and check if there is no other text in-front of it and the user did no other action in it. If there is no text and no other actions happened do this:
document.getElementById('span-keyword').remove();

Google Chrome executeScript that returns multiple values with one query?

I have the following Google Chrome executeScript.
chrome.tabs.executeScript(
tabs[0].id,
{code: 'document.querySelectorAll(".col-9.col-md-10")[3].innerText'}, citationResult => {
console.log(citationResult);
});
This code gets the 4th element which has the classes col-9 AND `col-md-10' and then gets the inner text of that element. That is a string.
I would like a generalized query which instead returns every element which has col-9 AND `col-md-10'. However, when I try something like this:
chrome.tabs.executeScript(
tabs[0].id,
{code: 'document.querySelectorAll(".col-9.col-md-10")}, citationResult => {
console.log(citationResult);
});
I seem to get an empty array.
Is there a way to get those four elements returned rather than just getting the innerText of that single element?
As wOxxOm said, I needed to return an array of primitives. This is what solved my problem.
'var x = document.querySelectorAll(".col-9.col-md-10"); const finalArray = []; \n' +
'for (let i = 0; i < x.length; i++) {\n' +
' finalArray.push(x[i].innerText);\n' +
'} finalArray;'

How can I automatically insert commas when a user inputs currency value in an Angular 7 reactive form, no [(ngModel)]

I have an input field where the user can input a numeric value. I need to automatically insert commas after every 3rd digit. When the user deletes numbers, the commas need to be in the correct places (after every 3rd digit, starting from the first number) as well as stay in place instead of relocating to the end of the input value. I cannot use ngModel, this is a reactive form.
I have tried this method in my TS file, to mask the user input
maskInputAmount(e) {
const t = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})
(\d{0,3})/);
e.target.value = t[2] ? t[1] + ',' + t[2] + (t[3] ? ',' + t[3] : '') :
t[1];
}
And in my HTML input field
<input (input)="maskInputAmount($event)" maxlength=11
formControlName="businessNetWorth" id="businessNetWorth"
type="text" class="form-control col-3 col-lg-12" data-hint="yes">
I am having commas come after every 3rd number. However, when deleting numbers from the end of the input, the commas at the front of the number should update correctly. For example, I enter '123,456,789'. When I delete the last two numbers I get '123,456,7' when it should be '1,234,567'.
One other issue, when a user deletes one of the first numbers, the comma in the input box automatically repositions itself to the end of the input value, I need it to stay in place. For example: '123,456,789'. I delete '3' and have '124,567,89' and the cursor is now behind the '9' when it should stay in front of the '2'.
How can I change my maskInputAmount(e) method to make this behave correctly?
Following code worked for me. (Assume present currency is in Indian rupees. If you want to have your own currency then you need to mention your country's code in code).
app.component.html
<input type="text" [formControl]="currency" (input)="changeToCurrency(currencyTextRef)" #currencyTextRef>
//sending reference of input element #currencyTextRef to function
{{ currency.value }}
app.component.ts
currency = new FormControl();
temp;
currncyLength=0;
changeToCurrency(currencyTextRef) {
this.currncyLength = this.currency.value.length;
console.log("currency len is "+this.currncyLength);
let index:number;
// if(currencyTextRef.selectionStart || currencyTextRef.selectionStart == '0') {
// console.log("index isss "+currencyTextRef.selectionStart);
index = currencyTextRef.selectionStart; //getting caret(cursor) position
// }
console.log("index is "+index);
// console.log("value is "+this.currency.value);
let a = this.currency.value;
a = a.replace(/,/g,'');
let num:number = + a;
let temp = new Intl.NumberFormat('en-IN').format(num); //inplace of en-IN you can mention your country's code
// console.log("temp is "+temp);
this.currency.setValue(temp.toString());
console.log("pressent len iss "+this.currency.value.length)
if(this.currncyLength<this.currency.value.length) {
console.log("incoming to < ")
index+=1;
currencyTextRef.setSelectionRange(index,index);
}
else if(this.currncyLength >=this.currency.value.length) {
console.log("incoming to > ");
// index-=1;
currencyTextRef.setSelectionRange(index,index);
}
// else {
// currencyTextRef.setSelectionRange(index,index);
// }
}
Following link might help.
Intl number MDN

Value Calculation issue in Google web HTML App

I have created an HTML web app in google script this works like a calculator, This app works fine if I add the input in descending order however if I skip the order and update in put data numbers randomly in any column then I am not getting the output properly
Example:- update the numbers in box number 4 and 5 then update in box number 1 you will find the differences in total numbers
Please refer the attached sheet for detailed script
Project Name- Project Proposal Form
$("#rTpe1").keyup(function(e){
$("#rFor1").val(this.value * $("#PerHourRate1").val());
$("#rFor3").val( Number($("#rFor1").val()) +Number($("#rFor2").val()))
});
$("#rTpe2").keyup(function(e){
$("#rFor2").val(this.value * $("#PerHourRate2").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val()))
});
$("#rTpe12").keyup(function(e){
$("#rFor12").val(this.value * $("#PerHourRate3").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val())+ Number($("#rFor12").val()))
});
$("#rTpe13").keyup(function(e){
$("#rFor13").val(this.value * $("#PerHourRate4").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val())+ Number($("#rFor12").val())+ Number($("#rFor13").val()))
});
I could be wrong, but I think that's the main culprit:
If your work your way top to bottom, the output in '#rFor3' is not affected. For example, if you enter values in the first field ('#rTpe1'), this statement
Number($("#rFor2").val()))
will evaluate to '0' because '#rFor2' probably contains an empty string at this point and Number("") will get you a zero. Because all subsequent input fields reference the results of previous calculations ('rTpe2' references 'rFor1', 'rTpe12' references both 'rFor1' and 'rFor2', etc), the sum will come out as correct.
Now consider the reverse scenario. For simplicity, let's make all your rates equal to 1. If you enter the value of '5' into 'rTpe12', the value of 'rFor3' will be
Number("") + Number("") + Number(5*1) == 5; //the first two inputs will contain empty strings at this point
The output of '#rFor3' would be 5. If you go up a step and enter the value of '2' into 'rTpe2', the value of the 'rFor3' output will change to
Number("") + Number(2*1) == 2; the first input will contain an empty string.
The code is not easy to understand, so even if this solution doesn't work for you, consider caching your DOM elements to improve performance and make your code more readable. Currently, you are using jQuery selectors to search the DOM over and over again, which is a serious performance drag. You could also store your calculated value as a variable and simply add values to it instead of recalculating on each input. For example
$('document').ready(function(){
var total = 0;
var input1 = $('#input1');
var input2 = $('#input1');
var input3 = $('#input1');
var output = $('#output');
input1.keyup(function(e){
var value = Number(this.value);
sum += value;
output.val(sum);
});
});

dc.js crossfilter without reduce

Is crossfilter manipulating my data?
Background
I have performed all the processing I need server side and just want to graph exactly what comes down the json pipe. So far I've get the graph working exactly how I want it to except for it seems my data is being manipulated.
Here's my crossfilter code:
ndx = crossfilter(rData);
runDimension = ndx.dimension(function (d) { return [+d.series, +d.norm_1]; });
runGroup = runDimension.group();
runGroup.reduceSum(function (d) { return d.value;});
Note: norm_1 is unique
Issues
Basically I'm noticing two issues:
I know for a fact that all my data will be between -1 and 1 (I've run several checks to test this), BUT when graphing it I see it dips down to -1.4 in some places.
My server sends exactly 1000 rows of data, but by breakpointing some of the dc.js code I can see it's only graphing 752 rows.
More Evidence
On my chart I've set the valueAccessor and added some checks to test the values going out of bounds, and I can see very clearly it goes out:
.valueAccessor(function (d) {
if (d.value > 1 || d.value < -1) {
console.log(d);
}
return d.value;
})
The data from the server requires a small amount formatting before going into crossfilter (it comes down as a table and needs to be split into series objects). I used this as an opportunity to test whether the data goes out of bounds, and I can see clearly it stays within bounds:
for (var i = 0; i < $scope.remoteData.rows.length; i++) {
for (var j = 0; j < $scope.remoteData.labels.length; j++) {
var label = $scope.remoteData.labels[j];
var value = $scope.remoteData.rows[i][label];
if (value > 1 || value < -1) {
console.log({
label: label,
i: i,
series: j,
norm_1: $scope.remoteData.rows[i].norm_1,
value: value,
});
}
rData.push({
series: j,
norm_1: $scope.remoteData.rows[i].norm_1,
value: value
})
}
}
Discussion
I suspect my problems have something to do with:
runGroup.reduceSum(function (d) { return d.value;});
Is this function adding together certain data points?
Sounds like you have some rows for which [+d.series, +d.norm_1] is not unique. And yes any rows with the same key will be added with reduceSum.
I'd suggest making your dimension key be something that's really unique.
If you don't have a unique key, with a little more work you could use the array indices themselves as the dimension key. It will mean you have to use both key and value accessors everywhere to look back in the original array.
Something like:
ndx = crossfilter(d3.range(0, rData.length));
runDimension = ndx.dimension(function(d) { return d; })
runGroup = runDimension.group().reduceSum(function(d) {
return rData[d].value;
})
chart.keyAccessor(function(kv) { return rData[kv.key].x; })
.valueAccessor(function(kv) { return rData[kv.key].y; })