C# (Xamarin iOS) How to loop son data on Custom UITableViewCell? - c#

Any Help will be appreaciated :) Thank you in advance
I tried to loop other object inside of the function and its working but on this, it can't loop. Help. this is rush, and I'm not that familiar with creating iOS app.
public override void ViewDidLoad()
{
base.ViewDidLoad();
using (var web = new WebClient())
{
var url = "http://www.creativeinterlace.com/smitten/maintenance/api/feeds/get-miss-location/101";
json = web.DownloadString(url);
}
json = json.Replace("{\"location\":", "").Replace("}]}", "}]");
var ls = JArray.Parse(json);
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations = new List<Locations>
{
new Locations
{
shopname = name1,
address= loc1,
time = time1
},
};
}
nmtable.Source = new LocationSource(locations);
nmtable.RowHeight = 60;
nmtable.ReloadData();
}
}

You initialize the locations every time in the loop,so the list updates with only the newest object. You should initialize the list outside of the loop , and add object every time.
locations = new List<Locations>();
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations.Add(new Locations{ shopname = name1,address= loc1,time = time1});
};
}

Related

My C# WPF webscraper returns error when more than one result is found

I am working on a WPF XAML application that scrapes certain websites for products. I have the search part working and it finds what I'm looking for. But as soon as there is more then 1 result I get a System.InvalidoperationException. I use a ObservableCollection to put the results into a <ListBox>.
Here is the search method:
private static ObservableCollection<EntryModel> _entries = new ObservableCollection<EntryModel>();
public static ObservableCollection<EntryModel> LoadCollectionData
{
get { return _entries; }
set { _entries = value; }
}
public static void PrehmSearchResults(string SearchQuery)
{
HtmlWeb web = new HtmlWeb();
try
{
string ZoekOpdracht = SearchQuery.Replace(" ", "+");
HtmlDocument doc = web.Load("https://www.prehmshop.de/advanced_search_result.php?keywords=" + ZoekOpdracht);
var title = doc.DocumentNode.CssSelect("div.header_cell > a").Single().InnerText;
var links = doc.DocumentNode.CssSelect("a.product_link");
var productLink = new List<string>();
var productTitle = new List<string>();
foreach (var item in links)
{
if (item.Attributes["href"].Value.Contains(".html"))
{
productLink.Add(item.Attributes["href"].Value);
productTitle.Add(title);
}
}
var TitleAndLink = productLink.Zip(productTitle, (l, t) => new { productLink = l, productTitle = t });
foreach (var nw in TitleAndLink)
{
var product = new List<EntryModel>();
var adDetails = new EntryModel
{
Title = nw.productTitle,
Link = nw.productLink
};
Debug.Print(adDetails.ToString());
var ZoekOpdrachtInTitle = adDetails.Title.ToLower().Contains(ZoekOpdracht.ToLower());
if (ZoekOpdrachtInTitle)
{
_entries.Add(adDetails);
}
}
}
So I found the solution without changing too much code. thanks for the help from #PaulSinnema.
The link is part of the title so I only had to change
var title = doc.DocumentNode.CssSelect("div.header_cell > a").ToList();
And I had to change the foreach loop:
foreach (var item in title)
{
if (item.Attributes["href"].Value.Contains(".html"))
{
productLink.Add(item.Attributes["href"].Value);
productTitle.Add(item.InnerText);
}
}

Could not find column 'PredictedLabel'

I'm using ML.Net and trying to cluster some data, and the exception I'm getting is in the title: 'Could not find column 'PredictedLabel'. But I do have this column in my prediction class!
public class ClusterPrediction
{
public uint Label { get; set; }
// Predicted label from the trainer.
//[ColumnName("PredictedLabel")] <-- doesn't make a differnce if I have this or not
public uint PredictedLabel { get; set; }
public float[] Score { get; set; } = new float[0];
public float[] Features { get; set; } = new float[0];
}
Here is how I setup my pipeline:
var clusterSchema = SchemaDefinition.Create(typeof(InputCombinedClusterData));
for (int i = 0; i < 5; i++)
{
var col = clusterSchema[i];
var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
col.ColumnType = new VectorDataViewType(itemType, InputCombinedClusterData.LOOKBACK);
}
var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
var options = new KMeansTrainer.Options
{
// will tune this later
NumberOfClusters = 15,
OptimizationTolerance = 1e-9f,
MaximumNumberOfIterations = 10000,
};
var fundamentalCols = new List<string> { tons of columns };
string featuresColumnName = "Features";
var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
.Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"));
foreach (var col in fundamentalCols)
{
pipeline.Append(mlContext.Transforms.NormalizeMinMax(col));
}
pipeline.Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {lots more columns}));
pipeline.Append(mlContext.Clustering.Trainers.KMeans(options));
// Train the model.
var model = pipeline.Fit(trainingData);
// test the model
var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);
// Run the model on test data set
var transformedTestData = model.Transform(testData);
// Goes BOOM here
var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
transformedTestData, reuseRowObject: false).ToList();
I do have an alternate clustering trainer that DOES work, but it has far fewer columns. I'm not seeing the difference why the one above with more columns would blow up on not finding a PredictedLabel column when both trainers are using the same prediction class? Here is the one that does work for reference:
var clusterSchema = SchemaDefinition.Create(typeof(InputPriceClusterData));
for (int i = 0; i < 5; i++)
{
var col = clusterSchema[i];
var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
col.ColumnType = new VectorDataViewType(itemType, InputPriceClusterData.LOOKBACK);
}
var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
var options = new KMeansTrainer.Options
{
NumberOfClusters = 15,
OptimizationTolerance = 1e-9f,
MaximumNumberOfIterations = 10000
};
// Define the trainer.
string featuresColumnName = "Features";
var pipeline = mlContext.Transforms
.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume")
.Append(mlContext.Clustering.Trainers.KMeans(options));
// Train the model.
var model = pipeline.Fit(trainingData);
// test the model
var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);
// Run the model on test data set.
var transformedTestData = model.Transform(testData);
// Convert IDataView object to a list.
var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
transformedTestData, reuseRowObject: false).ToList();
For the initial broken trainer, what am I missing? Ordering of the appends?
Might be a bit of a facepalm moment, but the .Append method on a pipeline doesn't do an in place append like someIList.Sort() would. I also found that I can batch up all the column pairs for normalization too. Doing it all in 1 shot resolved the issue:
string featuresColumnName = "Features";
var colPairs = new List<InputOutputColumnPair>();
foreach (var col in fundamentalCols)
{
colPairs.Add(new InputOutputColumnPair(col, col));
}
var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
.Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"))
.Append(mlContext.Transforms.NormalizeMinMax(colPairs.ToArray()))
.Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {boatload of columns}))
.Append(mlContext.Clustering.Trainers.KMeans(options));

C# string array.length error when calling from a CSV file

I'm fairly new to C# and im writing a rental vehicle management system. I'm trying to retrieve all lines from a CSV file that is set up like this:
[Registration][Grade][Make][Model][Year][NumSeats][Transmission][Fuel][GPS][SunRoof][DailyRate][Colour]
[123ABC][Economy][Toyota][Camry][2005][5][Automatic][Petrol][No][No][30][White]
[234BCD][Economy][Ford][Focus][2012][5][Automatic][Petrol][Yes][No][45][Blue]
[987ZYX][Economy][Holden][Cruise][2016][5][Manual][Diesel][Yes][No][60][Red]
and then iterate it through a for loop before it's sent to another method.
In the following method beyond the one shown, it's being put into an ArrayList so that the values retrieved can be searched for by the user in the program.
I'm stuck on the for loop as it gives me an error on the vehicles1.Length; saying that vehicles1 is a use of an unassigned local variable. I don't know if initializing the array is my problem, because I've tried that and it gives me no errors but the program just breaks.
void setUpVehicles(out Fleet fleetVehicles)
{
const char DELIM = ',';
Vehicle veh = new Vehicle();
FileStream inFile = new FileStream(FILENAME3, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string recordIn;
string[] vehicles1;
recordIn = reader.ReadLine();
while (recordIn != null)
{
string year = veh.Year.ToString();
string seats = veh.NumSeats.ToString();
string gps = veh.GPS.ToString();
string sunRoof = veh.SunRoof.ToString();
string dailyRate = veh.DailyRate.ToString();
vehicles1 = recordIn.Split(DELIM);
veh.Registration = vehicles1[0];
veh.Grade = vehicles1[1];
veh.Make = vehicles1[2];
veh.Model = vehicles1[3];
year = vehicles1[4];
seats = vehicles1[5];
veh.Transmission = vehicles1[6];
veh.Fuel = vehicles1[7];
gps = vehicles1[8];
sunRoof = vehicles1[9];
dailyRate = vehicles1[10];
veh.Colour = vehicles1[11];
}
fleetVehicles = new Fleet();
for (int i = 0; i < vehicles1.Length; i++)
{
fleetVehicles.insertVehicle(vehicles1[i]);
}
}
IEnumerable<Vehicle> setUpVehicles(string fileName)
{
using(var reader = new StreamReader(fileName))
using(var parser = new Microsoft.VisualBasic.TextFieldParser(reader))
{
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.Delimiters = new string[] {","};
string[] row;
while(!parser.EndOfData)
{
row = parser.ReadFields();
var vehicle = new Vehicle {
Registration = row[0],
Grade = row[1],
Make = row[2],
Model = row[3],
Year = row[4],
NumSeats = row[5],
Transmission = row[6],
Fuel = row[7],
GPS = row[8],
SunRoo = row[9],
DailyRate = row[10],
Colour = row[11]
};
yield return vehicle;
}
}
}
Then you would call it to make a fleet like this:
var fleetVehicles = new Fleet();
foreach(var vehicle in setUpVehicles(FILENAME3))
{
feetVehicles.insertVehicles(vehicle);
}

Xamarin Android FindViewById<ListView> returns null

I am trying to pull REST data from an api deserialise it and place it in a list. I have tried like so
private void ParseAndDisplay(JsonValue json)
{
ListView lstData = FindViewById<ListView>(Resource.Id.lstData);
List<Team> list_teams = new List<Team>();
RootObject objs = JsonConvert.DeserializeObject<RootObject>(json.ToString());
foreach (var obj in objs.teams)
{
var id = obj._links.self.href;
var indexOfLastBackSlash = id.LastIndexOf("/") + 1;
id = id.Substring(indexOfLastBackSlash);
Team team = new Team();
team.name = obj.name;
//team.id = id;
list_teams.Add(team);
//var list = list_teams.ToArray();
var slist = new List<string>();
foreach (Team t in list_teams) { string s = t.name;
slist.Add(s);
}
var data = new string[slist.Count()];
data = slist.ToArray();
lstData.Adapter = new ArrayAdapter(this,Resource.Xml.listViewTemplate, data);
}
However lstData comes up as null when I try to assign it to the ArrayAdapter and an unhandled exception error occurs. I am trying to run it to my phone.

How to generate mdx query using C#?

I am new to mdx query and I am very curious about mdx query generation using C# so I searched for any demo or open source then I found Ranet.olap (https://ranetuilibraryolap.codeplex.com/) which is providing what I need.
After taking the dlls I tried to incorporate them in my code. I am pasting my full console code which should generate mdx query but it's not doing so, am I doing something wrong?
using System;
using System.Collections.Generic;
using Microsoft.AnalysisServices.AdomdClient;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Metadata;
using Ranet.Olap.Core.Types;
namespace MDX
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
string connString = "Provider=MSOLAP.3; Data Source=localhost;Initial Catalog=AdventureWorkDW2008R2;Integrated Security=SSPI;";
CubeDef cubes;
AdomdConnection conn = new AdomdConnection(connString);
conn.Open();
cubes = conn.Cubes.Find("AdventureWorkCube");
Ranet.Olap.Core.Managers.MdxQueryBuilder mdx = new Ranet.Olap.Core.Managers.MdxQueryBuilder();
mdx.Cube = cubes.Caption;
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listColumn = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listRow = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listData = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
//Column area
Dimension dmColumn = cubes.Dimensions.Find("Dim Product");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hColumn = dmColumn.Hierarchies["English Product Name"];
//hierarchy properties
List<PropertyInfo> lPropInfo = new List<PropertyInfo>();
foreach (var prop in hColumn.Properties)
{
PropertyInfo p = new PropertyInfo();
p.Name = prop.Name;
p.Value = prop.Value;
lPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIColumn = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIColumn.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIColumn.Caption = hColumn.Caption;
areaIColumn.CustomProperties = lPropInfo;
listColumn.Add(areaIColumn);
//Rows Area
Dimension dmRow = cubes.Dimensions.Find("Due Date");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hRow = dmRow.Hierarchies["English Month Name"];
List<PropertyInfo> lRowPropInfo = new List<PropertyInfo>();
foreach (var prop in hRow.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name,prop.Value);
lRowPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIRow = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIRow.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIRow.Caption = hRow.Caption;
areaIRow.CustomProperties = lRowPropInfo;
listRow.Add(areaIRow);
//Measure Area or Data Area
Measure ms = cubes.Measures.Find("Order Quantity");
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIData = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIData.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
areaIData.Caption = ms.Caption;
List<PropertyInfo> lmpropInfo = new List<PropertyInfo>();
foreach (var prop in ms.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name, prop.Value);
lmpropInfo.Add(p);
}
areaIData.CustomProperties = lmpropInfo;
listData.Add(areaIData);
mdx.AreaWrappersColumns = listColumn;
mdx.AreaWrappersRows = listRow;
mdx.AreaWrappersData = listData;
string mdxQuery = mdx.GenerateMdxQuery();
conn.Close();
}
}
}
A simple example of the generation mdx query (only Ranet OLAP 3.7 version):
using System.Collections.Generic;
using Ranet.Olap.Core.Data;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Types;
using Ranet.Olap.Core.Wrappers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
var mdx = new QueryBuilderParameters
{
CubeName = "[Adventure Works]",
SubCube = "",
MdxDesignerSetting = new MDXDesignerSettingWrapper(),
CalculatedMembers = new List<CalcMemberInfo>(),
CalculatedNamedSets = new List<CalculatedNamedSetInfo>(),
AreaWrappersFilter = new List<AreaItemWrapper>(),
AreaWrappersColumns = new List<AreaItemWrapper>(),
AreaWrappersRows = new List<AreaItemWrapper>(),
AreaWrappersData = new List<AreaItemWrapper>()
};
//define parameters
mdx.MdxDesignerSetting.HideEmptyColumns = false;
mdx.MdxDesignerSetting.HideEmptyRows = false;
mdx.MdxDesignerSetting.UseVisualTotals = false;
mdx.MdxDesignerSetting.SubsetCount = 0;
var itemCol1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Customer].[Customer Geography]"
};
mdx.AreaWrappersColumns.Add(itemCol1);
var itemRow1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Date].[Calendar]"
};
mdx.AreaWrappersRows.Add(itemRow1);
var itemData1 = new Measure_AreaItemWrapper();
itemData1.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
itemData1.UniqueName = "[Measures].[Internet Order Count]";
mdx.AreaWrappersData.Add(itemData1);
string query = MdxQueryBuilder.Default.BuildQuery(mdx, null);
}
}
}
MDX Query result:
SELECT
HIERARCHIZE(HIERARCHIZE([Customer].[Customer Geography].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 0,
HIERARCHIZE(HIERARCHIZE([Date].[Calendar].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 1
FROM
[Adventure Works]
WHERE ([Measures].[Internet Order Count])
CELL PROPERTIES BACK_COLOR, CELL_ORDINAL, FORE_COLOR, FONT_NAME, FONT_SIZE, FONT_FLAGS, FORMAT_STRING, VALUE, FORMATTED_VALUE, UPDATEABLE, ACTION_TYPE
Still in process of revising code for this engine, though some suggestions for you:
It looks like you just grab cube metadata (dims, measures etc.) and pass it to generator. This does not sound like a way to generate MDX. MDX statement should look like
select
{
// measures, calculated members
} on 0,
{
// dimension data - sets
} on 1 // probably more axis
from **Cube**
All other parameters are optional

Categories

Resources