good day!
i have a situation while trying to process several images in a batch using c#, NumSharp and an onnx model
See an extract code below:
var modelPath = #"Resources/model_20221026.onnx";
var outputColumnNames = new[] { "dense_4" };
var inputColumnNames = new[] { "input_5" };
var mlContext = new MLContext();
var pipeline = mlContext.Transforms.ApplyOnnxModel(outputColumnNames, inputColumnNames, modelPath);
var img0 = Bitmap.FromFile(path, true);
var content = ResizeImage(img0, 512, 512);
img0.Dispose();
var data0 = content.ToNDArray(flat: false, copy: false);
var dataNP = np.array(data0).astype(NPTypeCode.Single).flatten().ToArray<float>();
content.Dispose();
var input = new Input { Data = dataNP };
var dataView = mlContext.Data.LoadFromEnumerable(new[] { input });
var transformedValues = pipeline.Fit(dataView).Transform(dataView);
var output = mlContext.Data.CreateEnumerable<Output>(transformedValues, reuseRowObject: false);
float[] probabilities = output.Single().Data;
float defect = (float)Math.Round(100 * probabilities[0], 2);
float nodefect = (float)Math.Round(100 * probabilities[1], 2);
string[] NameImg = path.Split('\\');
Logger.Info("------------ID: "
+ " " + NameImg[NameImg.Length - 1]
+ " - Defect: " + defect + "%"
+ " - NoDefect: " + nodefect + "%");
It will do it once, sometimes twice, but then, it will crash. The application will crash suddently, and won't write in logs anything if i try to catch any argument error.
If i try in debug mode i get this error:
Any idea is very welcome,
thanks!
I tried in:
Debug mode
Disposing contents
Instead of opening a file with Bitmap.FromFile, i tried to stream the content
I try catching arguments exceptions and exceptions in general
Related
I'm trying to launch roblox from c#, but it seems it cannot find the roblox-protocol.
I tried the code I use in windows run and it did find, but once I try it with Process.Start it says the file could not be found.
public static string LaunchRoblox(string authTicket)
{
Random rnd = new Random();
long browserTrackerId = 55393295400 + rnd.Next(1, 100);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int launchTime = (int)t.TotalSeconds * 1000;
string url = $#"roblox-player:1+launchmode:play+gameinfo:{authTicket}+launchtime:{launchTime}+placelauncherurl:https://assetgame.roblox.com/game/PlaceLauncher.ashx?request=RequestGame&browserTrackerId=" + browserTrackerId + "&placeId=185655149&isPlayTogetherGame=false+browsertrackerid:" + browserTrackerId + "+robloxLocale:en_us+gameLocale:en_us";
return url;
}
static void Main(string[] args)
{
Program.x_crsf_token = GetXCSRFToken();
Console.Write("Sucessfully obtained X-CRSF-Token: " + Program.x_crsf_token);
Console.WriteLine("");
string AuthTicket = GetAuthTicket();
Console.Write("Sucessfully obtained AuthTicket: " + AuthTicket);
Console.WriteLine("");
string joiner = LaunchRoblox(AuthTicket);
Console.Write("Trying to launch roblox with:" + joiner);
Console.WriteLine("");
var game = Process.Start(joiner);
game.WaitForExit();
}
This is the error I get
What you do works in .NET Framework. But your error message shows that you are using .NET 6.0. For any .NET Core and later you would need to do something like:
var psi = new ProcessStartInfo(joiner)
{
UseShellExecute = true
};
var game = Process.Start(psi);
I've been looking for this but I cannot seem to find the answer.
What I want to accomplish is the following:
Right now when I reply with my embed it shows for example:
footbal,baseball
But what I want it to be is the following:
football,
baseball
Spread over 2 different lines.
Does anyone know how to do this with text Code?
Thank you in advance
Here is the code:
var value = "";
int price = 0;
foreach (var Item in content)
{
value += Item.Item1 + ": " + Item.Item2.ToString();
price += Item.Item2;
}
return new EmbedFieldBuilder()
{
Name = category + " - " + price,
Value = value
};
Worked for me with simple "\n" or Environment.NewLine:
var embed = new EmbedBuilder
{
Author = new EmbedAuthorBuilder() { Name = "AuthorNameHere" },
Title = "Sports",
Color = Color.Orange,
Description = "Football" + "\n\n" + "Baseball"
}.Build();
//var channel = GetYourNeededChannel();
await channel.SendMessageAsync("", false, embed);
Also works with fields in embed:
Fields = new List<EmbedFieldBuilder>()
{
new EmbedFieldBuilder()
{
Name = "TestField1",
Value = "FieldValue1" + "\n\n" + "FieldValue2"
}
}
Having this code:
var code = "public class TestClass {" +
" public int HelloWorld(int num) {" +
" return 5 + num;" +
" }" +
"}";
var script = CSharpScript.Create(code);
var x = (await script.RunAsync()).ReturnValue;
How does one pass a value for the parameter, call the method and read the return value?
Continue with another code is the simplest.
var call = await script.ContinueWith<int>("new TestClass().HelloWorld(3)").RunAsync();
var x = call.ReturnValue;
By the way, CSharpScript is a scripting engine which does not require you having class and method like ordinary C# program. You can just use 5 + num as script content.
var code = "5 + num";
var numValue = 3;
var setParam = await CSharpScript.RunAsync("var num = " + numValue + ";");
var runCode = await setParam.ContinueWithAsync(code);
var x = runCode.ReturnValue;
For full example, take a look of RoslynScript/Script.cs
I am using the BingSearchContainer.cs with a Winform in C#. I am returning the results using the following code. After a good couple of hours looking I can't figure out how to return the other pages of results. It is only possible to return a maximum of 50 results at a time. I would like to return more pages and then add these to "imageSet" to have a full list of resulting images. Any hints or pointers would be really useful, thanks in advance for any help.
void bingSearch(string searchTerm)
{
try
{
imageSet = new List<Bing.ImageResult>();
const string bingKey = "[key]";
var bing = new BingSearchContainer(
new Uri("https://api.datamarket.azure.com/Bing/Search/")) { Credentials = new NetworkCredential(bingKey, bingKey) };
var query = bing.Image("\"" + searchTerm + "\"" + "(" + site1 + " OR " + site2 + ")", null, null, null, null, null, ImageFilters);
Debug.Print("Full Search: " + query.ToString());
query = query.AddQueryOption("$top", 50);
query = query.AddQueryOption("$skip", 20);
var results = query.Execute();
int index = 0;
foreach (var result in results)
{
imageSet.Add(result);
Debug.Print("URL: " + imageSet[index].MediaUrl);
index++;
}
Debug.Print("Results: " + imageSet.Count);
}
catch
{
Debug.Print("Error");
}
}
Solved this.
Actually it is very simple. The "$skip", 20 query option sets the off-set for the pages such that if I have an off-set of 0 I get the first 50 images, an off-set of 50 I get the next 50 images and so on.
I get:
Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given
key was not present in the dictionary.
when iterating over user story query results and try to access story["Tasks"]
foreach (var story in queryStoryResults.Results)
{
Console.WriteLine("FormattedID: " + story["FormattedID"]);
Console.WriteLine("Name: " + story["Name"]);
Console.Write("Tasks: " + story["Tasks"]);
}
First, make sure that Tasks are being fetched, along with task specific fields that you want to extract, e.g. State.
Next, a nested loop is needed inside the loop that iterates over user story results.
Here is the code example. It queries on user stories from the current iteration and prints out FormattedID and State of tasks associated with the query results:
namespace RESTexample_storiesFromIteration
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#domain.com", "1984", "https://rally1.rallydev.com", "1.43");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
bool projectScopingUp = false;
bool projectScopingDown = true;
DateTime now = DateTime.Today;
String nowString = now.ToString("yyyy-MM-dd");
Request iterationRequest = new Request("Iteration");
iterationRequest.Workspace = workspaceRef;
iterationRequest.Project = projectRef;
iterationRequest.Fetch = new List<string>()
{
"Name",
"StartDate",
"EndDate",
"Project",
"State"
};
String iterationQueryString = "((StartDate <= \"" + nowString + "\") AND (EndDate >= \"" + nowString + "\"))";
iterationRequest.Query = new Query(iterationQueryString);
QueryResult queryIterationResults = restApi.Query(iterationRequest);
var myIteration = queryIterationResults.Results.First();
var myIterationName = myIteration["Name"];
var myIterationProject = myIteration["Project"];
var myIterationProjectName = myIterationProject["Name"];
Console.WriteLine("Name: " + myIterationName);
Console.WriteLine("Project Ref: " + myIterationProjectName);
Console.WriteLine("State: " + myIteration["State"]);
// Query for Stories
Request storyRequest = new Request("hierarchicalrequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"ObjectID",
"ScheduleState",
"State",
"FormattedID",
"PlanEstimate",
"Iteration",
"Tasks"
};
storyRequest.Query = new Query("Iteration.Name", Query.Operator.Equals, myIterationName);
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine("----------");
Console.WriteLine("FormattedID: " + s["FormattedID"]);
Console.WriteLine("Name: " + s["Name"]);
Console.WriteLine("PlanEstimate: " + s["PlanEstimate"]);
var tasks = s["Tasks"];
foreach (var t in tasks)
{
Console.WriteLine("Task: " + t["FormattedID"] + " " + t["State"]);
}
}
}
}
}