How to GetTimesCalled with exact arguments? - typemock-isolator

I'm just familiarizing with Typemock Isolator, so sorry, if the question below is stupid.
Can i somehow get times of my function was called with exact arguments?
Like Isolate.Verify.GetTimesCalled() + Isolate.Verify.WasCalledWithExactArguments()

Typemock doesn't have a function for getting number of calls with exact arguments. However, you can solve this problem using DoInstead():
public class UnderTestClass
{
public void Foo(int n)
{
//Doesn't matter
}
}
[TestMethod, Isolated]
public void VerifyNumberOfCalls()
{
//Arrange
var underTest = new UnderTestClass();
int number = 0;
Isolate.WhenCalled((int n) => underTest.Foo(n)).AndArgumentsMatch(n => n <= 0).DoInstead(context =>
{
number++;
context.WillCallOriginal();
});
//Act
underTest.Foo(2);
underTest.Foo(1);
underTest.Foo(0);
underTest.Foo(-1);
underTest.Foo(-2);
//Assert
Assert.AreEqual(3, number);
}

Related

What is an async scope for a delegate in Vala?

I am trying the async examples from the GNOME project site. I get the follwoing warning which I don't under stand on how to fix.
async.vala:8.2-8.17: warning: delegates with scope="async" must be owned
Code
async double do_calc_in_bg(double val) throws ThreadError {
SourceFunc callback = do_calc_in_bg.callback;
double[] output = new double[1];
// Hold reference to closure to keep it from being freed whilst
// thread is active.
// WARNING HERE
ThreadFunc<bool> run = () => {
// Perform a dummy slow calculation.
// (Insert real-life time-consuming algorithm here.)
double result = 0;
for (int a = 0; a<100000000; a++)
result += val * a;
output[0] = result;
Idle.add((owned) callback);
return true;
};
new Thread<bool>("thread-example", run);
yield;
return output[0];
}
void main(string[] args) {
var loop = new MainLoop();
do_calc_in_bg.begin(0.001, (obj, res) => {
try {
double result = do_calc_in_bg.end(res);
stderr.printf(#"Result: $result\n");
} catch (ThreadError e) {
string msg = e.message;
stderr.printf(#"Thread error: $msg\n");
}
loop.quit();
});
loop.run();
}
The warning is pointing at the run variable inside the async function. Who or what needs to be owned? The reference to the closure?
The delegate needs to have a well defined owner all the time. The error message is a bit misleading.
To fix it you have to explicitly transfer the ownership from the delegate to the thread constructor:
new Thread<bool>("thread-example", (owned) run);
Instead of
new Thread<bool>("thread-example", run);
See also: https://wiki.gnome.org/Projects/Vala/Tutorial#Ownership
PS: The generated C code is fine in both cases. (at least with valac 0.46.6)

type 'Future<dynamic>' is not a subtype of type 'List<CloseObservations>'

I'm very new to dart and i am countering an issue with a function that suppose return a List<CloseObservations> and not a Future<dynamic> and i couldn't figure out why my function do not return the correct type.
This is my function :
getData(BuildContext context) async {
List<CloseObservations> closeObservationData = new List();
WorkSiteState state = BlocProvider.of<WorkSiteBloc>(context).state;
List<Stage> stages = state.workSites[state.currentIndex].stages;
for (Stage stage in stages) {
String stageName = stage.name;
int closeNumber;
try {
for (Plan plan in stage.plans) {
for (Observation observation in plan.observations) {
if (!observation.open) {
closeNumber++;
}
}
}
} finally {
closeObservationData.add(CloseObservations(stageName, closeNumber));
}
}
return closeObservationData;
}
I hope the explanation of my problem is clear, if not tell me.
Thank you for your help !
You should explicitly specify return type of your function:
Future<List<CloseObservations>> getData(BuildContext context) async {
...
Async functions always return Future (there's also FutureOr, but you shouldn't return it - that's bad practice). If you don't need it to return Future, make it synchronous by removing async keyword and changing return type to List.

Lucene number of occurrences

I am using Lucene.net in my Web App.
Everithing works fine, but now i have to show the number of occurrences of my 'searchstring' in every single document of the hits array.
How can i do this? I use usual BooleanQuery.
That is my search:
BooleanQuery bq = new BooleanQuery();
bq.Add(QueryParser.Parse(Lquery, "", CurIndexDescritor.GetLangAnalizer()), false,false);
BooleanQuery.SetMaxClauseCount(int.MaxValue);
IndexSearcher searcher = new IndexSearcher(indexPath);
Hits hits = (filter != null) ? searcher.Search(bq, filter) : searcher.Search(bq);
for (int i = 0; i < hits.Length(); i++)
{
Document doc = hits.Doc(i);
SearchResultItem MyDb = new SearchResultItem();
MyDb.key = doc.Get(KeyField);
MyDb.score = hits.Score(i);
result.Add(MyDb);
}
Where can i get the number of occurrences?
Thanks!
If you dont want the score back and dont want to order the results using score you could probably build a custom Similarity implementation.
I quickly tested the following code, and it appears to work fine with TermQueries and PhraseQueries, i didnt test more query types tho. A PhraseQuery hit counts as a single occurence.
public class OccurenceSimilarity : DefaultSimilarity
{
public override float Tf(float freq)
{
return freq;
}
public override float Idf(int docFreq, int numDocs)
{
return 1;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1;
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1;
}
public override Explanation.IDFExplanation idfExplain(System.Collections.ICollection terms, Searcher searcher)
{
return CACHED_IDF_EXPLAIN;
}
public override Explanation.IDFExplanation IdfExplain(Term term, Searcher searcher)
{
return CACHED_IDF_EXPLAIN;
}
public override float SloppyFreq(int distance)
{
return 1;
}
private static Explanation.IDFExplanation CACHED_IDF_EXPLAIN = new ExplainIt();
private class ExplainIt : Explanation.IDFExplanation
{
public override string Explain()
{
return "1";
}
public override float GetIdf()
{
return 1.0f;
}
}
}
To use it:
Similarity.SetDefault(new OccurenceSimilarity());

ActionScript ByteArray manipulation

I have some binary data and I can't store it in a string, as such I'm using a ByteArray.
The problem is that I need some functionality that comes with strings, to be specific I need the charAt, substr, indexOf and substring methods.
These would be fairly easy to implement. I can post the code if wanted. Is the data string-like? Or does it need to be treated as arbitrary binary? In either case, how wide are characters (e.g. 8-bit, 16-bit)?
public static function charAt(bytes:ByteArray, index:int):String {
if (bytes.length <= index) return null;
return String.fromCharCode(bytes[index]);
}
public static function substr(bytes:ByteArray, start:int, length:int=0):String {
var res:ByteArray = bytes.readBytes(bytes, start, length);
return res.toString();
}
public static function substring(bytes:ByteArray, start:int, end:int=0):String {
return substr(bytes, start, end-start);
}
public static function indexOf(bytes:ByteArray, str:String):int {
for (var i:int=0; i<bytes.length; i++) {
var strPos:int = 0;
while (String.fromCharCode(bytes[i+strPos]) == str.charAt(strPos)) {
strPos++;
if (strPos == str.length) return i;
}
}
return -1;
}

Flex: implementing classic curry function in actionscript?

What's the best way to implement a classic curry function in actionscript with a nice syntax?
I've tried:
Function.prototype.curry = function()
{
return "helloWorld";
}
trace((function():void {}).curry());
...approach but that didn't work.
I guess I'm stuck with a ugly approach such as:
FunctionUtils.curry(fp, ... args)
???
I must admit I've never understood the difference between "curry" and "partial". I use the following function to do more or less what you want to do:
package {
public function partial( func : Function, ...boundArgs ) : Function {
return function( ...dynamicArgs ) : * {
return func.apply(null, boundArgs.concat(dynamicArgs))
}
}
}
Usage examples:
var multiply : Function = function( a : Number, b : Number ) : Number { return a * b; }
var multiplyByFour : Function = partial(multiply, 4);
trace(multiplyByFour(3)); // => 12
Ended up with (heavily inspired by dojo's implementation):
public static function curry(func:Function, ... args:Array):*
{
var arity:int = func.length;
var currying:Function = function(func:Function, arity:int, args:Array):*
{
return function(... moreArgs:Array):* {
if(moreArgs.length + args.length < arity)
{
return currying(func, arity, args.concat(moreArgs));
}
return func.apply(this, args.concat(moreArgs));
}
}
return currying(func, arity, args);
}
Request in the comments section to show an example of how to use this:
function foo(i:int, j:int):void
{
trace(i+j);
}
function bar(fp:Function):void
{
fp(2);
}
bar(FunctionUtils.curry(foo, 1)); //trace==3
Silly example, I know, but curry:ing is extremely useful. Have a look at http://www.svendtofte.com/code/curried_javascript/ for theory.

Resources