`toBeInstanceOf(Number)` does not work in jest - jestjs

I have a test as follows:
expect(result.data.quota).toBeInstanceOf(Number);
This test fails with a weird error saying the a Number was expected and a Number was received:
expect(value).toBeInstanceOf(constructor)
Expected constructor: Number
Received constructor: Number
Received value: 2000

expect(value).not.toBeNaN();
Edit: I would go with #bszoms solution:
expect(typeof value).toBe('number')

The following works for all constructors:
expect(value).toEqual(expect.any(Number));

You can also do this: expect(typeof <value>).toBe('number')
Or you can use jest-extended, which adds a whole range of matchers including toBeNumber.
Both courtesy of the discussion here.

Taking #stephan's anwer, this works for async / promise based methods:
await expect(asyncFunction()).resolves.toEqual(expect.any(Number));

Related

Why isn't Jest applying my timeout when I use jest.setTimeout()? [duplicate]

This question already has answers here:
How can I increase the test time out value in jest?
(3 answers)
Closed 9 months ago.
I know I can use jest.setTimeout() to set a custom timeout for a test. I'm doing this below. MINUTE has the value 60 * 1000.
Why isn't Jest applying my timeout?
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
13 |
14 | describe(`integration with API provider`, () => {
> 15 | it(`works`, async () => {
| ^
16 | // Just in case network is slow.
17 | jest.setTimeout(1 * MINUTE);
As you've seen (and despite what's claimed elsewhere on SO), you cannot change a single test's timeout by calling jest.setTimeout from inside it. Note that the docs you quote state (emphasis mine):
This only affects the test file from which this function is called.
It's intended to be used at test discovery time, not execution time, to set the timeout for a given context. The timeout is set before the test callback is invoked, you can't change it once the test actually starts.
For a single test you can set the timeout by passing a third argument to the test/it function (or the various helpers defined on it), for example:
it("has a description", () => {
// ...
}, 60_000);

kdb/q: How to apply a string manipulation function to a vector of strings to output a vector of strings?

Thanks in advance for the help. I am new to kdb/q, coming from a Python and C++ background.
Just a simple syntax question: I have a string with fields and their corresponding values
pp_str: "field_1:abc field_2:xyz field_3:kdb"
I wrote an atomic (scalar) function to extract the value of a given field.
get_field_value: {[field; pp_str] pp_fields: " " vs pp_str; pid_field: pp_fields[where like[pp_fields; field,":*"]]; start_i: (pid_field[0] ss ":")[0] + 1; end_i: count pid_field[0]; indices: start_i + til (end_i - start_i); pid_field[0][indices]}
show get_field_value["field_1"; pp_str]
"abc"
show get_field_value["field_3"; pp_str]
"kdb"
Now how do I generalize this so that if I input a vector of fields, I get a vector of values? I want to input ("field_1"; "field_2"; "field_3") and output ("abc"; "xyz"; "kdb"). I tried multiple approaches (below) but I just don't understand kdb/q's syntax well enough to vectorize my function:
/ Attempt 1 - Fail
get_field_value[enlist ("field_1"; "field_2"); pp_str]
/ Attempt 2 - Fail
get_field_value[; pp_str] /. enlist ("field_1"; "field_3")
/ Attempt 3 - Fail
fields: ("field_1"; "field_2")
get_field_value[fields; pp_str]
To run your function for each you could project the pp_str variable and use each for the others
q)get_field_value[;pp_str]each("field_1";"field_3")
"abc"
"kdb"
Kdb actually has built-in functionality to handle this: https://code.kx.com/q/ref/file-text/#key-value-pairs
q){#[;x](!/)"S: "0:y}[`field_1;pp_str]
"abc"
q)
q){#[;x](!/)"S: "0:y}[`field_1`field_3;pp_str]
"abc"
"kdb"
I think this might be the syntax you're looking for.
q)get_field_value[; pp_str]each("field_1";"field_2")
"abc"
"xyz"

How to add two maps of key to values(array) together in Presto?

I have this presto query that gives me this.
but what I am looking for is this.
{"accountnumber":"A00000065","invoice":{"ids":["2c92c09a693316310169384472126a0d"], "numbers":["INV00000270"]}}
I have tried using the map_concat to no luck.
[![enter image description here][2]][2]
https://prestodb.io/docs/current/functions/map.html
[2]: https://i.stack.imgur.com/pq5iu.png
UPDATE: If I do the following it works.
map_concat(multimap_agg('number', invoice.invoicenumber), multimap_agg('id', invoice.id))
but if I change to
map_concat(multimap_agg('number', invoice.invoicenumber), multimap_agg('id', invoice.balance))
I get this error
line 1:23: Unexpected parameters (map(varchar(6),array(varchar)), map(varchar(2),array(decimal(18,6)))) for function map_concat. Expected: map_concat(map(K,V)) K, V
It should go in a comment, but that's too long.
If it doesn't work, I'll delete the answer.
try this:
SELECT map_concat(multimap_agg('ids', invoice.id), multimap_agg('numbers', invoice.invoicenumber))
FROM ...

AutoHotKey: read of two underscore keys

One part of my AutoHotKey script should recognize if __ is typed.
Following the AutoHotKey documentation, I've tried:
~__::
tooltip,hi world
return
and got this error:
Line Text: ~__::
Error: Invalid hotkey.
this shows no errors, but works only for one underscore:
~_::
tooltip,hi world
return
this shows no errors, but it just clears the __:
:*:__::
tooltip,hi world
return
this shows error Error: Invalid hotkey.:
~:*:__::
tooltip,hi world
return
this shows no errors, but does nothing (Doku: Executehotstring) :
:X:~__::
tooltip,hi world
return
Here are 4 potential solutions. I have left one working, comment out/uncomment hotkey labels by adding/removing leading semicolons as appropriate.
The 2 blocks of code are functionally equivalent, and for the 2 alternatives, within each block, b0 prevents automatic backspacing, i.e. the underscores that you typed are not deleted.
;:*?:__:: ;deletes the underscores
:b0*?:__:: ;does not delete the underscores
SoundBeep
return
;note: the X option requires AHK v1.1.28+
;:X*?:__::SoundBeep ;deletes the underscores
;:Xb0*?:__::SoundBeep ;does not delete the underscores
This AutoHotKey recognize if __ is typed:
countUnderscore :=0
~_::
countUnderscore++
if(countUnderscore == 2){
tooltip, %countUnderscore% = countUnderscore
countUnderscore := 0
}
return

Pytorch, Unable to get repr for <class 'torch.Tensor'>

I'm implementing some RL in PyTorch and had to write my own mse_loss function (which I found on Stackoverflow ;) ).
The loss function is:
def mse_loss(input_, target_):
return torch.sum(
(input_ - target_) * (input_ - target_)) / input_.data.nelement()
Now, in my training loop, the first input is something like:
tensor([-1.7610e+10]), tensor([-6.5097e+10])
With this input I'll get the error:
Unable to get repr for <class 'torch.Tensor'>
Computing a = (input_ - target_) works fine, while b = a * a respectively b = torch.pow(a, 2) will fail with the error metioned above.
Does anyone know a fix for this?
Thanks a lot!
Update:
I just tried using torch.nn.functional.mse_loss which will result in the same error..
I had the same error,when I use the below code
criterion = torch.nn.CrossEntropyLoss().cuda()
output=output.cuda()
target=target.cuda()
loss=criterion(output, target)
but I finally found my wrong:output is like tensor([[0.5746,0.4254]]) and target is like tensor([2]),the number 2 is out of indice of output
when I not use GPU,this error message is:
RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed. at /opt/conda/conda-bld/pytorch-nightly_1547458468907/work/aten/src/THNN/generic/ClassNLLCriterion.c:93
Are you using a GPU ?
I had simillar problem (but I was using gather operations), and when I moved my tensors to CPU I could get a proper error message. I fixed the error, switched back to GPU and it was alright.
Maybe pytorch has trouble outputing the correct error when it comes from inside the GPU.

Resources