Specify Variable Initialization Order in Scala - scala

I have a special class Model that needs to have its methods called in a very specific order.
I tried doing something like this:
val model = new Model
new MyWrappingClass {
val first = model.firstMethod()
val second = model.secondMethod()
val third = model.thirdMethod()
}
The methods should be called in the order listed, however I am seeing an apparently random order.
Is there any way to get the variable initialization methods to be called in a particular order?

I doubt your methods are called in the wrong order. But to be sure, you can try something like this:
val (first, second, third) = (
model.firstMethod(),
model.secondMethod(),
model.thirdMethod()
)
You likely have some other problem with your code.

I can run 100 million loops where it never gets the order wrong, as follows:
class Model {
var done = Array(false,false,false);
def firstMethod():Boolean = { done(0) = true; done(1) || done(2) };
def secondMethod():Boolean = { done(1) = true; !done(0) || done(2) };
def thirdMethod():Boolean = { done(2) = true; !done(0) || !done(1) };
};
Notice that these methods return a True if done out of order and false when called in order.
Here's your class:
class MyWrappingClass {
val model = new Model;
val first = model.firstMethod()
val second = model.secondMethod()
val third = model.thirdMethod()
};
Our function to check for bad behavior on each trial:
def isNaughty(w: MyWrappingClass):Boolean = { w.first || w.second || w.third };
A short program to test:
var i = 0
var b = false;
while( (i<100000000) && !b ){
b = isNaughty(new MyWrappingClass);
i += 1;
}
if (b){
println("out-of-order behavior occurred");
println(i);
} else {
println("looks good");
}
Scala 2.11.7 on OpenJDK8 / Ubuntu 15.04
Of course this doesn't prove it impossible to have wrong order, only that correct behavior seems highly repeatable in a fairly simple case.

Related

Mirth - iterate over insurance HL7 segments

working with an ADT message template in Mirth, having issues with the IN1 and IN2 segments, the IN2 specifically.
Here's a sample message that I'm working with, removed almost all the segments.
MSH|^~&|EPIC|AMB||99|20220403165344|RELEASEAUTO|ADT^A04|367476|T|2.5|||AL|NE
IN1|1|10500201|105^Test|BCBS NC BLUE CARE^Test1|PO BOX 35^^DURHAM^NC^27702^||
IN2|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||first iteration IN1-62||
IN1|1|10500201|106^Test|BCBS NC BLUE CARE^Test1|PO BOX 35^^DURHAM^NC^27702^||
IN2|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||second iteration IN1-62||
So far I've built the following to iterate over the IN1 segment:
//IN1 Segments
var IN1count=0;
for each (seg in msg.IN1) {
createSegment('IN1',output,IN1count);
output.IN1[IN1count]['IN1.2'] = seg['IN1.2'];
output.IN1[IN1count]['IN1.3'] = seg['IN1.3'];
output.IN1[IN1count]['IN1.4'] = seg['IN1.4'];
output.IN1[IN1count]['IN1.8'] = seg['IN1.8'];
output.IN1[IN1count]['IN1.9'] = seg['IN1.9'];
output.IN1[IN1count]['IN1.10'] = seg['IN1.10'];
output.IN1[IN1count]['IN1.12'] = seg['IN1.12'];
output.IN1[IN1count]['IN1.13'] = seg['IN1.13'];
output.IN1[IN1count]['IN1.22'] = seg['IN1.22'];
output.IN1[IN1count]['IN1.36'] = seg['IN1.36'];
IN1count++;
}
I'm struggling to map the IN2 segment correctly on the outbound, I've read about getSegmentsAfter but I can't find that function online... how do I write the correct JS code to look for whether the given IN1 has an IN2 after, specifically if it has IN2-61, and only then create the IN2 segment?
Hope that makes sense :)
You'll find code for createSegmentAfter here; it is JavaScript inserted before your transformer: https://github.com/nextgenhealthcare/connect/blob/2f3740db44c8d42aa6fafffd991b9c1fde940ea0/server/src/com/mirth/connect/server/builders/JavaScriptBuilder.java
One approach to keeping track of whether you just passed an IN1 would be to loop over all segments with something like this:
var was_in1 = false;
var last_in1;
for each ( seg in msg.children() ){
if (was_in1) {
if (seg.name() == "IN2") {
// existing IN2 follows IN1
} else {
// insert new IN2
}
if (seg.name() == "IN1") {
was_in1 = true;
last_in1 = seg;
} else {
was_in1 = false;
}
}
It'd be nice if there was a "nextSibling()" method for messages, but there isn't. Luckily, we can simulate it by:
Getting the current object's childIndex
Getting all children from the current object's parent
Access the next child with the index childIndex + 1
It'd look like this:
for each (seg in msg.IN1) {
// Do your IN1 stuff ...
var nextSeg = seg.parent().children()[ seg.childIndex() + 1];
if(nextSeg != null && nextSeg.name() == 'IN2' && nextSeg['IN2-61'].toString() != '') {
// Do yourIN2 stuff ...
}
}

draggable on ScalaJS removeEventListener does not work

based on that js demo: http://jsfiddle.net/wfbY8/737/
class Draggable(element: HTMLDivElement) {
var offX: Double = 0
var offY: Double = 0
val divMove = (e:MouseEvent) => {
//element.style.position = 'absolute';
element.style.top = (e.clientY-offY) + "px"
element.style.left = (e.clientX-offX) + "px"
}
val mouseDown = (e:MouseEvent) => {
offY = e.clientY - element.offsetTop
offX = e.clientX - element.offsetLeft
window.addEventListener("mousemove", divMove, useCapture = true)
println("added")
}
val mouseUp = (e:MouseEvent) => {
window.removeEventListener("mousemove", divMove, useCapture = true)
println("removed")
}
def addListeners(){
element.addEventListener("mousedown", mouseDown, useCapture = false)
window.addEventListener("mouseup", mouseUp, useCapture = false)
}
addListeners()
}
From the client code I use it like:
val panelElem = document.getElementById(COMPONENT_ID).asInstanceOf[HTMLDivElement]
if (draggable == null) {
draggable = new Draggable(panelElem)
}
I see "added" and "removed" on my log. But the element still movable (when I move mouse without pressing it) for me as if I did not removed mousemove event from the listener (on mouseUp).
I wonder why..
This happens because you're effectively converting the Scala function (the lambda) into a JS function separately for add and remove. In Scala.js, Scala functions are implicitly converted to JS functions as needed. However, the conversion yields a different JS function every time (it does not have the same identity). Therefore, the function you're trying to remove is not the same as the one you added, and of course that has no effect.
You can fix this by forcing the conversion to happen early, so that then you add and remove the same function. To do so, simply add an explicit type to your function vals as JS functions:
val divMove: js.Function1[MouseEvent, Unit] = (e:MouseEvent) => {
...
}
This way, the conversion from Scala function to JS function happens only once, and it is the same JS function that is given to add- and removeEventListener.

How can I reduce the redundancies of the fields handling of feed handler

I am subscript to a message feed for a number of fields, I need to set the values from the feed to the domain object and have code like below:
if (map.contains(quoteBidPriceAcronym)) {
quote.bid.price = Some(map.get(quoteBidPriceAcronym).get.asInstanceOf[Number].doubleValue());
quote.changed = true;
}
if (map.contains(quoteBidSizeAcronym)) {
quote.bid.size = Some(sizeMultipler() * map.get(quoteBidSizeAcronym).get.asInstanceOf[Number].intValue());
quote.changed = true;
}
if (map.contains(quoteBidNumAcronym)) {
quote.bid.num = Some(map.get(quoteBidNumAcronym).get.asInstanceOf[Number].shortValue());
quote.changed = true;
}
if (map.contains(quoteAskPriceAcronym)) {
quote.ask.price = Some(map.get(quoteAskPriceAcronym).get.asInstanceOf[Number].doubleValue());
quote.changed = true;
}
if (map.contains(quoteAskSizeAcronym)) {
quote.ask.size = Some(sizeMultipler() * map.get(quoteAskSizeAcronym).get.asInstanceOf[Number].intValue());
quote.changed = true;
}
if (map.contains(quoteAskNumAcronym)) {
quote.ask.num = Some(map.get(quoteAskNumAcronym).get.asInstanceOf[Number].shortValue());
quote.changed = true;
}
if (map.contains(quoteExchTimeAcronym)) {
quote.exchtime = getExchTime(String.valueOf(map.get(quoteExchTimeAcronym).get));
}
It look pretty redundant, any suggestion to improve it?
You can do something like:
map.get(quoteBidPriceAcronym).map { item =>
quote.bid.price = item.map(_.asInstanceOf[Number].doubleValue())
quote.changed = true
}
Other issues might be better to fix outside. E.g. why map[quoteBidPriceAcronym] is storing an Option, if your code assumes it's not going to be None?
Something like this perhaps?
val handlers = Map[String, Number => Unit] (
quoteBidPriceAcronym -> { n => quote.bid.price = Some(n.doubleValue) },
quoteBidSizeAcronym -> { n => quote.bid.size = Some(sizeMultipler() * n.intValue },
etc. ...
)
for {
(k,handler) <- handlers
values <- map.get(k).toSeq
quote.chanded = true
_ = handler(n.asInstanceof[Number])
}
Personally, I don't like code changing an object state (quote) but this is a question on Scala, not functional programming.
That said I would reverse the way you are using you map map keys. Instead of checking whether a value exists to perform some action, I'd have a map from your keys to actions and I'd iterate over your map elements.
e.g (assuming map is of the type Map[String, Any]):
val actions: Map[String, PartialFunction[Any, Unit]] = Map(
(quoteBidPriceAcronym, {case n: Number => quote.bid.price = Some(n.doubleValue())}),
(quoteBidSizeAcronym, {case n: Number => quote.bid.size = Some(sizeMultipler() * n.doubleValue())}),
...
...
)
for((k,v) <- map; action <- actions.get(k); _ <- action.lift(v))
quote.changed = true;
The for construct here iterates over map key-values, then (next level of iteration, over the possible action available for the key. If an action is found, which is a partial function, it gets lifted to make it a function from Any to Option[Unit]. That way, you can iterate in an additional inner level so quote.changed = true is only run when the action is defined for v.

Result not ready when used, works in debugger but not in runtime

In the following image you can see where i put the breakpoint and then debugged two step. You can also see that both assignments worked great they have the same count and are the same.
However if I do the following. Run the exact same call but only break on the third line directly then this happnes
set.QuestionSet.Questions should have count of 8 BEFORE the assigment, so it seems it's not properly assigned for some reason. I suspect this has something to do with how I fetch my data from DB.
Question and QuestionSet are normal POCOs and here is the code for the entire method.
public IEnumerable<QuestionSet> SearchAndFilterQuestionsAndSets(string searchString, int nrPerPage, int page, out int totalSearchCount)
{
searchString = searchString.ToLower();
List<QuestionSet> finalList = new List<QuestionSet>();
var result = ActiveContext.QuestionSets
.Select(x => new
{
QuestionSet = x,
Questions = x.Questions.Where(
y =>
y.Description.ToLower().Contains(searchString)
).OrderBy(
z => z.Description
)
})
.ToList();
foreach (var set in result)
{
//If our search matched the set itself we load all questions
if (set.QuestionSet.Name.ToLower().Contains(searchString))
{
//we dont bring empty sets
if (set.QuestionSet.Questions.Count() > 0)
{
set.QuestionSet.Questions = set.QuestionSet.Questions.ToList<Question>().OrderBy(x => x.Description).ToList<Question>();
finalList.Add(set.QuestionSet);
}
}
//We had one or more questions matching the search term
else if (set.Questions.Count() > 0)
{
var b = set.Questions.ToList<Question>();
set.QuestionSet.Questions = set.Questions.ToList<Question>();
finalList.Add(set.QuestionSet);
}
}
totalSearchCount = finalList.Count();
return finalList.Skip((page - 1) * nrPerPage).Take(nrPerPage);
}
UPDATE
If I do this instead in the failing else if
var a = new QuestionSet();
a.Id = set.QuestionSet.Id;
a.Name = set.QuestionSet.Name;
a.Questions = set.Questions.ToList<Question>();
finalList.Add(a);
Then it works, so the problem lies within the anonymous object, but why does it work when i step through with debugger and not otherwise?? call me puzzled.
Could be something to do with Late binding of anonymous types

Copy Groovy class properties

I want to copy object properties to another object in a generic way (if a property exists on target object, I copy it from the source object).
My code works fine using ExpandoMetaClass, but I don't like the solution. Are there any other ways to do this?
class User {
String name = 'Arturo'
String city = 'Madrid'
Integer age = 27
}
class AdminUser {
String name
String city
Integer age
}
def copyProperties(source, target) {
target.properties.each { key, value ->
if (source.metaClass.hasProperty(source, key) && key != 'class' && key != 'metaClass') {
target.setProperty(key, source.metaClass.getProperty(source, key))
}
}
}
def (user, adminUser) = [new User(), new AdminUser()]
assert adminUser.name == null
assert adminUser.city == null
assert adminUser.age == null
copyProperties(user, adminUser)
assert adminUser.name == 'Arturo'
assert adminUser.city == 'Madrid'
assert adminUser.age == 27
I think the best and clear way is to use InvokerHelper.setProperties method
Example:
import groovy.transform.ToString
import org.codehaus.groovy.runtime.InvokerHelper
#ToString
class User {
String name = 'Arturo'
String city = 'Madrid'
Integer age = 27
}
#ToString
class AdminUser {
String name
String city
Integer age
}
def user = new User()
def adminUser = new AdminUser()
println "before: $user $adminUser"
InvokerHelper.setProperties(adminUser, user.properties)
println "after : $user $adminUser"
Output:
before: User(Arturo, Madrid, 27) AdminUser(null, null, null)
after : User(Arturo, Madrid, 27) AdminUser(Arturo, Madrid, 27)
Note: If you want more readability you can use category
use(InvokerHelper) {
adminUser.setProperties(user.properties)
}
I think your solution is quite good and is in the right track. At least I find it quite understandable.
A more succint version of that solution could be...
def copyProperties(source, target) {
source.properties.each { key, value ->
if (target.hasProperty(key) && !(key in ['class', 'metaClass']))
target[key] = value
}
}
... but it's not fundamentally different. I'm iterating over the source properties so I can then use the values to assign to the target :). It may be less robust than your original solution though, as I think it would break if the target object defines a getAt(String) method.
If you want to get fancy, you might do something like this:
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.properties*.keySet()
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
Basically, it first computes the common properties between the two objects and then copies them. It also works, but I think the first one is more straightforward and easier to understand :)
Sometimes less is more.
Another way is to do:
def copyProperties( source, target ) {
[source,target]*.getClass().declaredFields*.grep { !it.synthetic }.name.with { a, b ->
a.intersect( b ).each {
target."$it" = source."$it"
}
}
}
Which gets the common properties (that are not synthetic fields), and then assigns them to the target
You could also (using this method) do something like:
def user = new User()
def propCopy( src, clazz ) {
[src.getClass(), clazz].declaredFields*.grep { !it.synthetic }.name.with { a, b ->
clazz.newInstance().with { tgt ->
a.intersect( b ).each {
tgt[ it ] = src[ it ]
}
tgt
}
}
}
def admin = propCopy( user, AdminUser )
assert admin.name == 'Arturo'
assert admin.city == 'Madrid'
assert admin.age == 27
So you pass the method an object to copy the properties from, and the class of the returned object. The method then creates a new instance of this class (assuming a no-args constructor), sets the properties and returns it.
Edit 2
Assuming these are Groovy classes, you can invoke the Map constructor and set all the common properties like so:
def propCopy( src, clazz ) {
[src.getClass(), clazz].declaredFields*.grep { !it.synthetic }.name.with { a, b ->
clazz.metaClass.invokeConstructor( a.intersect( b ).collectEntries { [ (it):src[ it ] ] } )
}
}
Spring BeanUtils.copyProperties will work even if source/target classes are different types. http://docs.spring.io/autorepo/docs/spring/3.2.3.RELEASE/javadoc-api/org/springframework/beans/BeanUtils.html