Confusion using SimpleJSON - JSON interpretor - c#

I'm using SimpleJSON which can be found here. <-- Source and documentation.
Here's the JSON that's being output in my PHP script using the json_encode function.
{
"response":3,
"establishments":[
["1","-107.102180","39.410870","0"],
["8","-106.977715","39.377403","7.03707478751404"],
["9","-106.843636","39.484631","14.706647410396497"],
["12","-106.950661","39.230804","14.846070600598637"]
]
}
In the examples on the SimpleJSON page, "establishments" should technically be a nested object, and not a nested array. After going through the code I had assumed that the following would suffice
int id = N["establishments"][0].Value
double long = N["establishments"][1].Value
double lat = N["establishments"][2].Value
Where N is the node containing the Json Information (more info in docs).
However all of these values are returning blank, could anyone point out why? So far arrays have been my only problem with this, and I don't understand the logic behind this enough to figure out what's wrong on my own.
NOTE: As pointed out by #jskidie this is a two dimensional array, I'm having problems returning the full Array (in the 2nd dimension) not the values.

Because you have multi dimensional array. Try:
int id = N["establishments"][0][0].Value
double long = N["establishments"][0][1].Value
double lat = N["establishments"][0][2].Value

What I was looking for was stored in the JSONArray class.
JSONArray array = json["establishments"].AsArray;
for(int i = 0; i < array.Count; i++) {
}
which allows me to iterate over all occurrences.

Related

Passing a vector from C# to Python

I use Python.Net for C# interaction with Python libraries. I solve the problem of text classification. I use FastText to index and get the vector, as well as Sklearn to train the classifier (Knn).During the implementation, I encountered a lot of problems, but all were solved, with the exception of one.
After receiving the vectors of the texts on which I train Knn, I save them to a separate text file and then, if necessary, use it.
string loadKnowVec = File.ReadAllText("vectorKnowClass.txt", Encoding.Default);
string[] splitKnowVec = loadKnowVec.Split('\r');
splitKnowVec = splitKnowVec.Where(x => x != "").ToArray();
for()
{
keyValues_vector.Add(float.Parse(splitKnowVec[i], NumberFormatInfo.InvariantInfo), 1);
}
dynamic X_vec = np.array(keyValues_vector.Keys.ToArray()).reshape(-1, 1);
dynamic y_tag = np.array(keyValues_vector.Values.ToArray());
dynamic neigh = KNN(n_neighbors: 3);
dynamic KnnFit = neigh.fit(X_vec, y_tag);
string predict = neigh.predict("0.00889");
MessageBox.Show("Скорее всего это: "+predict);
During the training of the classifier, I encountered such a problem that from c# to python, it is not values with the float type, but the value of System.Single[].
Python.Runtime.PythonException: "TypeError : float() argument must be a string or a number,
not 'Single[]'
The stored value, at this point, of dynamic X_vec is "System.Single[]".(I think that's exactly the problem)
2.At first I tried to manually set the values of X_vec, but the error and its values were the same.
The first idea was to change the array type using the numpy library, but it didn't help, it also gave out "".
dynamic Xx = np.array(X_vec, dtype: "float");
dynamic yY = np.array(y_tag, dtype: "int");
Next, it was tried to create an empty array in advance and load specific values into it before changing the data type, but this also did not work.
Perhaps I do not understand the principle of the formation and interaction of the MSVS19 IDE and the python interpreter.
I solved this issue for a couple of days and each time I thought it was worth reading the documentation on python.net .
As a result, I found a solution and it turned out to be quite banal, it is necessary to represent X_vec not as a float[] , but as a List<float>
List<float> vectors = keyValues_vector.Keys.ToList();
List<int> classTag = keyValues_vector.Values.ToList();
dynamic a = np.array(vectors);
dynamic X_vec = a.reshape(-1, 1);
dynamic y_tag = np.array(classTag);

Sorting INT variables C#

I am just beginning with programming in c#;
I got a list of int variables that I want to sort, and find the number 1.
int Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9
do I need to do this with an array?
By using the yellow book of C# I found out how to make an array, but I can't figure out how to assign the variables to the array.
int [] Weapon_Count = new int [11] ;
for ( int i=0; i<11; i=i+1)
{
Weapon_Count [i] = ??? ;}
I hope this does make sense..
Please let me explain how to use a C#-array.
This creates an unitialized integer-array with 5 elements:
int[] a1= new int[5];
Assigning values 9,8,7,6 and 5:
(Please note that only indexes from 0 to 4 can be used. Index 5 is not valid.)
a1[0]=9;
a1[1]=8;
a1[2]=7;
a1[3]=6;
a1[4]=5;
The same can also achieved with just one line:
int[] a1= new int[] {9,8,7,6,5};
This might help you.
// Declaring the array
int[] Weapon_Count;
// Initializing the array with a size of 11
Weapon_Count = new int[11];
// Adding values to the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Weapon_Count[i] = i + 100;
}
// Printing the values in the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Console.WriteLine(Weapon_Count[i]);
}
// Same thing with a list
// Daclare and initializing the List of integers
List<int> weapon_list = new List<int>();
// Adding some values
weapon_list.Add(1);
weapon_list.Add(2);
weapon_list.Add(3);
weapon_list.Add(4);
weapon_list.Add(5);
// Printing weapin_list's values
for (int i = 0; i < weapon_list.Count; i++)
{
Console.WriteLine(weapon_list[i]);
}
// This is just for the console to wait when you are in debug mode.
Console.ReadKey();
Dont forget to include the using statment if you want to use lists (in short hand - dynamic arrays that can change in size.)
using System.Collections.Generic;
The easiest way to do this, assuming there is a finite list of variables to check, would be to throw them into a temporary array and call either Max() or Min() from the System.Linq namespace.
int maxCount = new int[] { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 }.Max(); // or .Min()
EDIT
If you still want to get those variables into an array, I would recommend using a System.Collections.Generic.List which has a dynamic size and helper methods such as .Add() to simplify things. Lists can also be used with Linq functions similar to the first part of my answer. See Dot Net Perls for some really good examples on different C# data types and functions.
EDIT 2
As #kblok says, you'll want to add using System.Linq; at the top of your file to gain access to the functions such as Max and Min. If you want to try using the List type, you'll need to add using System.Collections.Generic; as well. If you're in Visual Studio 2017 (maybe 2015 as well?) you can type out the data type and then hit Ctrl + . to get suggestions for namespaces that might contain that data type.
Before we start, you might edit your array to look like this:
int[] weapons = { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 };
This means that you've created an array called weapons and it is holding integer values.
After you did this, lets find out which element in your array has value of number one.
To find which value has value "1" we must look at each element in array, and we might do that on few ways but I would like recommend foreach or for loop, in this case I will choose foreach loop.
foreach(var item in weapons)
{
if (item == 1)
//Do something
}
This above means, loop throught all of my elements, and in case some of them is equal to number one please do something..
P.S
(I may advice to create one variable which will hold an element which has value '1' and when you find it in a loop assing that variable to that element, and later you can do whatever you want with that variable.. and if you think there will be more elements with value of number one and you need all of them, instead of variable I mentioned above you will create list or array to hold all of your elements and also you can do later with them whatever you want to.)
Thanks and if you are interested in this kind of solution, leave me a comment so let me help you till the end to solve this if you are still struggling.

Read integer or doubles from JsonArray in C#

I have to receive a json file from my server and I need to parse it. Until now, I receive all fields as strings:
{"key1":"12", "key2":"23.5",...}
I read it like this:
JsonArray root = JsonValue.Parse(jsonString).GetArray();
for (uint i = 0; i < root.Count; i++)
{
int id = Convert.ToInt32(root.GetObjectAt(i).GetNamedString("id"));
int state = Convert.ToInt32(root.GetObjectAt(i).GetNamedString("state"));
.....
But now, I receive some of the data as integers or doubles and I don't know how to parse it in the way I did until now because there is no method to return an int with a string given.
{"key1":12, "key2":23.5,...}
System.Json does not allow you to see the difference between integers and floating point numbers. You might want to try Json.NET, which does:
var parsed = JObject.Parse("{\"key1\":12, \"key2\":23.5 }");
foreach (JProperty node in parsed.Children())
{
Console.WriteLine("{0}: {1}", node.Name, node.Value.Type);
}
The output:
key1: Integer
key2: Float
Of course, there are other libraries out there that can deal with JSON, but at least Json.NET works with Silverlight and supports your scenario.

Arrays Windows Forms Index was outside the bounds

there are a couple of these questions asked, but mine primarily involves Windows Forms, which there are few, although if there is an answer, a relatively well explained one without complicated jargon please let me know so I can learn from it.
Cutting to the chase: I want to read some data from a txt file into an array and then display it into some radio buttons. But for here I have simplified it and put them into a messagebox.
private void Game1_Load(object sender, EventArgs e)
{
const int iGAME = 4;
string[] sQuestions = new string[iGAME];
int iNum;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (iNum = 0; iNum < iGAME; iNum++)
{
MessageBox.Show(sQuestions[iGAME]);
}
}
The problem here is that the system tells me that the index exceeds the bounds. Now I have checked the txt file and there is definitely 4 pieces of information to apply to an array.
You're using the wrong index for the array. You're passing iGAME (a constant set to 4) when you should be using iNum (a variable between 0-3). Given that the upper-bound for the index is 3, the 4 will cause the ArrayIndexOutOfBoundsException.
Also, tip: C# is not C, so you don't need to use separate constants to denote the length of an array, also convention in C-style languages is to use just i as an index variable, and it avoids confusion between iGAME and iNum which has befallen you. Finally, avoid including the type-name in a variable's name, you don't need it anymore, this isn't the 1980s with Hungarian notation. You can rewrite your code to be more maintainable as:
String[] questions = new String[ 4 ];
for(int i=0; i<questions.Length; i++) {
...
}
Or just use this:
String[] questions = File.ReadAllLines( fileName );
foreach(String question in questions) MessageBox.Show( question );
I dont get what you want but first
MessageBox.Show(sQuestions[iGAME]) is wrong
change it to
MessageBox.Show(sQuestions[iNum ]);
I have managed to fix my code, to those that are doing a similar sort of thing to me here is my fix, hope it helps you:
int i;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (i = 0; i < Questions.GetLength(0); i++)
{
MessageBox.Show(Questions[i] = Convert.ToString(sr.ReadLine()));`
What I did here is state the loop variable i, using StreamReader to read the TXT file (don't forget to add using System.IO; at the top of the page. I then created a for loop so that it saves time by assigning each array with data. I then decided to show the results in a messagebox for simplicity by stating the Questions with the array counter [i] and then converted it to a string so it could be read in the box as before hand it was just blank.
Hopefully that little friendly walkthrough helps you solve your issue.

PHP equivalent to C#'s multi-dimensional array declaration

In C# you can do this:
poules = new int[aantal, aantal, 2];
I couldn't find a way in PHP to do this. All I can find is a two dimensional array.
The example you presented is creating a 3D array, and getting it by a method (which is a bit slower, since a method is used). PHP uses jagged arrays.
An array in PHP is created using the array function.
To match your example: (for fixed array length)
$myArr = new SplFixedArray($aantal);
for ($i = 0; $i < $aantal; $i++) {
$myArr[$i] = new SplFixedArray($aantal);
for ($j = 0; $j < $aantal; $j++) {
$myArr[$i][$j] = new SplFixedArray(2);
}
}
SplFixedArray is used to define an array with a fixed size.
As claimed in comments, you will rarely see a PHP code as the above.
you can access the array cells like this:
$val = $myArr[$x][$y][$z];
Here is a reference: SplFixedArray
I'm not a C# person, so take this with a grain of salt. After perusing the documentation though, new int[aantal, aantal, 2] seem to be the syntax to declare multi-dimensional int arrays, in this case a 3-dimensional array.
PHP doesn't have multi-dimensional arrays. It only has arrays, and you can have arrays of arrays. I guess this is called a "jagged array" in C#. PHP arrays are also not typed, there's no equivalent to int[].
You can simply declare/access several dimensions at once though:
$arr = array();
$arr[1][2][3] = 'foo';
PHP will create the intermediate arrays as needed. The array is jagged though, there's no $arr[0][2][3] after the above code executed.
If you need to pre-allocate all dimensions beforehand, you will have to recursively loop. This is not really something done very often in PHP though, you should adapt your practices to work with jagged arrays to get things done.
This would be a php array:
$poules = array('aantal', 'anntal', '2');
In case aantal is a variable, just the same without quotes:
$poules = array($aantal, $anntal, '2');
In PHP you don't need to specify the variable type. Although you can use it to validate or filter inputs.
You can read more about PHP arrays in the official documentation:
http://uk3.php.net/manual/en/language.types.array.php
$poules = array('aantal', 'aantal', 2);
Or are aanta1 arrays too? Because in php you can do:
$myArray = array("some data", array("more data", "in a other array"), array("key1" => "even with keys"));

Categories