How to switch MutableRuntimeReferenceImageLibrary? - c#

I know how to switch Reference Library,
I am using the following function.
public void switchImageLibrary(int curLibIndex)
{
trackImageManager.trackedImagesChanged -= OnTrackedImagesChanged;
var newLib = curLibIndex == 0 ? "QR Library" : "Image Library";
LogHandler.Instance.Log("Switching Library to :- " + newLib);
trackImageManager.enabled = false;
var lib = curLibIndex == 0 ? QRCodeImageLibrary : ImageAccessPointLibrary;
trackImageManager.referenceLibrary = trackImageManager.CreateRuntimeLibrary(lib) as MutableRuntimeReferenceImageLibrary;
trackImageManager.enabled = true;
trackImageManager.trackedImagesChanged += OnTrackedImagesChanged;
LogHandler.Instance.Log("Current Marker Count : " + trackImageManager.referenceLibrary.count);
LogHandler.Instance.Log("Current Library name " + trackImageManager.referenceLibrary.ToString());
for (int i = 0; i < trackImageManager.referenceLibrary.count; i++) {
LogHandler.Instance.Log("Reference Added In Library : " + trackImageManager.referenceLibrary[i].name);
}
}
I can see after Job Complete and Marker added an event but after that nothing happen, Marker Tracking event was not updated !!

Related

C# EPPlus databar conditional formatting with solid fill color

I am generating excel reports that involves several columns that are percentage data. Since the reports are for presentation purposes I want to make them look nice by formatting the percentage data with databars with solid fill. Somehow this proves to be extremely difficult as there is no direct setting in EPPlus for solid fill for databar but nevertheless I have arrived at the answer that is in this post:
Inconsistent appearance between manual and coded versions of solid databar and databar minimum value
However no matter how hard I try to edit the code for my application I only have one column that end up with solid fill with the rest being gradient. Even though I changed the node in the question to a nodelist such as below:
var cfNodes = xdoc.SelectNodes("/default:worksheet/default:conditionalFormatting/default:cfRule", nsm);
foreach(XmlNode cfNode in cfNodes)
{
cfNode.AppendChild(extLstCf);
}
and also for the worksheet elements:
var wsNodes = xdoc.SelectNodes("/default:worksheet", nsm);
foreach(XmlElement wsNode in wsNodes)
{
wsNode.AppendChild(extLstWs);
}
I also tried playing around with the xml changing the <sqref> parameter but that still doesn't cover all my databar columns. I think there has to be something that I can change in the xml to accomplish what I want but I don't know what to look for...
Ok guys It took me a few days but I finally figured it out. There might be a simpler way to do this but so far this is how I got it working for me:
A worksheet xml extension list node need to be appended at the worksheet level node which includes the number data bar elements that your worksheet contains, and each of them needs to have gradient = 0 for solid fill I. For example my worksheet contains two data bars so mine looks like this:
var extLstWs = xdoc.CreateNode(XmlNodeType.Element, "extLst", xdoc.DocumentElement.NamespaceURI);
extLstWs.InnerXml = #"<ext uri=""{78C0D931-6437-407d-A8EE-F0AAD7539E65}""
xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:conditionalFormattings>
<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{3F3F0E19-800E-4C9F-9CAF-1E3CE014ED86}"">
<x14:dataBar minLength=""0"" maxLength=""100"" gradient=""0"">
<x14:cfvo type=""num"">
<xm:f>0</xm:f>
</x14:cfvo>
<x14:cfvo type=""num"">
<xm:f>100</xm:f>
</x14:cfvo>
<x14:negativeFillColor rgb=""FFFF0000""/><x14:axisColor rgb=""FF000000""/>
</x14:dataBar>
</x14:cfRule>
<xm:sqref>A1:A20</xm:sqref>
</x14:conditionalFormatting>
<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{3F3F0E19-800E-4C9F-9CAF-1E3CE014ED86}"">
<x14:dataBar minLength=""0"" maxLength=""100"" gradient=""0"">
<x14:cfvo type=""num"">
<xm:f>0</xm:f>
</x14:cfvo><x14:cfvo type=""num"">
<xm:f>200</xm:f>
</x14:cfvo><x14:negativeFillColor rgb=""FFFF0000""/>
<x14:axisColor rgb=""FF000000""/>
</x14:dataBar>
</x14:cfRule>
<xm:sqref>B1:B20</xm:sqref>
</x14:conditionalFormatting>
</x14:conditionalFormattings>
</ext>";
var wsNode = xdoc.SelectSingleNode("/default:worksheet", nsm);
wsNode.AppendChild(extLstWs);
Notice how I got two subnodes of <x14:conditionalFormattings> in there, one for each databar.
Secondly another extension list for conditional formatting rule nodes need to be appended under the <cfRule> node, also one for each databar. I was able to use a foreach loop to find all the databars in my worksheet and append the same xml to each of them like below:
var cfNodes = xdoc.SelectNodes("/default:worksheet/default:conditionalFormatting/default:cfRule", nsm);
foreach (XmlNode cfnode in cfNodes)
{
var extLstCfNormal = xdoc.CreateNode(XmlNodeType.Element, "extLst", xdoc.DocumentElement.NamespaceURI);
extLstCfNormal.InnerXml = #"<ext uri=""{B025F937-C7B1-47D3-B67F-A62EFF666E3E}""
xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:id>{3F3F0E19-800E-4C9F-9CAF-1E3CE014ED86}</x14:id></ext>";
cfnode.AppendChild(extLstCfNormal);
}
After doing the above I was finally able to show all my databars with solid fill.
This is my version how to make databars solid fill for those who fail to apply Aowei Xu's solution (like me...).
public static Random Rnd = new Random();
public static string GenerateXlsId()
{
//{29BD882A-B741-482B-9067-72CC5D939236}
string id = string.Empty;
for (int i = 0; i < 32; i++)
if (Rnd.NextDouble() < 0.5)
id += Rnd.Next(0, 10);
else
id += (char)Rnd.Next(65, 91);
id = id.Insert(8, "-");
id = id.Insert(13, "-");
id = id.Insert(18, "-");
id = id.Insert(23, "-");
return id;
}
public static void FixDatabarsAtWorksheet(OfficeOpenXml.ExcelWorksheet eworksheet)
{
System.Xml.XmlNodeList databars = eworksheet.WorksheetXml.GetElementsByTagName("dataBar");
if (databars.Count > 0)
{
string conditional_formattings_str = string.Empty;
for (int i = 0; i < databars.Count; i++)
{
string temp_databar_id = GenerateXlsId();
databars[i].ParentNode.InnerXml += #"<extLst>
<ext uri=""{B025F937-C7B1-47D3-B67F-A62EFF666E3E}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:id>{" + temp_databar_id + #"}</x14:id>
</ext>
</extLst>";
//--
string temp_sqref = databars[i].ParentNode.ParentNode.Attributes["sqref"].Value;
string left_type = string.Empty;
string left_val = string.Empty;
string right_type = string.Empty;
string right_val = string.Empty;
string color = string.Empty;
Color databar_fill_color = Color.Empty;
Color databar_border_color = Color.Empty;
for (int j = 0; j < databars[i].ChildNodes.Count; j++)
if (databars[i].ChildNodes[j].LocalName == "cfvo" && databars[i].ChildNodes[j].Attributes["type"] != null)
{
if (string.IsNullOrEmpty(left_type))
left_type = databars[i].ChildNodes[j].Attributes["type"].Value;
else if (string.IsNullOrEmpty(right_type))
right_type = databars[i].ChildNodes[j].Attributes["type"].Value;
if (databars[i].ChildNodes[j].Attributes["val"] != null)
if (string.IsNullOrEmpty(left_val))
left_val = databars[i].ChildNodes[j].Attributes["val"].Value;
else if (string.IsNullOrEmpty(right_val))
right_val = databars[i].ChildNodes[j].Attributes["val"].Value;
}
else if (databars[i].ChildNodes[j].LocalName == "color")
{
color = databars[i].ChildNodes[j].Attributes["rgb"].Value;
int argb = Int32.Parse(color, System.Globalization.NumberStyles.HexNumber);
databar_fill_color = Color.FromArgb(argb);
databar_border_color = Color.FromArgb(255,
databar_fill_color.R - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.R - 50,
databar_fill_color.G - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.G - 50,
databar_fill_color.B - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.B - 50);
}
string temp_conditional_formatting_template = #"<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{" + temp_databar_id + #"}"">
<x14:dataBar minLength=""" + (string.IsNullOrEmpty(left_val) ? "0" : left_val) + "\" maxLength=\"" + (string.IsNullOrEmpty(right_val) ? "100" : right_val) + "\" gradient=\"0\" " + (databar_border_color.IsEmpty ? string.Empty : "border = \"1\"") + ">";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (left_type.ToLower() == "min" ? "autoMin" : left_type) + "\" />";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (right_type.ToLower() == "max" ? "autoMax" : right_type) + "\" />";
if (!databar_border_color.IsEmpty)
temp_conditional_formatting_template += Environment.NewLine + "<x14:borderColor rgb=\"" + BitConverter.ToString(new byte[] { databar_border_color.A, databar_border_color.R, databar_border_color.G, databar_border_color.B }).Replace("-", "") + "\" />";
temp_conditional_formatting_template += Environment.NewLine + #"</x14:dataBar>
</x14:cfRule>
<xm:sqref>" + temp_sqref + #"</xm:sqref>
</x14:conditionalFormatting>";
conditional_formattings_str += temp_conditional_formatting_template;
}
databars[0].ParentNode.ParentNode.ParentNode.InnerXml += #"<extLst>
<ext uri=""{78C0D931-6437-407d-A8EE-F0AAD7539E65}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:conditionalFormattings>" + conditional_formattings_str + #"
</x14:conditionalFormattings>
</ext>
</extLst>";
}
}
Such pain for such small thing... Gwa-a-a-a-a-ar-r-r-r!
P.S. MS, I hate you for XmlElements skipping prefix value when inserting them into parent nodes!
P.S.2. This makes any other conditional formatting to vanish... don't know why... OMG!

compare List with different size in C#

Hi I have an application in C# .NET where a person can submit an abstract. It will be a paragraph.
Now if I made any changes on that abstract from my end, It should send the email to that person with the Original abstract and modified abstract. Where in Modified section it should highlight the changes done.
I have written a function for this:
public string[] compareText(string submittedValue,string updatedValue)
{
#region COMPARETEXT
List<string> oldAbstract = submittedValue.Split('.').ToList<string>();
List<string> newAbstract = updatedValue.Split('.').ToList<string>();
string resultOldAbstract = "";
string resultNewAbstract = "";
for (var i = 0; i < (oldAbstract.Count - 1); i++)
{
if (String.Equals(oldAbstract[i], newAbstract[i], StringComparison.Ordinal))
{
resultOldAbstract += oldAbstract[i].ToString() + ".";
resultNewAbstract += newAbstract[i].ToString() + ".";
}
else
{
List<string> oldAbstract1 = oldAbstract[i].Split(' ').ToList<string>();
List<string> newAbstract1 = newAbstract[i].Split(' ').ToList<string>();
if (oldAbstract1.Count == newAbstract1.Count)
{
for (var j = 0; j < (oldAbstract1.Count); j++)
{
if (String.Equals(oldAbstract1[j], newAbstract1[j], StringComparison.Ordinal))
{
if (j < (oldAbstract1.Count - 1))
{
resultOldAbstract += oldAbstract1[j].ToString() + " ";
resultNewAbstract += newAbstract1[j].ToString() + " ";
}
else
{
resultOldAbstract += oldAbstract1[j].ToString() + ".";
resultNewAbstract += newAbstract1[j].ToString() + ".";
}
}
else
{
if (j < (oldAbstract1.Count - 1))
{
resultOldAbstract += oldAbstract1[j].ToString() + " ";
resultNewAbstract += "<span style='background:yellow'>" + newAbstract1[j].ToString() + "</span> ";
}
else
{
resultOldAbstract += oldAbstract1[j].ToString() + ".";
resultNewAbstract += "<span style='background:yellow'>" + newAbstract1[j].ToString() + "</span>.";
}
}
}
}
else
{
resultOldAbstract += oldAbstract[i].ToString() + ".";
resultNewAbstract += "<span style='background:yellow'>" + newAbstract[i].ToString() + "</span>.";
}
}
}
//return resultOldAbstract,resultNewAbstract;
return new[] {resultOldAbstract,resultNewAbstract};
#endregion
}
but it only works when the size of both list are same. For e.g.
****Submitted abstract****
hi This is John. i am 26 year old. I live in New York.
****Updated abstract****
Hi This is John. I am 26 year old. I live in washington.
when I do these changes then It works fine. It highlights the changes done at hi, i, New York.
Here the submitted list and updated list both have same number of elements ( here it is 3 , bcz i am splitting at fullstop '.'). But suppose in my update abstract I add a new line or remove a line:
****Updated abstract****
Hi This is John. I am 26 year old. I live in washington. I am a software engineer.
or
****Updated abstract****
Hi This is John. I am 26 year old.
then it does not work because the size of list is different and in for loop it throws index error.
Any thoughts ?

error CS0246: The type or namespace name `AForge' could not be found. Are you missing a using directive or an assembly reference?

I'm trying to make a n-Queens with Genetic Algorithm in Unity3D, but this error appears everytime...
code:
using UnityEngine;
using System;
using System.Collections;
using AForge.Genetic;
using AForge.Math;
namespace AlgoritmoGenetico
{
public class GA : MonoBehaviour {
int populationSizeBox;
int iterationsBox;
int nRainhasBox;
int crossoverRateBox;
int motacaoRateBox;
int paradaBox;
//int selecao;
private String log = "";
private int nRainhas = 14;
private int nPopulacao = 14;
private int nGeracoes = 8000;
private int nParada = 100;
private double crossoverRate = 0.75;
private double mutationRate = 0.01;
// Use this for initialization
void Start () {
Iniciar ();
}
// Update is called once per frame
void Update () {
}
public void Iniciar(){
configuraAlgoritimo();
int selecao = 0; // definimos para o metodo roleta
ISelectionMethod metodoDeSelecao = (selecao == 0) ? (ISelectionMethod)new RouletteWheelSelection() :
(selecao == 1) ? (ISelectionMethod)new EliteSelection() :
(ISelectionMethod)new RankSelection();
AvaliadorDeRainhas avaliador = new AvaliadorDeRainhas();
Population populacao = new Population(nPopulacao, new ShortArrayChromosome(nRainhas, nRainhas - 1), avaliador, metodoDeSelecao);
populacao.CrossoverRate = crossoverRate;
populacao.MutationRate = mutationRate;
int iteracao = 0;
int pararEm = nParada;
while (iteracao < nGeracoes)
{
populacao.RunEpoch();
if (nParada > 0 && iteracao == pararEm)
{
atualizaDadosPara(iteracao, populacao);
pararEm += nParada;
}
if (populacao.BestChromosome.Fitness == nRainhas)
break;
iteracao++;
}
atualizaDadosPara(iteracao,populacao);
}
private void atualizaDadosPara(int iteracao,Population populacao)
{
log = "Geração: " + iteracao +
"\n Método de Seleção : " + populacao.SelectionMethod +
"\n Avaliação Média: " + populacao.FitnessAvg +
"\n Melhor Avaliação : " + populacao.FitnessMax +
"\n Melhor indivíduo: " + populacao.BestChromosome.ToString();
print (log);
}
private void configuraAlgoritimo(){
try
{
nPopulacao = Math.Max(10, Math.Min(100, int.Parse(populationSizeBox)));
}
catch
{
nPopulacao = 8;
}
try
{
nGeracoes = Math.Max(0, int.Parse(iterationsBox));
}
catch
{
nGeracoes = 100;
}
try
{
nRainhas = Math.Max(4, int.Parse(nRainhasBox));
}
catch
{
nRainhas = 8;
}
try
{
crossoverRate = Math.Max(0.0, int.Parse(crossoverRateBox));
}
catch
{
crossoverRate = 0.75;
}
try
{
mutationRate = Math.Max(0.0, int.Parse(motacaoRateBox));
}
catch
{
mutationRate = 0.01;
}
try
{
nParada = Math.Max(0, int.Parse(paradaBox));
}
catch
{
nParada = 0;
}
}
}
}
I've recreated the problem that occured in your case.
You're missing AForge.dll file in your project's \Assets folder.
DLL you are looking for should be located in AForge.NET Framework-x.x.x-(libs only)\Release folder that you probably have downloaded zipped from AForge.NET site.
If you still struggle to find it, consider redownloading whole package from choosing [ Download Libraries Only ]:
http://www.aforgenet.com/framework/downloads.html
I've also fixed some issues you had there. You don't need to cast int value with int.Parse() if it is declared as int already.
Just do Math.Max(x, y) etc with functions you are using.
Also you are not using anything from AForge.Math namespace. If that was intentional, consider removing using AForge.Math; as it's unused.

C# my rich textbox keeps adding all the song names instead of just 1 at the time

i'm making a little music program for school, and i keep having problems wiht my richtextbox (rtb), it keeps adding all the songs from before and i don't know how to fix it without cleaning it over and over again everytime i click the button.
private void AddSongKtab()
{
SongKtab[nr] = new SongInfo();
string m_SongName;
string m_SongLocation;
ofdOpenKtab.ShowDialog();
m_SongName = ofdOpenKtab.SafeFileName;
m_SongLocation = ofdOpenKtab.FileName;
SongKtab[nr].SongName = m_SongName;
SongKtab[nr].SongLocation = m_SongLocation;
tbAddKtab.Text = "";
tbAddKtab.Text = m_SongName;
rtbExtraKtab.AppendText("added" + m_SongName + "\n");
rtbExtraKtab.AppendText("Located at " + m_SongLocation + "\n\n");
rtbSongsKtab.ScrollToCaret();
nr++;
showAllKtab();
}
private void showAllKtab()
{
int m_index;
rtbExtraKtab.Clear();
for (m_index = 0; m_index < nr; m_index++)
{
rtbSongsKtab.AppendText(SongKtab[m_index].SongName + "\n");
}
}

How to display opening times?

I'm trying to show intervals of working hours/days it's should look like this:
(source: clip2net.com)
I have table where I'm storing day number, open time and closing time for each day
(source: clip2net.com)
Then I created query=>
var groups = from s in this.OpenTimes
orderby s.Day
group s by new { s.Till, s.Start } into gr
select new
{
Time = gr.Key.Start + "-" + gr.Key.Till,
Days = this.OpenTimes
.Where(o => o.Start == gr.Key.Start && o.Till == gr.Key.Till)
.OrderBy(d => d.Day).Select(d => d.Day).ToArray()
};
This query provides all grouped time intervals and days that included to this time-range
But I faced with problem - I created second half that representing this groups, but it's not working properly.
Maybe somebody could explain to me needed point of vision or this basic logic of showing opening times.
Thanks in advice...
Next approach works for me:
result screen
public string OpeningTimesString
{
get
{
if (!this.OpeningTimes.IsLoaded)
this.OpeningTimes.Load();
var groups = (from s in this.OpeningTimes
orderby s.Day, s.Start, s.Stop
group s by new { Stop = formatTime(s.Stop), Start = formatTime(s.Start), s.Day } into gr
select new
{
Time = gr.Key.Start + "-" + gr.Key.Stop,
Day = gr.Key.Day
}).ToList();
string result = "";
int tmp = 1;
for (int i = 0; i < groups.Count(); i++)
{
//One one = new One();
bool exit = false;
tmp = i;
while (exit == false)
{
if (i + 1 < groups.Count && groups[i].Time.Equals(groups[i + 1].Time))
{
i++;
}
else
{
if (tmp != i)
result += (NormalDayOfWeek)(groups[tmp].Day - 1) + "-" + (NormalDayOfWeek)(groups[i].Day - 1) + " : " + groups[i].Time + "<br />";
else
result += (NormalDayOfWeek)(groups[i].Day - 1) + " : " + groups[i].Time + "<br />";
exit = true;
}
}
}
if (result.IsNotNull())
return result;
else
return "[%Not yet defined]";
}
}

Categories