RethinkDB branch / do + "Argument 1 to deleteAt may not be `undefined`." - rethinkdb

I am trying to write some somewhat complicated ReQL that deletes a single value from an array in a field, or deletes the record entirely if that value is the only one in the array.
I thought I had worked it out using branch/do/offsetAt, but then I ran into this "Argument 1 to deleteAt may not be undefined." error and I'm at a loss as to what the fix is.
r.branch(
r.db('db').table('table').get('uuid').eq(null),
{"deleted": 0, "errors": 0, "inserted": 0, "replaced": 0, "skipped": 0, "unchanged": 1},
r.db('db').table('table').get('uuid').getField('array_field').eq(['value']),
r.db('db').table('table').get('uuid').delete(),
r.do(
r.db('db').table('table').get('uuid').getField('array_field').offsetsOf('value'),
function(index) {
return r.branch(
index.eq([]),
{"deleted": 0, "errors": 0, "inserted": 0, "replaced": 0, "skipped": 0, "unchanged": 1},
r.db('db').table('table').get('uuid').update({
"array_field": r.row('array_field').deleteAt(index[0])
})
)
}
)
)
Also, as a side question, is there a more efficient way to do this without constantly fetching the record over and over calling .get()

So it turns out the issue here was in thinking I could use [] on the index.
Switching to .deleteAt(index.nth(0)) at line 16 solved the problem, or at least changed the error to "Cannot use r.row in nested queries"
So I rewrote the code to also solve my secondary issue, of constantly fetching the data using .get()
My new code is now
r.do(
r.db('db').table('table').get('uuid'),
function(record) {
return r.branch(
record.eq(null),
{"deleted": 0, "errors": 0, "inserted": 0, "replaced": 0, "skipped": 0, "unchanged": 1, "result": "no record"},
record.getField('array_field').eq(['array_value']),
r.db('db').table('table').get('uuid').delete(),
r.do(
record.getField('array_field').offsetsOf('array_value'),
function(index) {
return r.branch(
index.eq([ ]),
{"deleted": 0, "errors": 0, "inserted": 0, "replaced": 0, "skipped": 0, "unchanged": 1, "result": "no index"},
r.db('db').table('table').get('uuid').update({
"array_field": record.getField('array_field').deleteAt(index.nth(0))
})
)
}
)
)
}
)

Related

How to iterate in a Rust element non-iterable?

I'm trying to iterate trough the results of this variable created from an API with a for loop (here commented or it will give an error):
let create_account_instruction: Instruction = solana_sdk::system_instruction::create_account(
&wallet_pubkey,
&mint_account_pubkey,
minimum_balance_for_rent_exemption,
Mint::LEN as u64,
&spl_token::id(),
);
println!("Creating the following instructions: {:?}", create_account_instruction);
// for x in create_account_instruction {
// println!("{:?}", x)
// }
Here is the results I would like to iterate trough (FYI: Those private and public keys are just for test on devnet):
Creating the following instructions: Instruction { program_id: 11111111111111111111111111111111, accounts: [AccountMeta { pubkey: ESCkgk5AfDC8cXd4KYjkUda1psCL8otfu8NvniUBiGhX, is_signer: true, is_writable: true }, AccountMeta { pubkey: Ah63GoKnnBicTELvfz2F9YvF9vaR51HR2BK3hJWwWE8x, is_signer: true, is_writable: true }], data: [0, 0, 0, 0, 96, 77, 22, 0, 0, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 6, 221, 246, 225, 215, 101, 161, 147, 217, 203, 225, 70, 206, 235, 121, 172, 28, 180, 133, 237, 95, 91, 55, 145, 58, 140, 245, 133, 126, 255, 0, 169] }
If I try to iterate trough it via for loop (uncommenting the above), I get this error:
Compiling AmatoRaptor v0.1.0 (/home/joomjoo/Desktop/Tester)
error[E0277]: `Instruction` is not an iterator
--> src/main.rs:89:14
|
89 | for x in create_account_instruction {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ `Instruction` is not an iterator
|
= help: the trait `Iterator` is not implemented for `Instruction`
= note: required because of the requirements on the impl of `IntoIterator` for `Instruction`
note: required by `into_iter`
--> /home/joomjoo/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:234:5
|
234 | fn into_iter(self) -> Self::IntoIter;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
For more information about this error, try `rustc --explain
My question is what is the easiest way to iterate trough the results?
From the Solana documentation, Instruction is a struct:
pub struct Instruction {
pub program_id: Pubkey,
pub accounts: Vec<AccountMeta, Global>,
pub data: Vec<u8, Global>,
}
You can access its attributes, and iterate over them:
for x in create_account_instruction.data {
...
}
or
for x in create_account_instruction.accounts {
...
}

Jsplumb - Connectors

Am trying to draw a flowchart. I create divs dynamically and have set a unique 'id' property for each div and connect them using Jsplumb connectors.
I get the source and destination id from database(note that 'id' property for div dynamically created is its ID from database) and store in 'connectors' json. Its format is
Eg:
{[from:A,to:B], [from:A,to:C], [from:B,to:C]}
angular.forEach(connectors, function (connect) {
$scope.connection(connect.from, connect.to);
})
The jsplumb code is as follows
$scope.connection = function (s, t) {
var stateMachineConnector1 = {
connector: ["Flowchart", { stub: 25, midpoint: 0.001 }],
maxConnections: -1,
paintStyle: { lineWidth: 3, stroke: "#421111" },
endpoint: "Blank",
anchor: "Continuous",
anchors: [strt, end],
overlays: [["PlainArrow", { location: 1, width: 15, length: 12 }]]
};
var firstInstance = jsPlumb.getInstance();
firstInstance.connect({ source: s.toString(), target: t.toString() }, stateMachineConnector1);
}
THE PROBLEM:
What i have now is
Here the connector B to C overlaps existing A to C connector.
What i need is to separate the two connections like below
I could not find a solution for this anywhere. Any help? Thanks!
Using anchor perimeter calculates the appropriate position for endpoints.
jsfiddle demo for perimeter
jsPlumb.connect({
source:$('#item1'),
target:$("#item2"),
endpoint:"Dot",
connector: ["Flowchart", { stub: 25, midpoint: 0.001 }],
anchors:[
[ "Perimeter", { shape:"Square" } ],
[ "Perimeter", { shape:"Square" } ]
]
});
Jsplumb anchors
What I suggest you to do, to exactly replicate your schema, would be to set 2 endpoints on on box on A, B and C
A Endpoints should be [0.25, 1, 0, 0, 0, 0] and [0.75, 1, 0, 0, 0, 0]
B and C Endpoints should be [0.25, 0, 0, 0, 0, 0] and [0.75, 0, 0, 0, 0, 0]
It basically works like this (I might be wrong for the 4 last one its been a while but you only need to worry about the x and y)
[x,y,offsetx, offsety, angle, angle]
For the x 0 is the extreme left and 1 extreme right
Same goes for y (0 is top and 1 is bottom).
Take care

Ctrl-S input event in Windows console with ReadConsoleInputW

I am using ReadConsoleInputW to read Windows 10 console input. I want to be able to detect when Ctrl+S is pressed. Using the code I have, I can detect Ctrl+Q without issue, but I'm not seeing anything for Ctrl+S. Is Ctrl+S even detectable?
The below is the sequence of INPUT_RECORD I read when pressing Ctrl+S a few times, followed by Ctrl+Q.
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 }
Key { key_down: true, repeat_count: 1, key_code: 81, scan_code: 16, wide_char: 17, control_key_state: 40 }
If it matters, this is in Rust using wio.
Calling SetConsoleMode with ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS as the second argument (thus disabling ENABLE_PROCESSED_INPUT) did the trick.
oconnor0's answer helped me find the solution.
However, I could not get ctrl-s event by disabling ENABLE_PROCESSED_INPUT, so I tried using only ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS as suggested by oconnor0. This worked, but this means ENABLE_PROCESSED_INPUT is not the culrpit!
So I tried:
//This didn't work
if (!GetConsoleMode(hConsoleInput, &lpMode)) Error();
lpMode &= ~(ENABLE_PROCESSED_INPUT);
if (!SetConsoleMode(hConsoleInput, lpMode)) Error();
//This worked
if (!GetConsoleMode(hConsoleInput, &lpMode)) Error();
lpMode &= ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
if (!SetConsoleMode(hConsoleInput, lpMode)) Error();
Disabling ENABLE_ECHO_INPUT forces you to disable ENABLE_ECHO_INPUT (see msdn), but it isn't the culprit because:
//This didn't work either
if (!GetConsoleMode(hConsoleInput, &lpMode)) Error();
lpMode &= ~(ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT);
if (!SetConsoleMode(hConsoleInput, lpMode)) Error();
So this means that ENABLE_LINE_INPUT is the culprit!
It's not clear why though:
ENABLE_LINE_INPUT 0x0002 The ReadFile or ReadConsole function returns
only when a carriage return character is read. If this mode is
disabled, the functions return when one or more characters are
available.

AnimationHandler has changed for threejs, how can I get it working?

I created a webgl animation using the threejs library, some time ago, today I have been trying to get it to run on the latest version of the three.js library.
In the latest library, there is no pathcontrols.js.
I copied pathcontrols.js from my old library to the new version, but this has not solved the problem,
Below is the full function that does not work properly, but it is the .add() and the animation() calls where I think the problem is:
function initAnimationPath( parent, spline, name, duration ) {
var animationData = {
name: name,
fps: 0.6,
length: duration,
hierarchy: []
};
var i,
parentAnimation, childAnimation,
path = spline.getControlPointsArray(),
sl = spline.getLength(),
pl = path.length,
t = 0,
first = 0,
last = pl - 1;
parentAnimation = { parent: -1, keys: [] };
parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
for ( i = 1; i < pl - 1; i++ ) {
t = duration * sl.chunks[ i ] / sl.total;
parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
}
animationData.hierarchy[ 0 ] = parentAnimation;
THREE.AnimationHandler.add( animationData );
return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
};
it seems that the deprecation of animationhandler.add() seems to be the issue, but I am having difficulty working out how to replace it.
(amongst many other things) I tried replacing animationhandler line and animation line with this:
THREE.AnimationHandler.update(delta);
return new THREE.Animation( camera, animationData);
No joy. I would like to know how to get the animation started??
Thanks

Complex d3.nest() manipulation

I have an array of arrays that looks like this:
var arrays = [[1,2,3,4,5],
[1,2,6,4,5],
[1,3,6,4,5],
[1,2,3,6,5],
[1,7,5],
[1,7,3,5]]
I want to use d3.nest() or even just standard javascript to convert this data into a nested data structure that I can use with d3.partition.
Specifically, I want to create this flare.json data format.
The levels of the json object I want to create with d3.nest() correspond to the index positions in the array. Notice that 1 is in the first position in all the subarrays in the example data above; therefore, it is at root of the tree. At the next positions in the arrays there are three values, 2, 3, and 7, therefore, the root value 1 has 3 children. At this point the tree looks like this:
1
/ | \
2 3 7
At the third position in the subarrays there are four values, 3, 5, and 6. These children would be places into the tree as follows:
1
____|___
/ | \
2 3 7
/ \ / / \
3 6 6 3 5
How can I produce this data structure using d3.nest()? The full data structure with the example data I showed above should look like this:
{"label": 1,
"children": [
{"label": 2, "children": [
{"label": 3, "children": [
{"label": 4, "children": [
{"label": 5}
]},
{"label": 6, "children": [
{"label": 5}
]}
]},
{"label": 6, "children": [
{"label": 4, "children": [
{"label": 5}
]}
]},
{"label": 3, "children": [
{"label": 6, "children": [
{"label": 4, "children": [
{"label": 5}
]}
]}
]},
{"label": 7, "children": [
{"label": 3, "children": [
{"label": 5}
]},
{"label": 5}
]}
]}
]}
I'm trying to convert my array data structure above using something like this (very wrong):
var data = d3.nest()
.key(function(d, i) { return d.i; })
.rollup(function(d) { return d.length; })
I've been banging my head for a week to try and understand how I can produce this hierarchical data structure from an array of arrays. I'd be very grateful if someone could help me out.
#meetamit's answer in the comments is good, but in my case my tree is too deep to repeatedly apply .keys() to the data, so I cannot manually write a function like this.
Here's a more straightforward function that just uses nested for-loops to cycle through all the path instructions in each of your set of arrays.
To make it easier to find the child element with a given label, I have implemented children as a data object/associative array instead of a numbered array. If you want to be really robust, you could use a d3.map for the reasons described at that link, but if your labels are actually integers than that's not going to be a problem. Either way, it just means that when you need to access the children as an array (e.g., for the d3 layout functions), you have to specify a function to make an array out of the values of the object -- the d3.values(object) utility function does it for you.
The key code:
var root={},
path, node, next, i,j, N, M;
for (i = 0, N=arrays.length; i<N; i++){
//for each path in the data array
path = arrays[i];
node = root; //start the path from the root
for (j=0,M=path.length; j<M; j++){
//follow the path through the tree
//creating new nodes as necessary
if (!node.children){
//undefined, so create it:
node.children = {};
//children is defined as an object
//(not array) to allow named keys
}
next = node.children[path[j]];
//find the child node whose key matches
//the label of this step in the path
if (!next) {
//undefined, so create
next = node.children[path[j]] =
{label:path[j]};
}
node = next;
// step down the tree before analyzing the
// next step in the path.
}
}
Implemented with your sample data array and a basic cluster dendogram charting method:
http://fiddle.jshell.net/KWc73/
Edited to add:
As mentioned in the comments, to get the output looking exactly as requested:
Access the data's root object from the default root object's children array.
Use a recursive function to cycle through the tree, replacing the children objects with children arrays.
Like this:
root = d3.values(root.children)[0];
//this is the root from the original data,
//assuming all paths start from one root, like in the example data
//recurse through the tree, turning the child
//objects into arrays
function childrenToArray(n){
if (n.children) {
//this node has children
n.children = d3.values(n.children);
//convert to array
n.children.forEach(childrenToArray);
//recurse down tree
}
}
childrenToArray(root);
Updated fiddle:
http://fiddle.jshell.net/KWc73/1/
If you extend the specification of Array, it's not actually that complex. The basic idea is to build up the tree level by level, taking each array element at a time and comparing to the previous one. This is the code (minus extensions):
function process(prevs, i) {
var vals = arrays.filter(function(d) { return prevs === null || d.slice(0, i).compare(prevs); })
.map(function(d) { return d[i]; }).getUnique();
return vals.map(function(d) {
var ret = { label: d }
if(i < arrays.map(function(d) { return d.length; }).max() - 1) {
tmp = process(prevs === null ? [d] : prevs.concat([d]), i+1);
if(tmp.filter(function(d) { return d.label != undefined; }).length > 0)
ret.children = tmp;
}
return ret;
});
}
No guarantees that it won't break for edge cases, but it seems to work fine with your data.
Complete jsfiddle here.
Some more detailed explanations:
First, we get the arrays that are relevant for the current path. This is done by filtering out those that are not the same as prevs, which is our current (partial) path. At the start, prevs is null and nothing is filtered.
For these arrays, we get the values that corresponds to the current level in the tree (the ith element). Duplicates are filtered. This is done by the .map() and .getUnique().
For each of the values we got this way, there will be a return value. So we iterate over them (vals.map()). For each, we set the label attribute. The rest of the code determines whether there are children and gets them through a recursive call. To do this, we first check whether there are elements left in the arrays, i.e. if we are at the deepest level of the tree. If so, we make the recursive call, passing in the new prev that includes the element we are currently processing and the next level (i+1). Finally, we check the result of this recursive call for empty elements -- if there are only empty children, we don't save them. This is necessary because not all of the arrays (i.e. not all of the paths) have the same length.
Since d3-collection has been deprecated in favor of d3.array, we can use d3.groups to achieve what used to work with d3.nest:
var input = [
[1, 2, 3, 4, 5],
[1, 2, 6, 4, 5],
[1, 3, 6, 4, 5],
[1, 2, 3, 6, 5],
[1, 7, 5],
[1, 7, 3, 5]
];
function process(arrays, depth) {
return d3.groups(arrays, d => d[depth]).map(x => {
if (
x[1].length > 1 || // if there is more than 1 child
(x[1].length == 1 && x[1][0][depth+1]) // if there is 1 child and the future depth is inferior to the child's length
)
return ({
"label": x[0],
"children": process(x[1], depth+1)
});
return ({ "label": x[0] }); // if there is no child
});
};
console.log(process(input, 0));
<script src="https://d3js.org/d3-array.v2.min.js"></script>
This:
Works as a recursion on the arrays' depths.
Each recursion step groups (d3.groups) its arrays on the array element whose index is equal to the depth.
Depending on whether there are children or not, the recursion stops.
Here is the intermediate result produced by d3.groups within a recursion step (grouping arrays on there 3rd element):
var input = [
[1, 2, 3, 4, 5],
[1, 2, 6, 4, 5],
[1, 2, 3, 6, 5]
];
console.log(d3.groups(input, d => d[2]));
<script src="https://d3js.org/d3-array.v2.min.js"></script>
Edit - fixed
Here is my solution
Pro:It is all in one go (doesn't need objects converting to arrays like above)
Pro:It keeps the size/value count
Pro:the output is EXACTLY the same as a d3 flare with children
Con:it is uglier, and likely less efficient
Big Thanks to previous comments for helping me work it out.
var data = [[1,2,3,4,5],
[1,2,6,4,5],
[1,3,6,4,5],
[1,2,3,6,5],
[1,7,5],
[1,7,3,5]]
var root = {"name":"flare", "children":[]} // the output
var node // pointer thingy
var row
// loop through array
for(var i=0;i<data.length;i++){
row = data[i];
node = root;
// loop through each field
for(var j=0;j<row.length;j++){
// set undefined to "null"
if (typeof row[j] !== 'undefined' && row[j] !== null) {
attribute = row[j]
}else{
attribute = "null"
}
// using underscore.js, does this field exist
if(_.where(node.children, {name:attribute}) == false ){
if(j < row.length -1){
// this is not the deepest field, so create a child with children
var oobj = {"name":attribute, "children":[] }
node.children.push(oobj)
node = node.children[node.children.length-1]
}else{
// this is the deepest we go, so set a starting size/value of 1
node.children.push({"name":attribute, "size":1 })
}
}else{
// the fields exists, but we need to find where
found = false
pos = 0
for(var k=0;k< node.children.length ;k++){
if(node.children[k]['name'] == attribute){
pos = k
found = true
break
}
}
if(!node.children[pos]['children']){
// if no key called children then we are at the deepest layer, increment
node.children[pos]['size'] = parseInt(node.children[pos]['size']) + 1
}else{
// we are not at the deepest, so move the pointer "node" and allow code to continue
node = node.children[pos]
}
}
}
}
// object here
console.log(root)
// stringified version to page
document.getElementById('output').innerHTML = JSON.stringify(root, null, 1);
Working examples
https://jsfiddle.net/7qaz062u/
Output
{ "name": "flare", "children": [ { "name": 1, "children": [ { "name": 2, "children": [ { "name": 3, "children": [ { "name": 4, "children": [ { "name": 5, "size": 1 } ] } ] }, { "name": 6, "children": [ { "name": 4, "children": [ { "name": 5, "size": 1 } ] } ] } ] }, { "name": 3, "children": [ { "name": 6, "children": [ { "name": 4, "children": [ { "name": 5, "size": 1 } ] } ] }, { "name": 3, "children": [ { "name": 6, "children": [ { "name": 5, "size": 1 } ] } ] } ] }, { "name": 7, "children": [ { "name": 5, "size": 1 }, { "name": 3, "children": [ { "name": 5, "size": 1 } ] } ] } ] } ] }

Resources