Using react native async storage getItem - react-native

React.useEffect(_ => {
ReactNativeAsyncStorage.getItem("jwt")
|> Js.Promise.then_(jwt => {Js.log(jwt)});
None;
});
Error:
This expression has type unit but an expression was expected of type
Js.Promise.t('a) = Js.Promise.t('a)
I am using https://github.com/reason-react-native/async-storage with https://github.com/react-native-community/async-storage

The type of Js.Promise.then_ is
('a => t('b), t('a)) => t('b)
which means the function passed to it must return a, and that then_ itself will return that promise.
You're making two mistakes in your code:
You are not returning a promise from the function you pass to then_
You are not handling the promise returned by then_.
The following fixes both:
React.useEffect(_ => {
let _: Js.Promise.t(unit) =
Js.Prmoise.(
ReactNativeAsyncStorage.getItem("jwt")
|> then_(jwt => resolve(Js.log(jwt)))
);
None;
});
let _: Js.Promise.t(unit) = ... uses the wildcard pattern to discard the result of the following expression. The type of the result is Js.Result.t(unit), which is annotated to protect against accidental partial application.
resolve(Js.log(jwt)) will return a promise with the result of calling Js.log, which is unit, hence why the resulting promise has the type Js.Promise.t(unit).
See the Reason documentation for more on how to use promises.

Related

Filter within ErgoScript using Coll

I'd like to use the filter function in Coll. However I'm getting an error that says that there's something wrong with parsing:
Code:
val isNftInDataInputBox: Boolean =
dataInputBox.tokens
.filter(token => token._1 == outProfileBox.R5[Coll[Byte]].get)
.nonEmpty
Error:
Invalid declaration of lambda Ident(token,NoType) => Some(EQ(Select(Ident(token,NoType),_1,None),Select(ApplyTypes(Select(Ident(outProfileBox,NoType),R5,None),Vector(Coll[SByte$])),get,None)))
sigmastate.lang.syntax.ParserException:
line 61: .filter(token => token._1 == outProfileBox.R5[Coll[Byte]].get)
Is Filter allowed in ErgoScript?
Is this the correct documentation for Colls?
https://github.com/ScorexFoundation/sigmastate-interpreter/blob/fada073b82a16a928c457693b888da4c0310aca6/library/src/main/scala/special/collection/impl/CollsImpl.scala
I was able to filter it this way:
val filteredNFTToken: Coll[(Coll[Byte], Long)] = dataInputBox.tokens
.filter{
(token: (Coll[Byte], Long)) => token._1 == outProfileBox.R5[Coll[Byte]].get
}
val isNftInDataInputBox: Boolean = filteredNFTToken.size == 1
However, when I try
filteredNFTToken.NonEmpty
it fails with
Cannot find method 'nonEmpty' in in the object Ident(filteredNFTToken,NoType) of Product type with methods List(SMethod(sigmastate.SCollection$#25a5c8e,size,(Coll[IV]) => SInt$,1,FixedCost(14),MethodIRInfo(None,None,None),Some(OperationInfo(Some(SizeOf$(177)),The size of the collection in elements.,ArrayBuffer(ArgInfo(this,this instance)))),None), SMethod(sigmastate.SCollection$#25a5c8e,getOrElse,[IV](Coll[IV],SInt$,IV) => IV,2,FixedCost(30),MethodIRInfo(Some(<function1>),None,None),Some(OperationInfo(Some(ByIndex$(178)),Return the element of collection if \lst{index} is in range \lst{0 .. size-1},ArrayBuffer(ArgInfo(this,this instance), ArgInfo(index,index of the element of this collection), ArgInfo(default,value to return when \lst{index} is out of range)))),None), SMethod(sigmastate.SCollection$#25a5c8e,map,[IV,OV](Coll[IV],(IV) => OV) => Coll[OV],3,PerItemCost(20,1,10),MethodIRInfo(None,None,None),Some(OperationInfo(Some(MapCollection$(173)), Builds a new collection by applying a function to all elements of this collection.
Returns a new collection of type \lst{Coll[B]} resulting from applying the given function
\lst{f} to each element of this collection and collecting the results.
The documentation for available methods is 1.
The NonEmpty of nonEmpty methods are not available on Coll type.
Note, the names are case sensitive.
So, your solution is the right way to go.

How can I save part of a string in an alias using Cypress?

I'm trying to save just a number from a string I get from a paragraph but when I try to asign an alias to it and then check the value it returns undefined. I've tried a few solutions I found but none of those seem to work for me. These are two ways I tried (I tried another one similar to the second one but using split, had same result). The console.log inside of the 'then' doesn't show in the console, and when I try the alias after the code is when I get undefined.
cy.get('p')
.eq(1)
.should('have.text', '/[0-9]+/g')
.as('solNumber')
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number);
})
.as('solNumber')
Please convert with + operator and return the numeric value if you want numeric type to be stored.
cy.get('p').eq(1)
.invoke('text')
.then(fullText => {
const number = fullText.match(/[0-9]+/);
return +number // text to numeric
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', 42) // numeric type
});
Running your 2nd code on this,
<p>21</p>
<p>42</p>
gives the correct outcome
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number); // logs 42
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', '42') // passes
So, you need to inspect the DOM, it looks like it's not what you expect.
The first attempt you were passing a jquery element to the .should() and although some chainers change the subject yours did not so it saved the jquery element as solNumber.
The second attempt invokes the .text() which was passed to the .then() it logs the number correctly. However, you did not return anything at the end of the .then() block, therefore, solNumber should hold the entire paragraph.
This should help you out to extract the specific number and save it as an alias.
cy.get('p')
.invoke('text')
.invoke('trim')
.then(paragraph => {
const matcher = /some/
expect(paragraph).to.match(matcher) // check number is there
const indexOfText = paragraph.match(matcher) // get index of match text
return paragraph.substring(indexOfText.index, indexOfText.index + indexOfText[0].length) // return substring
})
.as('savedText')
cy.get('#savedText')
.then(cy.log) // will print out the number you seek

Summing a filtered column in DataTables

I'm trying to sum the results of filtered columns in DataTables. I've viewed the questions asked on their website and folks have had success using this method.
However, similar code for me produces 'Uncaught TypeError: undefined is not a function."
data = table._('td:nth-child(10)', {"filter": "applied"});
where 'table' is:
var table = $('#dataTable').DataTable({
// my initialization data
});
_ (the underscore function) seems to be deprecated in dataTables 1.10.x. In theory it should work with $('#dataTable').dataTable() (the old constructor) but this does not give the expected result (as least not for me).
But see this -> http://datatables.net/plug-ins/api/sum()
jQuery.fn.dataTable.Api.register( 'sum()', function () {
return this.flatten().reduce( function ( a, b ) {
return (a*1) + (b*1); // cast values in-case they are strings
});
});
var table = $("#example").DataTable();
$("#example").on('search.dt', function() {
console.log(table.column( 0, {page:'current'} ).data().sum() );
});
would give the same functionality in dataTables 1.10.x as you want in the question header.
see demo -> http://jsfiddle.net/6qLwkwud/
table.column( 0, {"filter": "applied"} ).data().sum() works perfectly well also.

Test contents of return array in PHPSpec

Say I have this method of a RuleFactory:
public function makeFromArray($rules)
{
$array = [];
foreach ($rules as $rule) {
$array[] = new Rule($rule[0], $rule[1]);
}
return $array;
}
I want to test that the return array contains Rule elements. Here is my test:
function it_should_create_multiple_rules_at_once()
{
$rules = [
['required', 'Please provide your first name'],
['alpha', 'Please provide a valid first name']
];
$this->makeFromArray($rules)->shouldHaveCount(2);
$this->makeFromArray($rules)[0]->shouldBeInstanceOf('Rule');
$this->makeFromArray($rules)[1]->shouldBeInstanceOf('Rule');
}
But this does not work, it throws an error in PHPSpec.
The strange thing is that I can do this just fine on other methods that return arrays, but for some reason I cannot do that here.
The error I get is this:
! it should create multiple rules at once
method [array:2] not found
How do I test the contents of this return array, WITHOUT creating my own inline matcher?
Your method accepts a single rule, not all of them. The spec should be:
$this->makeFromArray($rules)->shouldHaveCount(2);
$this->makeFromArray($rules[0])[0]->shouldBeAnInstanceOf('Rule');
$this->makeFromArray($rules[1])[1]->shouldBeAnInstanceOf('Rule');
Or, to avoid multiple calls:
$rules = $this->makeFromArray($rules);
$rules->shouldHaveCount(2);
$rules[0]->shouldBeAnInstanceOf('Rule');
$rules[1]->shouldBeAnInstanceOf('Rule');
Still, the most readable version would be the one leveraging a custom matcher:
$rules->shouldHaveCount(2);
$rules->shouldContainOnlyInstancesOf('Rule');

How do I use Rhino.Mocks.RhinoMocksExtensions.VoidType with lambda Expect?

I get the following error on this line:
session.Expect(s => s.Add("string", null)).IgnoreArguments().Return(SaveMockUser());
cannot convert from 'void' to 'Rhino.Mocks.RhinoMocksExtensions.VoidType'
SaveMockUser is defined as follows
private void SaveMockUser()
{
}
What am I doing wrong?
It's not possible to return a void type. Probably what you want to do is have another expectation that expects that SaveMockUser() is actually called or actually perform the action via a callback - i.e., when you see this function called, then do this.
session.Expect( s => s.Add("string", null) )
.IgnoreArguments()
.WhenCalled( x => SaveMockUser() );
or even better - use the new inline constraints
session.Expect( s => s.Add( Arg<string>.Is.Equal( "string" ), Arg<string>.Is.Anything ) )
.WhenCalled( x => SaveMockUser() );