In Rust, when assertion fails hop into debugger - visual-studio-code

A simple library that has been very convenient, indispensable even, in C# is
namespace SharedLibraries.Verification { public static class Verify {
// conditions that must be satisfied in order to use a module go here
public static void Require(bool B) {
if (B) return;
System.Diagnostics.Debugger.Break();
}
// things that should be provably true if the Require(s) of a module are met
public static void Assert(bool B) {
if (B) return;
System.Diagnostics.Debugger.Break();
}
public static void AssertFail() {
System.Diagnostics.Debugger.Break();
}
}}
namespace SharedLibraries.VerificationOff { public static class Verify {
[System.Diagnostics.Conditional("DoNotEverTurnThisOn")]
public static void Require(bool B) {}
[System.Diagnostics.Conditional("DoNotEverTurnThisOn")]
public static void Assert(bool B) {}
[System.Diagnostics.Conditional("DoNotEverTurnThisOn")]
public static void AssertFail() {}
}}
If a requirement or assertion fails, it pops me into the debugger. When I want to turn it off, I just change the include command from Verification to VerificationOff. It won't even compute "B" when it is turned off so there is no overhead.
I have been trying all kinds of different things to try to make a Rust/VSCode library to do the same thing. Here is what I have so far:
pub mod on {
pub fn require<Predicate: FnOnce() -> bool>(check : Predicate) {
if cfg!(debug_assertions) {
if !check() {
unsafe {
println!("before debug break");
winapi::um::debugapi::DebugBreak();
println!("after debug break");
}
}
}
}
pub fn assert<Predicate: FnOnce() -> bool>(check : Predicate) {
if cfg!(debug_assertions) {
if !check() {
unsafe {
winapi::um::debugapi::DebugBreak();
}
}
}
}
}
pub mod off {
pub fn require<Predicate: FnOnce() -> bool>(_check : Predicate) {}
pub fn assert <Predicate: FnOnce() -> bool>(_check : Predicate) {}
}
This works at least when the above code is in the same crate as the program that is executed. But when it is included from a standalone crate using "extern crate verifier" (or whatever name) then whenever an assertion fails the program just crashes and the debugger closes down. And it crashes exactly on the winapi call. The debugger vscode is using is cppvsdbg for windows.
I'm looking for help to make this work. Maybe converting to macros or using a different command to get the debuggers attention. I'm very fresh with rust so please be explicit.

Related

Unity Editor detect when build fails

I'm trying to use IPreProcessBuildWithReport and IPostProcessBuildWithReport to add a game object to the scene right before build, and promptly delete it from the scene when the build finishes. The goal is to reduce all that I can from the hierarchy during the development but include these objects during the build.
My issue occurs when the build fails (due to some error), it adds the game object before the build started but never reached the code to delete the game object when it fails.
Is there a similar method to detect when the build fails without building my own build player pipeline? I really don't want to stray away from unity's default build pipeline if I don't need to.
If there was no easy way, I was trying to think if maybe there was a way to track the buildfailed exception or error and run a method if it occurs.
Thanks, let me know what you guys think.
EDIT: As requested, here is an example:
class CustomBuildPipeline : MonoBehaviour, IPreprocessBuildWithReport, IPostprocessBuildWithReport
{
public int callbackOrder => 0;
// CALLED BEFORE THE BUILD
public void OnPreprocessBuild(BuildReport report)
{
// Create and add gameobjects to scene
}
// CALLED AFTER THE BUILD
public void OnPostprocessBuild(BuildReport report)
{
// Remove gameobjects from scene once built
}
}
}
PreProcess Interface
PostProcess Interface
I was wondering if there was a possible solution by somehow detecting when this buildexception was thrown and running code following.
EDIT 2: I found this post that has possible solutions, however, it may not be as elegant as I'd prefer. I'll try some things out and report back.
I used the post in the 'EDIT 2' to come up with a decent solution. I don't know if it will work 100% of the time and I would love for someone to correct me if I have chosen a poor solution. This should allow me to run code before the build starts, and if the build fails or succeeds without changing the unity build pipeline.
class CustomBuildPipeline : MonoBehaviour, IPreprocessBuildWithReport, IPostprocessBuildWithReport
{
public int callbackOrder => 0;
// CALLED BEFORE THE BUILD
public void OnPreprocessBuild(BuildReport report)
{
// Start listening for errors when build starts
Application.logMessageReceived += OnBuildError;
}
// CALLED DURING BUILD TO CHECK FOR ERRORS
private void OnBuildError(string condition, string stacktrace, LogType type)
{
if (type == LogType.Error)
{
// FAILED TO BUILD, STOP LISTENING FOR ERRORS
Application.logMessageReceived -= OnBuildError;
}
}
// CALLED AFTER THE BUILD
public void OnPostprocessBuild(BuildReport report)
{
// IF BUILD FINISHED AND SUCCEEDED, STOP LOOKING FOR ERRORS
Application.logMessageReceived -= OnBuildError;
}
}
}
This approach is using a custom build handler, but still uses the default build pipeline.
Use BuildHandler.OnBuildStarted instead of (or in addition to) IPreprocessBuildWithReport for pre-processing. For post-processing use BuildHandler.OnBuildCleanup, which is called when a build completes or fails. Can also be used in conjunction with IPostprocessBuildWithReport.
[InitializeOnLoad]
public class BuildHandler : MonoBehaviour
{
public static event Action OnBuildStarted;
public static event Action OnBuildCleanup;
static BuildHandler()
{
BuildPlayerWindow.RegisterBuildPlayerHandler(Build);
}
private static void Build(BuildPlayerOptions buildOptions)
{
try
{
BuildStarted();
//now start Unity's default building procedure
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildOptions);
}
catch (BuildPlayerWindow.BuildMethodException) { } //logged internally
catch (Exception ex)
{
Exception log = ex.InnerException == null ? ex : ex.InnerException;
Debug.LogException(log);
Debug.LogErrorFormat("{0} in BuildHandler: '{1}'", log.GetType().Name, ex.Message);
}
finally
{
BuildCleanup();
}
}
private static void BuildStarted()
{
try
{
if (OnBuildStarted != null)
OnBuildStarted.Invoke();
}
catch (Exception ex)
{
throw new Exception("OnBuildStarted failed", ex);
}
}
private static void BuildCleanup()
{
if (OnBuildCleanup != null)
{
foreach (Action cleanupBuild in OnBuildCleanup.GetInvocationList())
{
try
{
cleanupBuild.Invoke();
}
catch (Exception ex)
{
Object context = cleanupBuild.Target as Object;
Debug.LogException(ex, context);
Debug.LogWarning("Caught exception while BuildHandler.OnBuildCleanup... Continuing");
}
}
}
}
}

Play 2.5.9 + cucumber, JPA withTransaction deprecated

I am trying to write following database test with cucumber :
#Given("^I have N foos$")
public void i_have_N_foos() throws Throwable {
JPA.withTransaction(() -> {
fooSize = foo.count();
});
}
foot.count() should be in a transaction butJPA.withTransaction method is deprecated. How can I use JPAApi with my cucumber test?
Fixed with :
public class Foo{
JPAApi jpaApi;
#Given("^I have N foos$")
public void i_have_N_foos() throws Throwable {
jpaAPI= JPA.createFor("fooPersistenceUnit");
jpaApi.withTransaction(() -> {
fooSize = foo.count();
});
}
}

error when i run my RMI project

what do i have to do when I have this error:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException
I added the path of the bin in JDK in the properties of "MY computer": this one "C:\Program Files\Java\jdk1.6.0_19\bin"
and I entered to run-cmd-
cd C:\Users\user\Documents\NetBeansProjects\CountRMI\src\countrmi
start rmiregistry
and i run the server, so this error appear
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException
Thank u
Consider looking at the Cajo project. It wraps RMI so you don't have to worry about starting rmi registries and the such.
See the example below from one of the Cajo wiki pages
Duck.java
public interface Duck {
boolean looks();
boolean walks();
boolean talks();
}
DuckServer.java
import gnu.cajo.invoke.Remote;
import gnu.cajo.utils.ItemServer;
public class DuckServer implements Duck {
public boolean looks() {
System.out.println("hi there!");
return true;
}
public boolean walks() {
System.out.println("waddle waddle");
return true;
}
public boolean talks() {
System.out.println("quack quack!");
return true;
}
public static void main(String args[]) throws Exception { // simple unit test
Remote.config(null, 1198, null, 0); // use cajo port 1198
ItemServer.bind(new DuckServer(), "Donald");
System.out.println("duck server running");
}
}
DuckClient.java
import gnu.cajo.utils.extra.TransparentItemProxy;
public class DuckClient { // try out DuckServer
public static void main(String args[]) throws Exception {
Duck duck = (Duck)TransparentItemProxy.getItem(
"//serverHost:1198/Donald",
new Class[] { Duck.class }
);
System.out.println("looks like = " + duck.looks());
System.out.println("walks like = " + duck.walks());
System.out.println("talks like = " + duck.talks());
}
}
The time has passed, but maybe this helps someone. When you put
cd C:\Users\user\Documents\NetBeansProjects\CountRMI\src\countrmi
you are setting de path to sources files, but yo have to set this to the classes files, in this way
cd C:\Users\user\Documents\NetBeansProjects\CountRMI\build\classes
and start rmiregistry, of course
at least, it worked fine for me.

GWT problem with calling Java methods from JSNI

I tried the example from google at this page:
http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJavaFromJavaScript
I want to be able to call a Java method from JSNI, but nothing happens. No errors but the methods are not called. However, I can modify the fields from my class.
Here is the code I tried:
package com.jsni.client;
import com.google.gwt.core.client.EntryPoint;
public class Testjsnii implements EntryPoint {
String myInstanceField;
static int myStaticField;
void instanceFoo(String s) {
System.out.println(s);
}
static void staticFoo(String s) {
System.out.println(s);
}
public native void bar(Testjsnii x, String s) /*-{
this.#com.jsni.client.Testjsnii::instanceFoo(Ljava/lang/String;)(s);
x.#com.jsni.client.Testjsnii::instanceFoo(Ljava/lang/String;)(s);
#com.jsni.client.Testjsnii::staticFoo(Ljava/lang/String;)(s);
var val = this.#com.jsni.client.Testjsnii::myInstanceField;
}-*/;
public void onModuleLoad() {
bar(this,"Hello");
}
}
It prints nothing on the console but only a waring that says:
[WARN] [testjsnii] - JSNI method
'#com.jsni.client.Testjsnii::bar(Lcom/jsni/client/Testjsnii;Ljava/lang/String;)' returned > a value of type JavaScript object(1) but was declared void; it should not have returned a > value at all
I wonder what is the problem.
Thanks for the help.
You're actually running into a Chrome (10-dev) issue with the GWT DevMode plugin: http://code.google.com/p/google-web-toolkit/issues/detail?id=5778

Making Extension method Generic

In this post there's a very interesting way of updating UI threads using a static extension method.
public static void InvokeIfRequired(this Control c, Action<Control> action)
{
if(c.InvokeRequired)
{
c.Invoke(() => action(c));
}
else
{
action(c);
}
}
What I want to do, is to make a generic version, so I'm not constrained by a control. This would allow me to do the following for example (because I'm no longer constrained to just being a Control)
this.progressBar1.InvokeIfRequired(pb => pb.Value = e.Progress);
I've tried the following:
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke(() => action(c));
}
else
{
action(c);
}
}
But I get the following error that I'm not sure how to fix. Anyone any suggestions?
Error 5 Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
replace :
c.Invoke(() => action(c));
with :
c.Invoke(action, c);
This is a well known error with lambdas and anonymous methods:
Convert this delegate to an anonymous method or lambda
Your code just needs a cast to compile:
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke((Action<T>)((control) => action(control)));
}
else
{
action(c);
}
}
Try this slight varient:
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke((Action<T>)(() => action(c)));
}
else
{
action(c);
}
}
You need to cast it as a Delegate type. Kinda stupid I know. I can't really give you a good reason why a lambda expression isn't implicitly assignable as a delegate.