unity - Error In Read From JSON - c#

This is part of a code that someone wrote for me in answer to a question:
JSONObject jsonRead = new JSONObject(jsonString);
packsInfo = new Pack[jsonRead.Count];
for(int i =0; i < jsonRead.Count; i ++)
{
Pack pack = new Pack();
pack.number = (int)jsonRead[i]["number"].i;
pack.angle = (int)jsonRead[i]["angle"].i;
pack.zPosition = jsonRead[i]["z_position"].f;
pack.beatCaseDistance =jsonRead[i]["beat_case_distance"].f;
pack.gunDistance = jsonRead[i]["gun_distance"].f;
packsInfo[i] = pack;
}
I used it in my code. Every thing worked right but these lines:
pack.number = (int)jsonRead[i]["number"].i;
pack.angle = (int)jsonRead[i]["angle"].i;
I realized that .f is a get{} method for reading float from JSON and I find nothing for reading int. And if I delete .i, it gives me the error that he can't convert JSON to int implicitly.

.i returns long type. Because i using cast from long to int
int i = (int)json["number"].i.
Why is there no have fields or methods with returned int value? I don't know! But you can create it in JSONObject.cs! It will be something like this:
public int Int{
get {
return (int)i;
}
}

Related

CNTKLibrary-2.0 "System.AccessViolationException: Attempted to read or write protected memory. "

I am following the CNTKLibrary-2.0 example to write a simple case to check minibatch version of evaluation. The code looks like in the following way. But I got the access violation exception when I call "Evaluate" function. Any insights about such exception.
const string outputName = "r1";
const string inputName = "qu1fea";
var inputDataMap = new Dictionary<Variable, Value>();
// Load the model.
Function modelFunc = Function.LoadModel("D:/deep_cross/ModelEvaluation_cpp/models/dfsr.cn", device);
Console.WriteLine(modelFunc.Outputs.Count);
for (int i = 0; i < modelFunc.Outputs.Count; i++)
{
Console.WriteLine(modelFunc.Outputs[i].GetName());
}
// Get output variable based on name
Variable outputVar = modelFunc.Outputs.Where(variable => string.Equals(variable.Name, outputName)).Single();
// Get input variable. The model has only one single input.
// The same way described above for output variable can be used here to get input variable by name.
Console.WriteLine(modelFunc.Arguments.Count);
for (int i = 0; i < modelFunc.Arguments.Count; i++)
{
Console.WriteLine(modelFunc.Arguments[i].GetName());
}
Variable inputVar = modelFunc.Arguments.Where(Variable => string.Equals(Variable.Name, inputName)).Single();
var outputDataMap = new Dictionary<Variable, Value>();
Value inputVal, outputVal;
List<List<float>> outputBuffer;
// Get shape data for the input variable
NDShape inputShape = inputVar.Shape;
// Create Value for the batch data.
inputVal = Value.CreateBatch(inputVar.Shape, samples, device);
// Create input data map.
inputDataMap.Add(inputVar, inputVal);
// Create ouput data map. Using null as Value to indicate using system allocated memory.
// Alternatively, create a Value object and add it to the data map.
outputDataMap.Add(outputVar, null);
// Evaluate the model against the batch input
modelFunc.Evaluate(inputDataMap, outputDataMap, device);
// Retrieve the evaluation result.
outputBuffer = new List<List<float>>();
outputVal = outputDataMap[outputVar];
outputVal.CopyVariableValueTo(outputVar, outputBuffer);
// Output result
PrintOutput(outputVar.Shape.TotalSize, outputBuffer);
The exception is caused by a bug, which is now fixed. We have just published CNTK Nuget package 2.0-Beta9.0. Could you please have a try?
Sorry for the inconvenience.
Thanks,

Adding CustomClassObjects to Dictionary as values

I have a task where I need to have two values for one key in Dictionary.
Solution found in web is to make new class with two fields and use it's objects as values.
But how can I assign value to my CustomClassObjects from Dictionary's for loop?
Here is the code:
Dictionary<char, Huffmans> HuffmanDictionary = new Dictionary<char, Huffmans>();
Program.text = File.ReadAllText(Program.sourcetext);
char character;
for (int i = 0; i < Program.text.Length; i++)
{
counter++;
character = Convert.ToChar(Program.text[i]);
if (HuffmanDictionary.ContainsKey(character))
HuffmanDictionary[character].probability++;
else
HuffmanDictionary.Add(character, 1);// here is the problem, obviously program can't assign value directly to class...
}
public class Huffmans
{
public int code = 0;
public double probability = 0;
}
Basically, I need to assign only "probability" values on this step. Should I call constructor for "Huffmans " on each iteration?
Big thanks for any help, Alex
You need to instantiate your class before adding the value:
HuffmanDictionary.Add(character, 1);
Should be:
HuffmanDictionary.Add(character, new Huffmans{ code = 1 });
Alternatively you can create a constructor for your class:
public class Huffmans
{
public Huffmans(int _code)
{
code = _code;
}
public int code = 0;
public double probability = 0;
}
then you can do:
HuffmanDictionary.Add(character, new Huffmans(1));
EDIT:
Some more clarification:
HuffmanDictionary.Add(character, 1);
fails because you are passing a type int into the dictionary but it is expecting the type Huffmans. Our dictionary is : Dictionary<char,Huffmans>()
HuffmanDictionary.Add(character, new Huffmans{ code = 1 });
works because now we are creating a new object of type Huffmans and we are setting the code value to 1.
Not sure if I understood your comment correctly, but effectively we are doing the same as:
var newHuffmans = new Huffmans{ code = 1 };
HuffmanDictionary.Add(character, newHuffmans);
But rather than writing out all that code and creating a named variable with our class, we skip this and pass it directly into the dictionary.

How to convert array of string to enum?

How can I convert an array of string to enum?
The following code gives a basic idea about what is expected,
permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );
however, it throws an error like
can not convert object to enum.
Here, PagePermission is enum.
string pagePermission = "View,Edit";
string[] permissions = pagePermission.Split(',');
permission.Permissions = new List<PagePermission>();
for (int i = 0; i < permissions.Length; i++)
{
string a = permissions[i];
permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );
}
Use this
IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
Enum.Parse returns an object, you need to cast it to the actual enum type. In your case:
permission.Permissions.Add((PagePermission)Enum.Parse(typeof(PagePermission), a);
Otherwise you'd be adding an object to a list of PagePermission, which causes the error you had.

File Parsing where one column of an array needs to be converted to a different type

Still learning and looking for a little guidance - I've got a CSV file that I'm reading into my program using a method with two foreach loops like so:
int i = 0;
int j = 0;
string File = File.ReadAllText("c:\\employees.txt");
string[,] filesArray = new string[File.ReadLines("c:\\employees.txt").Count(), 4];
foreach (string row in rawFile.Split('\n'))
{
foreach (string col in row.Trim().Split(','))
{
filesArray[i, j] = col;
j++;
}
j = 0;
i++;
}
return filesArray;
All well and good and I can dumbly display the text fine but the format of the CSV file is
Z0003, EmployeeNameHere, 00001
and I want to do some math and other calculations based on the values in filesArray[2, 0] and so on but I'm trying to find what would be best practice for this situation.
I can think of ways that don't seem elegant and honestly it's been a bit of a mess trying to find the exact answer to this question through Google. I don't want to pick up bad habits at such an early stage!
Your problem right now is you have the data (even though getting it is ugly), but it is all in strings. No matter what you do, you will have to convert to a decimal or other numeric format to do math on it.
I would recommend using a library like FileHelpers to read your CSV data into an "employee" class first. This will give you strongly typed objects. See the 'Quick Start Delimited' entry on the left side. your class would look something like this:
[DelimitedRecord(",")]
public class Employee {
// fields in same order as in the file
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int MyNumber { get; set; }
}
Suggestions for current code:
What is rawFile ?? you get the lines using ReadAllLines()
Follow .NET naming guidelines. var file = ... not var File =
Don't use the same name as common .Net classes (e.g. File). Call it fileLines, etc
Don't read the file twice to get the # of lines. use new string[fileLines.Count, 4]
You can use LINQ and calls to split easier if you don't use a [,] multi-dimensional array.
To convert between string and int, you will need int.Parse or int.TryParse
Add error checking to make sure your lines are the correct length, etc
Some sample code:
var data = fileLines.Select(line => line.Split(','))
.Where(arr => arr.Length == 4) // should have 4 fields
.ToArray();
var xxxx = data[0][1]; // should be "EmployeeNameHere"
// this assumes your data is ALL valid
var numbers = data.Select(x => int.Parse(x[2])).ToList();
var sum = numbers.Sum();
// there is no "pretty" way to do TryParse
var numbers = new List<int>();
foreach(var arr in data) {
int temp = 0;
if (int.TryParse(arr[2], out temp)) {
numbers.Add(temp);
}
}

C# protobuf-net serialized object to java

So I have a small problem:
A message is sent using MQTT, it consists of a series of serialized objects using protobuf-net in C# (I can't modify this code, but I have access to the source). At the other end i receive the serialized objects in Java, the problem is I can't seem to be able to deserialize the objects using protobuf, if anyone ever had this problem and solved it, please help :)
Example of object from C#:
using ProtoBuf;
namespace Concentrator.Services
{
[ProtoContract]
public class MeterID
{
private byte[] _id;
[ProtoMember(1)]
public byte[] ID
{
get { return _id; }
set { _id = value.Length == 16 ? value : null; }
}
[ProtoMember(2)] public string MeterType;
}
}
My attempt at recreating the same object in Java (the .proto file):
syntax = "proto2";
package mqtt.entity;
option java_package = "mqtt.entity";
option java_outer_classname = "ProtoMeter";
message Meter {
optional bytes ID = 1;
optional string MeterType = 2;
}
message MeterID {
repeated Meter mid = 1;
}
A solution to this example would be a huge help, Thanks a lot.
The code where the object is deserialized in C#:
var ms = new MemoryStream(data, 7, data.Length - 9)
var res = Serializer.Deserialize<List<MeterID>>(ms);
this works in C#, I'm trying to achieve the same thing in java
The message in your C# code matches just:
message MeterID {
optional bytes ID = 1;
optional string MeterType = 2;
}
There is no need for a 2-level model (unless you're using *WithLengthPrefix in the C# code). You can also get that output by using:
var proto = Serializer.GetProto<MeterID>();
With your edit, a List<MeterID> could be mapped as
message List_MeterID {
repeated MeterID items = 1;
}
to be used in combination with the previous MeterID fragment. Which is what you have in the question. So it comes down to "what currently happens?".
try regenerate proto-file by GetProto<T>

Categories