XPath: How to sort a map? - xpath

I'm using a map for counting the number occurrences of, for example, each possible value of the attr attribute of the elem nodes:
<root>
<elem attr="a"/>
<elem attr="b"/>
<elem attr="b"/>
<elem />
<elem attr="a"/>
<elem attr="c"/>
<elem attr="b"/>
</root>
fold-left(
//elem/#attr,
map{},
function($m,$a) {map:put($m, $a, sum((1, $m($a))))}
)
Resulting map:
{
"a": 2,
"b": 3,
"c": 1
}
Now, using this map, I would like to sort the integer values in descending order and emit their associated key. The expected "output" would be:
b
a
c
How can I do it?

I can't see why you would want a map for this. It's essentially a grouping-and-sorting problem, therefore much easier in XSLT or XQuery, but if it has to be pure XPath, you can use
let $in := .
return (distinct-values(//#attr)
=> sort((), function($a){-count($in//#attr[.=$a])}))

If you store the map in a variable then it's possible to call fn:sort on the keys while using the associated values as "sort keys":
let
$map := map{ "a": 2, "b": 3, "c": 1 }
return
$map => map:keys() => sort((), function($key) { -$map($key) })
b
a
c
ASIDE
You can also define a map:sort function for maps, which would return a sequence of keys:
function(
$map as map(*),
$collation as xs:string?,
$valuate as function(xs:anyAtomicType, item()*) as xs:anyAtomicType*
) as xs:anyAtomicType*
{
sort(
map:keys($map),
$collation,
function($key) { $valuate($key, $map($key)) }
)
}
let $map:sort := function (...) {...}
return
map{ "a": 2, "b": 3, "c": 1 }
=> $map:sort((), function($k,$v) { -$v })

Related

Configuring a pydantic model that leaves field values unchanged if it would have caused a ValidationError?

For example...suppose I have the code:
from pydantic import BaseModel
class User(BaseModel):
a: int
b: dict
c: str
User(**{"a": "2", "b": "gibberish", "c": "ok"}).dict() # should give {"a": 2, "b": "gibberish", "c": "ok"}
Is this achievable with Pydantic? I've tried defining custom validators (w/ all sorts of configurations...using pre=True, root validators w/ or w/out pre=True, etc) but nothing seems to work.
Use construct to create models without validation:
from pydantic import BaseModel
class User(BaseModel):
a: int
b: dict
c: str
user_dict = User.construct(**{"a": "2", "b": "gibberish", "c": "ok"}).dict()
print(user_dict) # {'a': '2', 'b': 'gibberish', 'c': 'ok'}
As per https://github.com/samuelcolvin/pydantic/discussions/4284, this is not easily configurable via Pydantic V1. The only option (according to the author themselves) is to define custom data types and call the validators directly and then catch the exception.

Is there a way to make assertions only on selected array elements?

Let's say I want to check if an array contains an element with a certain value of a field that fulfills a given assertion, for eg.:
{ array: [ { element1: Mario, element2: White }, { element1: Luigi, element2: Green } ] }
Here I want to check that the element of array which has element1 equal to Mario has element2 equal to White. How can I do so with chai/supertest (or other npm packages)?
You can do it with jsonpath module:
var jp = require('jsonpath');
expect(jp.query(json, '$..array[?(#.element1=="Mario")]')[0].element2).to.equal('White')

Is there an Array equality match function that ignores element position in jest.js?

I get that .toEqual() checks equality of all fields for plain objects:
expect(
{"key1":"pink wool","key2":"diorite"}
).toEqual(
{"key2":"diorite","key1":"pink wool"}
);
So this passes.
But the same is not true for arrays:
expect(["pink wool", "diorite"]).toEqual(["diorite", "pink wool"]);
There does not seem to be a matcher function that does this in the jest docs, i.e. that tests for the equality of two arrays irrespective of their elements positions. Do I have to test each element in one array against all the elements in the other and vice versa? Or is there another way?
There is no built-in method to compare arrays without comparing the order, but you can simply sort the arrays using .sort() before making a comparison:
expect(["ping wool", "diorite"].sort()).toEqual(["diorite", "pink wool"].sort());
You can check the example in this fiddle.
As already mentioned expect.arrayContaining checks if the actual array contains the expected array as a subset.
To check for equivalence one may
either assert that the length of both arrays is the same (but that wouldn't result in a helpful failure message)
or assert the reverse: That the expected array contains the actual array:
// This is TypeScript, but remove the types and you get JavaScript
const expectArrayEquivalence = <T>(actual: T[], expected: T[]) => {
expect(actual).toEqual(expect.arrayContaining(expected));
expect(expected).toEqual(expect.arrayContaining(actual));
};
This still has the problem that when the test fails in the first assertion one is only made aware of the elements missing from actual and not of the extra ones that are not in expected.
Put the elements into a set. Jest knows how to match these.
expect(new Set(["pink wool", "diorite"])).toEqual(new Set(["diorite", "pink wool"]));
this does not answer the question exactly, but still may help people that end up here by google search:
if you only care that a subset of the array has certain elements, use expect.arrayContaining() https://jestjs.io/docs/en/expect#expectarraycontainingarray
e.g.,
expect(["ping wool", "diorite"])
.toEqual(expect.arrayContaining(["diorite", "pink wool"]));
Another way is to use the custom matcher .toIncludeSameMembers() from jest-community/jest-extended.
Example given from the README
test('passes when arrays match in a different order', () => {
expect([1, 2, 3]).toIncludeSameMembers([3, 1, 2]);
expect([{ foo: 'bar' }, { baz: 'qux' }]).toIncludeSameMembers([{ baz: 'qux' }, { foo: 'bar' }]);
});
It might not make sense to import a library just for one matcher but they have a lot of other useful matchers I've find useful.
What about checking the content and the length?
expect(resultArray).toEqual(expect.arrayContaining(expectedArray));
expect(resultArray.length).toEqual(expectedArray.length);
If you want to compare two arrays in JEST use the bellow model.
Official link: https://jestjs.io/docs/en/expect#expectarraycontainingarray
const array1 = ['a', 'b', 'c'];
const array2 = ['a', 'b', 'c'];
const array3 = ['a', 'b'];
it("test two arrays, this will be true", () => {
expect(array1).toEqual(expect.arrayContaining(array2));
});
it("test two arrays, this will be false", () => {
expect(array3).toEqual(expect.arrayContaining(array1));
});
You can combine using sets as stated in this answer with checking length of actual result and expectation. This will ignore element position and protect you from duplicated elements in the same time.
const materials = ['pink wool', 'diorite'];
const expectedMaterials = ['diorite', 'pink wool'];
expect(new Set(materials)).toEqual(new Set(expectedMaterials));
expect(materials.length).toBe(expectedMaterials.length);
EDIT: As there is suggested in comment below, this will only work for arrays with unique values.
If you don't have array of objects, then you can simply use sort() function for sorting before comparison.(mentioned in accepted answer):
expect(["ping wool", "diorite"].sort()).toEqual(["diorite", "pink wool"].sort());
However, problem arises if you have array of objects in which case sort function won't work. In this case, you need to provide custom sorting function.
Example:
const x = [
{key: 'forecast', visible: true},
{key: 'pForecast', visible: false},
{key: 'effForecast', visible: true},
{key: 'effRegForecast', visible: true}
]
// In my use case, i wanted to sort by key
const sortByKey = (a, b) => {
if(a.key < b.key) return -1;
else if(a.key > b.key) return 1;
else return 0;
}
x.sort(sortByKey)
console.log(x)
Hope it helps someone someday.
Still a work in progress, but this should work albeit, the error messages may not be clear:
expect.extend({
arrayContainingExactly(receivedOriginal, expected) {
const received = [...receivedOriginal];
if (received.length !== expected.length) return {
message: () => `Expected array of length ${expected.length} but got an array of length ${received.length}`,
pass: false,
};
const pass = expected.every((expectedItem, index) => {
const receivedIndex = findIndex(received, receivedItem => {
if (expectedItem.asymmetricMatch) return expectedItem.asymmetricMatch(receivedItem);
return isEqual(expectedItem, receivedItem);
});
if (receivedIndex === -1) return false;
received.splice(receivedIndex, 1);
return true;
});
return {
message: () => 'Success',
pass,
}
}
});
Then use it like this:
expect(['foo', 'bar']).arrayContainingExactly(['foo']) // This should fail
or
expect({foo: ['foo', 'bar']}).toEqual({
foo: expect.arrayContainingExactly(['bar', 'foo'])
}) // This should pass
We are looping through each value and removing it from the received array so that we can take advantage of the asymmetric matching provided by Jest. If we just wanted to do direct equivalency this could be simplified to just compare the 2 sorted arrays.
Note: This solution uses findIndex and isEqual from lodash.
You can use jest toContainEqual to check if an array contains an element. Then just do that for each element in your expected array:
const actual = [{ foobar: 'C' }, { foo: 'A' }, { bar: 'B' }];
const expected = [{ foo: 'A' }, { bar: 'B' }, { foobar: 'C' }];
expect(actual).toContainEqual(expected[0]);
expect(actual).toContainEqual(expected[1]);
expect(actual).toContainEqual(expected[2]);
(Or put the expect statement in a loop if you have too many elements to check)

RethinkDB: Updating documents

This is a longshot, but I was wondering if in rethinkDB, let's say I update a document. Is there a magic function such that, if it is a field that is a string or int, it just updates it, but if the value of the field is an array, it appends it to the array?
In that case you'd need to use .branch and branch on the type. Something like .update(function(row) { return {field: r.branch(row('field').typeOf().eq('ARRAY'), row('field').add([el]), el)}; })
There is a magic function that does something similar. .forEach has the undocumented behaviour of adding numbers, combining arrays and drops strings:
>>> r.expr([{a:1, b:[2], c:"3"}, {a:2, b:[4], c:"6"}]).forEach(r.row)
{"a": 3, "b": [2,4], "c": "3"}

Iterate an array of hashes

I have a hash with a key of cities and the value is an array of hashes containing location data. It looks like this:
#locations = {
"cities"=>[
{"longitude"=>-77.2497049, "latitude"=>38.6581722, "country"=>"United States", "city"=>"Woodbridge, VA"},
{"longitude"=>-122.697236, "latitude"=>58.8050174, "country"=>"Canada", "city"=>"Fort Nelson, BC"},
...
]
}
I'd like to iterate through and print all the values for the key city:
Woodbridge, VA
Fort Nelson, BC
...
I can't say why would you have that structure, anyway, in the data format you have above, you would access it like
#locations[1].each { |c| p c["city"] }
Although, this implies that you should always expect second object in the array to be the required cities array. Further you need to put in required nil check.
For your corrected data format:
#locations = { "cities"=>[
{ "longitude"=>-77.2497049,
"latitude"=>38.6581722,
"country"=>"United States",
"city"=>"Woodbridge, VA"},
{ "longitude"=>-122.697236,
"latitude"=>58.8050174,
"country"=>"Canada",
"city"=>"Fort Nelson, BC" }] }
#locations["cities"].each { |h| puts h["city"] }
Woodbridge, VA
Fort Nelson, BC
or to save in an array:
#locations["cities"].each_with_object([]) { |h,a| a << h["city"] }
#=> ["Woodbridge, VA", "Fort Nelson, BC"]
As suggested by others, you have to do the exact same thing but let me explain whats happening in there.
Your example is an array and has multiple elements which could be just string like cities or an array of hashes like you mentioned.
So in order to iterate through the hashes and get the city values printed, you first of all have to access the array that has hashes. By doing so
#locations["cities"]
=> [{"longitude"=>-77.2497049, "latitude"=>38.6581722, "country"=>"United States", "city"=>"Woodbridge, VA"}, {"longitude"=>-122.697236, "latitude"=>58.8050174, "country"=>"Canada", "city"=>"Fort Nelson, BC"}]
Now that you have go the array you required, you can just integrate through them and get the result printed like this
#locations["cities"].map{|hash| p hash['city']}
In case your getting nil errors as you have stated in comments, just see what happens when you try to access the array of hashes. if you still are experiencing issues, then you may have to provide the full input so as to understand where the problem is.

Resources