Why do poked values change on last clock cycle in chiseltest, thus failing asserts? - chisel

I've tried adding some asserts to my code, but these asserts fail when testing my module,
even though I've poked the values accordingly. Interestingly, according to some prints, the value changes value in the last simulated cycle, as shown by this minimal example:
package stack_overflow_demo
import chisel3._
import chisel3.tester._
import org.scalatest.FreeSpec
import chisel3.experimental.BundleLiterals._
class AssertFail extends Module {
val io = IO(new Bundle {
val input = Input(UInt(2.W))
})
printf("%d\n", io.input) // prints 3 and then 0
assert(io.input === 3.U) // fails, apparently on the second cycle
}
class AssertTest extends FreeSpec with ChiselScalatestTester {
"break" in {
test(new AssertFail) { dut =>
dut.io.input.poke(3.U)
dut.clock.step()
}
}
}
I basically want to understand why that happens and also if I can keep these asserts active in my code or if I have to remove them alltogether.
(The actual code is part of an RISC-V decoder that can not manage the "C" compressed instruction-extension, so for simulation I tried to assert the lowest two bits to be 11)
Thank you!

I think the problem is that the chiseltest harness uses an implicit scope in your testing block, when the scope is finished it restores the input values to their state when it began. That is what is causing the problem. I think this is a bug, and shouldn't be too hard to fix. You should open and issue on the chiseltest repo. We'll try and get this fixed or provide a workaround

Related

Is it okay to create clicklisteners (or other listeners) inside a viewmodelscope?

I have a a fragment containing a googleMap where I am creating a bunch of Markers (which also is clickable). They are spiced with different information (colors, shapes and so on) from a room livedata query. In addition I have some MaterialButton buttons (which are styled as pushbuttons) where I toggle the Marker visible status on. At the moment, the "setup" of theese markers takes some time (200ms-2 secs, depends of amount of markers). To get out of that waiting, I was planning to use a viewmodelscope. Since there are some clicklisteners for theese buttons defined in there (they should do some action with the markers), will they still be alive when the viewmodelscope coroutine section ends, and If they are alive, do they still live in the correct coroutine-context, and do I need to do some housekeeping on the listeners when fragment and/or viewmodel ends?
I.E:
class MapsFragment:Fragment(){
private lateinit var mapsViewModel : MapsViewModel
private lateinit var googleMap : GoogleMap
//...
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mapsViewModel = ViewModelProvider(requireActivity()).get(MapsViewModel::class.java)
_binding = FragmentMapsBinding.inflate(inflater, container, false)
val root:View = binding.root
//...
return root
}//onCreateView
//...
override fun onViewCreated(view: View, savedInstanceState:Bundle?){
super.onViewCreated(view, savedInstanceState)
//...
mapFragment?.getMapAsync(_googleMap->
_googleMap?.let{safeGoogleMap->
googleMap = safeGoogleMap
}?:let{
Log.e(TAG,"googleMap is null!!")
return#getMapAsync
}
//...
mapsViewModel.apply{
liveDataMapsListFromFiltered?.observe(
viewLifecycleOwner
){mapDetailList->
viewModelScope.launch{
binding.apply{
//...
siteMarkers.map{
siteMarker.remove() //removes existing markes from map on update
}
siteMarkers.clear() //empty the siteMarker array on update
//...
mapDetailList?.map{
it.apply{
//...
coordinateSiteLongitude?.let { lng->
coordinateSiteLatitude?.let { lat->
siteMarkerLatLng = LatLng(lat,lng)
siteLatLngBoundsBuilder?.include(siteMarkerLatLng)
}
}
//...
siteMarkerLatLng?.let { safeSiteMarkerLatLng ->
val siteMarkerOptions =
MarkerOptions()
.position(safeSiteMarkerLatLng)
.anchor(0.5f, 0.5f)
.visible(siteMarkerState)
.flat(true)
.title(setTicketNumber(ticketNumber?.toDouble()))
.snippet(appointmentName)//TODO: Consider build siteId instead
.icon(siteIcon[iconType])
siteMarkers.add(
googleMap.addMarker(siteMarkerOptions) //Here are the markers added
)
}//siteMarkerLatLng?.let
}//it.apply
}//mapDetailList?.map
onSiteCheckedChangeListener?.let{
fragmentMapsMapTagSelector
?.apTagSelectorMaterialButtonSite
?.removeOnCheckedChangeListener(it) //clearing listener on button before update
}
onSiteCheckedChangeListener = MaterialButton.OnCheckedChangeListener { siteButton, isChecked ->
siteMarkers.map {
it.isVisible = isChecked
}
}.also {
fragmentMapsMapTagSelector
?.mapTagSelectorMaterialButtonSite
?.addOnCheckedChangeListener(it)
}
//Will this onCheckedChangeListener still survive when this viewmodelscope runs to the end ?
}//binding.apply
}//viewModelScope.launch
}//liveDataMapsListFromFiltered.observe
}//mapsviewModel.apply
}//getMapAsync
}//onViewCreated
}//MapsFragment
I think you misunderstand what a CoroutineScope is. It determines the lifecycle of coroutines that it runs, but not of the objects created in the process of running those coroutines.
viewModelScope is a CoroutineScope that automatically cancels any coroutines it is running when the associated ViewModel is torn down. The coroutine doesn't know what you're doing with it. Cancelling a coroutine merely stops it from running to completion, like returning from a function early. In your code, you set your listeners and haven't stored references to them besides in the views they are set to, so their lives are tied to their respective view's lives.
If you were going to use a coroutine in your fragment to set up something for your UI, you would use the Fragment's lifecycleScope, not the ViewModel's viewModelScope. Like if you were fetching something to show in your UI, you would want that coroutine to be cancelled when the Fragment is destroyed, not the ViewModel which might be outliving the Fragment.
Your use of a coroutine in your example code looks pointless, because I don't see any blocking or asynchronous suspend functions being called. You mentioned setting up site markers is taking like 200ms. I'm not familiar with Google Maps since I haven't used it in the past several years, so I'm not sure which part is time-consuming. Usually, UI elements do not allow you to interact with them on background threads, so you might be out of luck. But maybe the time-consuming part is allowed to be done on background threads. You'll have to read the documentation. Using a coroutine for this won't make it take less time, but can prevent the UI from stuttering/freezing.
If you were going to do some long computation with a coroutine, you would need to switch dispatchers to do the blocking work and interact with the UI elements back on the main dispatcher. Simply putting something in a coroutine doesn't make it take less time, but it provides a convenient way to do something on another thread and then continue on the main thread after the result is ready. For example:
lifecycleScope.launchWhenStarted { // lifecycle coroutines launch on main thread by default
val result = withContext(Dispatchers.Default) { // switch to dispatcher for background work
doTimeConsumingCalculation()
}
// back on main thread:
applyResultsToMyViews(result)
}
By using launchWhenStarted instead of launch, a Fragment's lifecycleScope will pause the coroutine when the Fragment is not attached, which will prevent potential crashes from trying to update UI using requireContext() or requireActivity() when there is no Activity.

How to choose which child class to instantiate dynamically

My current project is in as3, but this is something I am curious about for other languages as well.
I'm attempting to use a factory object to create the appropriate object dynamically. My LevelFactory has a static method that returns a new instance of the level number provided to the method. In the code calling that method, I am able to dynamically create the buttons to call the levels like so:
for (var i:int = 1; i < 4; i++) {
var tempbutton:Sprite = createButton("Level " + i, 25, 25 +(60 * i), start(i));
_buttons.push(button);
}
This code just creates a simple button with the given arguments (ButtonText, x, y, function). It's working fine. The buttons are created, and clicking on one of them calls this method with the appropriate argument
private function start(level:int):Function {
return function(e:MouseEvent):void {
disableButtons();
newLevel = LevelFactory.createLevel(level);
addChild(newLevel);
}
}
This is all working fine; I'm just providing it for background context. The question I have is this: Is it possible to dynamically choose the type of object that my static function returns? Currently, I have am doing it as follows
public static function createLevel(level:int):Level {
var result:Level;
switch(level) {
case 1: result = new Level1(); break;
case 2: result = new Level2(); break;
//etc
}
return result;
}
I should note that all of these Level1, Level2, etc. classes extend my base level class. (Yay polymorphism!) What I would like to do is be able to do something along the lines of
public static function createLevel(level:int):Level {
var result:Level;
var levelType:String = "Level" + level;
return new levelType();
}
Obviously it's not going to work with a string like that, but is there any way to accomplish this in as3? What about other languages, such as Java or Python? Can you dynamically choose what type of child class to instantiate?
Update:
import Levels.*;
import flash.events.*;
import flash.utils.*;
public class LevelFactory
{
public static function createLevel(level:int):Level {
var ref:Class = getDefinitionByName('Levels.' + 'Level' + level) as Class;
var result:Level = new ref();
return result;
}
}
Update/Edit: getDefinitionByName seems to be what I'm looking for, but it has a problem. It seems that the compiler will strip unused imports, which means that unless I declare each subclass in the code ahead of time, this method will get a reference error. How can I get around the need to declare each class separately (which defeats the purpose of dynamic instantiation)?
Yes, you sure can, and it's very similar to the string thing that you've provided. The only thing that you are missing is the getDefinitionByName method: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#getDefinitionByName()
You can generate whatever class name you want, and what this method does is that it searches for that class in it's namespace, and if it finds it - it returns it as a class:
var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;
var instance:Object = new ClassReference();
This piece of code will instantiate a Sprite. This way you can instantiate your classes without all those switches and cases, especially when you have to make a hundred levels :)
Hope that helps! Cheers!
Edit:
In your case, the code should be:
var ref:Class = getDefinitionByName('com.path.Level' + index) as Class;
var level:Level = new ref(); // it will actually be Level1 Class
Since Andrey didn't quite finish helping me out, I am writing up a more complete answer to the question after much research.
getDefinitionByName definitely has the use I am looking for. However, unlike its use in Java, you HAVE to have a hard reference to the class you want instantiated somewhere in your code. Merely imported the class is not enough; the reason for this is that the compiler will strip the reference from any unused import to save space. So if you import the package of classes you want to choose dynamically but don't have a hard reference to them, the compiler will de-reference them. This will lead to a run-time error when the program cannot find the appropriate reference to your class.
Note that you don't actually have to do anything with the reference. You just have to declare a reference so that it can be found at run-time. So the following code will work to eliminate the switch-case statement and allow me to dynamically declare which class I am using at run-time.
{
import Levels.*;
import flash.events.*;
import flash.utils.*;
/**
*
* Returns the requested level using the createLevel class
* ...
* #author Joshua Zollinger
*/
public class LevelFactory
{
Level1, Level2, Level3, Level4, Level5, Level6, Level7;
public static function createLevel(level:int):Level {
var ref:Class = getDefinitionByName('Levels.Level' + level) as Class;
var result:Level = new ref(); // it will actually be the correct class
return result;
}}}
The obvious downside to this is that you still have to have a hard-coded reference to every class that can be instantiated like this. In this case, if I try to create a Level8 instance, it will through a run-time error because Level8 is not referenced. So every time I create a new level, I still have to go add a reference to it; I can't just use the reference dynamically.
There are supposedly ways around this that I have not tested yet, such as putting the code for the classes in a separate SWF and importing the SWF at run-time or using outside libraries that will have different functionality. If anyone has a solid way to get a truly dynamic reference that doesn't require a hard coded reference anywhere, I would love to hear about it.
Of course, it's still a lot cleaner this way; I don't have a extensive switch case statement to pack all the levels. And it's easier and faster to add a reference to the list than creating a new case in a switch. Plus it is closer to dynamic programming, which is usually a good thing.

Scala SimpleSwingApplication not repainting

I have a simple swing application in Scala. Work is done by a separate object but progress must be periodically reported to the GUI which launched it. The problem is that the updates are only visible once the Thread has completed its task. I've tried adding various calls to repaint() top.peer.repaint() and Thread.sleep(0) all to no avail and all the while feeling that the fact that I'm resorting to adding these is a sign I'm doing something wrong.
I remember struggling and overcoming this issue with this back when I used to develop in Java and have tried to structure my solution based on what I recall being the right approach but I must be missing something.
Here is a simple example which reproduces the problem:
import scala.swing._
import scala.swing.event.ButtonClicked
import BorderPanel.Position._
import java.awt.EventQueue
class HeavyLifter extends Runnable {
override def run = {
UpdateInterface.say("Performing Useful Work")
for (i <- 0 until Int.MaxValue) {
UpdateInterface.say(i.toString)
}
}
}
object UpdateInterface extends SimpleSwingApplication {
private val txtLog = new TextArea(32,64) {
editable = false
}
private val scrollPane = new ScrollPane(txtLog)
private val btnGo = new Button("Go")
def say(strWhat : String) = {
txtLog.append(strWhat + "\n")
}
def top = new MainFrame {
contents = new BorderPanel {
listenTo(btnGo)
reactions += {
case ButtonClicked(`btnGo`) => EventQueue.invokeLater(new HeavyLifter)
}
layout(scrollPane) = Center
layout(btnGo) = South
}
}
}
Update I've accepted the answer which drew attention to the cause of the problem. I stupidly thought that since the worker was a Runnable that EventQueue.invokeLater would spawn a separate thread for it. I have been pointed in the direction of Swing Worker which is probably the right way to go.
The EventQueue.invokeLater cause the loop to run in the dispatch thread (i.e the UI thread), which basically means that the UI thread is occupied to do the for loop and once that is done then it will update the UI and perform other tasks, after all a thread can do a single thing at a time. This is the reason your UI gets updated after the loop is completed.
What you can do is, run the worker runnable in a new thread and from that worker code dispatch a new runnable, for each update, (whose run method updated the text area value) using EventQueue.invokeLater.

as3 calling a function in another class [duplicate]

UPDATE: OK I am about ready to give up on Pacakages and classes. No answers coming. Not sure what to do. I tried to make the question easier and made a new post but I was down voted for it. as3 calling a function in another class
I am TOTALLY NEW to using PACKAGES and CLASSES. I am finally converting over from the timeline after having so many issues. Please be patient with my lack of knowledge. I need to know how to call a function in the child swf file I loaded from code in the maintime in the parent swf.
There are 2 swf files. Main.swf and pConent.swf
1. Main.swf has code in the timeline of the first frame.
2. pConent.swf is loading a PACKAGE CLASS as file.
QUESTIONS
I am trying to call a function in it from its parent Main.swf. How do I do this?
Here is sections of the code from both. Thanks
Main.swf CODE /// is an AIR for Andrid swf
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
function LoadContentTWO(e:Event)
{
Content = TheContent.content as MovieClip;
pContent = Content as Object;
addChild(TheContent);
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
}
}
A SECTION OF THE "CLASS" in pContent.swf I am trying to call
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
trace("inside ONLINE" );
}
if(OS=="device")
{
trace("inside DEVICE" );
}
}
THE ERROR I AM GETTING
TypeError: Error #1006: GetOnlineStatus is not a function.
UPDATE: I decided to post the FULL PACKAGE ( my first) to see if I am doing it right.
package
{
import flash.display.MovieClip;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.*;
import flash.media.Sound;
import flash.system.*;
import flash.media.SoundChannel;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class pContent extends MovieClip
{
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
var ScreenY = flash.system.Capabilities.screenResolutionY;
var ScreenX = flash.system.Capabilities.screenResolutionX;
var swf:String;
var daSounds:String;
var images:String;
var videos:String;
var OnlineStatus:Boolean;
//++++++++++++++++++++++++
//++++++++++++++++++++++++
public function pContent()
{
BG.addEventListener(MouseEvent.CLICK, mouseHandlerdown);
}
//++++++++++++++++++++++++
//++++++++++++++++++++++++
//-------- * FUNCTIONS * --------
//-------------------------------
public function mouseHandlerdown(event:MouseEvent):void
{
alpha = .3; // testing
}
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
{
OnlineStatus = true;
Security.allowDomain("*");
trace("inside THE PATH " + ThePath.text);
daSounds = "http://mycontactcorner.com/upload/files/";
swf = "http://mycontactcorner.com/upload/files/";
trace("inside THE DEVICE ONLINE" );
OnlineStatus = false;
swf = "";
daSounds = "content/sounds/";
//LoadMenu();
LoadStage();
LoadBeau();
}
if(OS=="device")
{
trace("inside THE DEVICE ONLINE" );
}
}
//------ * END FUNCTIONS * -----
//------------------------------
}// END FUNCTION pContent
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
}//// END PACKAGE
Don't be disappointed, but I won't have a "real" answer to your question, and I am really not going to work through all of your code to solve it, either. It is your own task to learn how to do this, and unless people here are very, very hungry for reputation, no one will do it for you - we will only help you to find the right way.
Your problem is not "packages and classes", so please do not give up on them. They will help you a great deal, once you've started to understand them. Your problem is, that you are not facing a single problem, but actually at least two (and quite substantial ones, I might add):
You need to go back to learn about the basics of object oriented programming in ActionScript. You won't have much luck getting answers to questions like this, otherwise. And believe me, I don't mean that in a patronizing way - it is simply a complicated matter, and it is hard to communicate complicated issues, both when you don't know the terms to express them, or when your counterpart doesn't understand them. Think of it like a high school math problem: You won't ever find a solution to your trigonometry question (or get a decent answer), unless you learn some basic algebra first.
You also have a problem related to loading, application domains, and the Flash Player security model - which are all far more complicated than what you should aim at when trying out OOP stuff. This can be a major obstacle, and unless you want to frustrate yourself, you should try to avoid it, until your program actually runs.
So this here is my advice: Always try to solve one problem at a time. Do not work yourself into such complex scenarios as the one you are in right now, but take step by step, until you've reached a level where you are confident with what you are doing.
Your first issue should be to understand what's going on with classes and objects. Everything else will come later. You should try to isolate your problem in the pContent.swf and get that to work first - or better yet, put everything you need for your program into a single file. Convert to using classes. Then, once you know how to work with those, start learning about more advanced OO, decoupling your code using interfaces, type casting and loading binaries at runtime.
//makes contact with classs but comes out as: [object pContent]
its because you said
pContent = Content as Object;
I am not sure why you are doing this extra step
Change it to this
Content = TheContent.content as MovieClip;
// pContent = Content as Object; //NO NEED OF THIS
addChild(Content); // just in case this gives error change it as addChild(Content as Object);
var OSS:String = "device";
trace(Content); //now see the difference
Content.GetOnlineStatus(OSS); // it calls now
Also, give the link where you posted that scary question :P if it has rest of the code
Sorry if this does not sound like an answer, but I'm going to write a couple of doubts that I have reading your code that can possibly lead to the solution:
Why are you casting it to MovieClip? If you cast it as MovieClip, the compiler it is going to tell you that the method "GetOnlineStatus" doesn't exist, because MovieClip class doesn't have it! I think you have to cast it as pContent
Why are you trying to casting TheContent.content? What is "content"? I had a look to your previous post and I cannot see anything called "content"?
If I ignore my second doubt (TheContent.content issue), I would change the code like this:
Content = TheContent.content as pContent; // your class it's called pContent
addChild(Content);
Content.GetOnlineStatus(OSS); // it calls now
Also, keep in mind that generally it's a good pratice to capitalize name of classes and not variables.
Let me know!
private function GetOnlineStatus
Try making this a public function instead. When it's private it can't be accessed outside the scope of the class that owns it.
I believe that in order to make this work, content property of the Loader. You have to create a reference to the loaded SWF as the class you are trying to call. This class has to be included in the main SWF's project. Then you can call the functions of that particular class in the child.
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
}
function LoadContentTWO(e:Event)
{
var pContent:GetOnlineStatus = GetOnlineStatus(e.target.content);
addChild(e.target.content); //Assuming that "TheContent was
// declared as var TheContent:Loader , you'd be adding the loader to the stage when I think you actually wanted // to add the content.
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
// This should work now. If not, try to loading a function that is not the class' main function. Because I think you might get an "unable to call static function error". I'm a begginner too though, so sorry if I'm wrong. Example: pContent.GetOnlineStatusFunction(OSS);
}
This answer assumes that the pContent.swf contains a class file that looks like this:
package {
public class GetOnlineStatus {
public function GetOnlineStatus (OSS:String) {
//Do your GetOnlineStatus Logic. This is the main function.
}
/*public function GetOnlineStatusFunction (OSS:String) {
//Example non-main function
} */
}
}
Source: http://www.scottgmorgan.com/accessing-document-class-of-externally-loaded-swf-with-as3/

Handle swing ScrollBar events in scala

I am trying to add a ScrollBar. The ScrollBar will iterate through the documents displayed. However, I am having trouble receiving an event when the scroll bar changes. I'm not sure what I need to listen to, and I'm not sure what event I should be responding to. I tried the following and I get some events, but I don't think these are the ideal events to handle.
listenTo(scrollBar)
listenTo(scrollBar.keys)
listenTo(scrollBar.mouse.moves)
listenTo(scrollBar.mouse.wheel)
listenTo(scrollBar.mouse.clicks)
For example, I only get MouseClicked, MousePressed, and MouseReleased when I click inside the scrollbar--not when I click on the arrows to actually change the value.
I found this discussion about scroll bars not receiving events properly, but it's two years old. As far as I can tell, the author did not follow up an file a ticket. Maybe he found a workaround.
Any ideas?
Good question. Clicking on arrows isn't handled by ScrollBar, it's handled by ScrollBarUI. I believe that default implementation(or at least base class for majority of ScrollBarUI implementations) is BasicScrollBarUI.
If you'll take a look into source of javax.swing.plaf.basic.BasicScrollBarUI it has incrButton and decrButton buttons and they are components you want listen to.
P.S. I had similar need for having custom (key) listener for my Slider and having custom ui which exposes needed components/model(as you could see almost all components are protected so you easy could access them in subclasses and expose via public getters) worked great for me. I did that in plain java though, maybe in scala you can listen to buttons just by specyfying property name.
One more piece of Scala Swing being broken. The Adjustable trait seems to be completely hollow, nothing is wired.
The following works:
class ScrollBarAlive extends swing.ScrollBar {
me =>
peer.addAdjustmentListener(new java.awt.event.AdjustmentListener {
def adjustmentValueChanged(e: java.awt.event.AdjustmentEvent) {
publish(new swing.event.ValueChanged(me))
}
})
}
Test:
import swing._
object ScrollBarTest extends SimpleSwingApplication {
lazy val top = new Frame {
val label = new Label { text = "0" }
val scroll = new ScrollBarAlive {
orientation = Orientation.Horizontal
listenTo(this)
reactions += {
case event.ValueChanged(_) =>
label.text = value.toString + (if (valueIsAjusting) " A" else "")
}
}
contents = new BorderPanel {
add(label, BorderPanel.Position.North)
add(scroll, BorderPanel.Position.South)
}
pack().centerOnScreen()
open()
}
}
A proper implementation would also introduce a subtype of AdjustingEvent.