I have this code :
namespace FrequencyGeneratorConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
int from = 100000;// Convert.ToInt32(txtFrom.Text);
int to = 999999;//Convert.ToInt32(txtTo.Text);
int numbers = 2000; //Convert.ToInt32(txtNumbers.Text);
int range = 50;// Convert.ToInt32(txtRange.Text);
var generatedFrequencies = new List<Frequency>(to - from);
var availableRanges = new List<AvailableRange>(to - from + 1);
//AvailableRange maxAvailableRange = new AvailableRange();
var random = new Random();
DateTime first = DateTime.Now;
for (int i = 0; i < numbers; i++)
{
var frequency = new Frequency();
if (availableRanges.Count == 0)
{
frequency.Number = random.Next(from, to);
frequency.Number = (int)Math.Round((decimal)frequency.Number / 5) * 5;
int fromValue = frequency.Number - (range / 2);
int toValue = frequency.Number + (range / 2);
frequency.From = fromValue < from ? from : fromValue;
frequency.To = toValue > to ? to : toValue;
generatedFrequencies.Add(frequency);
var availableRange1 = new AvailableRange { From = #from, To = frequency.From };
availableRange1.RangeLong = availableRange1.To - availableRange1.From;
availableRanges.Add(availableRange1);
var availableRange2 = new AvailableRange { From = frequency.To, To = to };
availableRange2.RangeLong = availableRange2.To - availableRange2.From;
availableRanges.Add(availableRange2);
}
else
{
DateTime d1 = DateTime.Now;
int max = 0, index = 0;
for (int j = 0; j < availableRanges.Count; j++)
{
if (availableRanges[j].RangeLong > range)
{
index = j;
}
}
DateTime d2 = DateTime.Now;
double total1 = (d2 - d1).TotalMilliseconds;
AvailableRange availableRange = availableRanges[index];
if (availableRange.RangeLong <= range)
{
Console.WriteLine("there is no available pathes " + generatedFrequencies.Count);
break;
}
DateTime d3 = DateTime.Now;
double total2 = (d3 - d2).TotalMilliseconds;
frequency.Number = random.Next(availableRange.From + (range / 2), availableRange.To - (range / 2));
frequency.Number = (int)Math.Round((decimal)frequency.Number / 5) * 5;
int fromValue = frequency.Number - (range / 2);
int toValue = frequency.Number + (range / 2);
frequency.From = fromValue < from ? from : fromValue;
frequency.To = toValue > to ? to : toValue;
generatedFrequencies.Add(frequency);
var availableRange1 = new AvailableRange { From = availableRange.From, To = frequency.From, RangeLong = frequency.From - availableRange.From };
availableRanges.Add(availableRange1);
//availableRange.From = 1;
var availableRange2 = new AvailableRange { From = frequency.To, To = availableRange.To, RangeLong = availableRange.To - frequency.To };
availableRanges.Add(availableRange2);
//availableRange.To = frequency.From;
//availableRange.RangeLong = availableRange.To - availableRange.From;
DateTime d4 = DateTime.Now;
double total3 = (d4 - d3).TotalMilliseconds;
//availableRange.RangeLong = 0;
availableRanges.RemoveAt(index);
DateTime d5 = DateTime.Now;
double total4 = (d5 - d4).TotalMilliseconds;
double total = (d5 - d1).TotalMilliseconds;
if (total > 1)
{
// Console.WriteLine(total + #" : " + total1 + #" : " + total2 + #" : " + total3 + #" : " + total4 +
// #" frequency : " + frequency.Number + #" max : " + max + #" index : " + index);
}
}
}
DateTime last = DateTime.Now;
Console.WriteLine((last - first));
Console.ReadLine();
}
}
public class Frequency
{
public int From { get; set; }
public int To { get; set; }
public int Number { get; set; }
public override string ToString()
{
return " from : " + From + " to : " + To + " number : " + Number;
}
}
public class AvailableRange
{
public int From { get; set; }
public int To { get; set; }
public int RangeLong { get; set; }
public override string ToString()
{
return " from : " + From + " to : " + To + " RangeLong : " + RangeLong;
}
}
}
now the problem is this code take some time
when i analyze the code i expect that some cycles take 15 milliseconds and others take 0 millisecond
if the number of loops is small this problem does not appear
i tried to solve this problem but i could not find the answered
what is the problem
Not use DateTime for performance measure. Use System.Diagnostics.Stopwatch
What you are seeing is the 16 millisecond accuracy limitation of the System.DateTime structure.
See http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx.
You need to use the System.Diagnostics.Stopwatch class instead for any sort of performance assessment as it is usually accurate to the microsecond (depending on how much thread context switching is occurring at the time of the test).
I think that you cannot get an accurate measurement because this is a user-mode code running in multitasking environment. Even if the thread priority is set to highest, it can be superseded by any kernel mode process.
Related
I would like to create a list where I have 10 main points and associated 4 minor points as a List to each main point.
Lets say I have a class definition like this and a method:
public class Abc{
public Point2D MainPoint { get; set; }
public List<Point2D> MinorPoints { get; set; }
public static List<Abc> AddValues(){
var result = new List<Abc>();
List<Point2D> newMinorPointsList = new List<Point2D>();
for (int i = 0; i < 10; i++){
var newMainPoint = new Point2D(10 * i, 5 * i);
for (int j = 0; j < 4; j++){
var newMinorPoint = new Point2D(20 * i * j, 10 * i * j);
newMinorPointsList.Add(newMinorPoint);
}
result.Add( new Abc() { MainPoint = newMainPoint, MinorPoints = new List<Point2D>(newMinorPointsList)});
}
}
public static string PrintValues(List<Abc> pointList){
string result = "";
string resultMain = "";
string resultMinor = "";
string resultMinorString = "";
var allPoints = new Abc();
for (int i = 0; i < pointList.Count; i++){
allPoints.MainPoint = pointList[i].MainPoint;
allPoints.MinorPoints = new List<Point2D>(pointList[i].MinorPoints);
for (int j = 0; j < allPoints.MinorPoints.Count; j++){
resultMinor = allPoints.MinorPoints[j] + ", ";
resultMinorString += resultMinor;
}
resultMain = "Main Point: " + allPoints.MainPoint + ", Minor Points: " + resultMinorString;
result += resultMain;
}
}
But I'm getting null reference exception at allPoints.MinorPoints = new List(pointList[i].MinorPoints); and it looks like values are not added into MinorPoints. What am I doing wrong?
Here is a re-write of your code:
public static List<Abc> CreateListOfAbc() {
var result = new List<Abc>();
for (int i = 0; i < 10; i++)
result.Add(new Abc() {
MainPoint = new Point2D(10 * i, 5 * i),
MinorPoints = Enumerable.Range(0, 4).Select(j => new Point2D(20 * i * j, 10 * i * j)).ToList()
});
return result;
}
public static string PrintListOfAbc(List<Abc> pointList) {
string result = "";
foreach (var p in pointList)
result += $"Main Point: {p.MainPoint}, Minor Points: {String.Join(", ", p.MinorPoints)}\n";
return result;
}
The disadvantage of the code below is that it calculates the RSI for all prices at once. What if I have to add a new price? It's going to recalculate everything just because one additional price in the array. It will take longer than if I backup AverageGain/AverageLoss.
public class RSI
{
private readonly int _period;
public RSI(int period)
{
_period = period;
}
public decimal[] Calculate(decimal[] prices)
{
var rsi = new decimal[prices.Length];
decimal gain = 0m;
decimal loss = 0m;
rsi[0] = 0m;
for (int i = 1; i <= _period; ++i)
{
var diff = prices[i] - prices[i - 1];
if (diff >= 0)
{
gain += diff;
}
else
{
loss -= diff;
}
}
decimal avrg = gain / _period;
decimal avrl = loss / _period;
decimal rs = gain / loss;
rsi[_period] = 100m - (100m / (1m + rs));
for (int i = _period + 1; i < prices.Length; ++i)
{
var diff = prices[i] - prices[i - 1];
if (diff >= 0)
{
avrg = ((avrg * (_period - 1)) + diff) / _period;
avrl = (avrl * (_period - 1)) / _period;
}
else
{
avrl = ((avrl * (_period - 1)) - diff) / _period;
avrg = (avrg * (_period - 1)) / _period;
}
rs = avrg / avrl;
rsi[i] = 100m - (100m / (1m + rs));
}
return rsi;
}
}
My idea is to make something that remembers the previous input and calculate the RSI based on it, just like this one. Right now, this code is not working because _period is not involved at all. Those people in that github made it, but I'm still struggling to do it because of all these inherited classes/interfaces. I don't want to implement all of the interfaces/abstract classes. The one I extracted below are enough for me.
// Trying to achieve this:
var candles = _client.GetKlines(bot.Symbol, KlineInterval.OneHour).Data.ToList();
RelativeStrengthIndex rsi = new RelativeStrengthIndex(12);
for (int i = 0; i < candles.Count - 1; i++)
{
var result = rsi.ComputeNextValue(new InputData(candles[i].Close));
Console.WriteLine($"RSI(12) = {result}");
}
// New candle data
var newResult = rsi.ComputeNextValue(new InputData(0.01256m));
Console.WriteLine($"RSI(12) = {newResult}");
public abstract class Indicator
{
public abstract decimal ComputeNextValue(InputData input);
public abstract void Reset();
}
public class InputData
{
public decimal Value { get; private set; }
public InputData(decimal value)
{
Value = value;
}
}
public class RelativeStrengthIndex : Indicator
{
private int _period;
private InputData _previousInput;
public decimal AverageGain { get; private set; }
public decimal AverageLoss { get; private set; }
public RelativeStrengthIndex(int period)
{
_period = period;
}
public override decimal ComputeNextValue(InputData input)
{
if (_previousInput != null && input.Value >= _previousInput.Value)
{
AverageGain = input.Value - _previousInput.Value;
AverageLoss = 0m;
}
else if (_previousInput != null && input.Value < _previousInput.Value)
{
AverageGain = 0m;
AverageLoss = _previousInput.Value - input.Value;
}
_previousInput = input;
if (AverageLoss == 0m)
{
return 100m;
}
var rs = AverageGain / AverageLoss;
return 100m - (100m / (1 + rs));
}
public override void Reset()
{
_previousInput = default;
}
}
I did it myself. If you have any suggestions/improvements, please note them in the comments.
public class RelativeStrengthIndex : Indicator
{
private readonly int _period;
private InputData _previousInput;
private int _index;
private decimal _gain;
private decimal _loss;
private decimal _averageGain;
private decimal _averageLoss;
public RelativeStrengthIndex(int period)
{
_period = period;
_index = 0;
_gain = 0;
_loss = 0;
_averageGain = 0;
_averageLoss = 0;
}
public override decimal ComputeNextValue(InputData input)
{
// Formula: https://stackoverflow.com/questions/38481354/rsi-vs-wilders-rsi-calculation-problems?rq=1
_index++;
if (_previousInput != null)
{
var diff = input.Value - _previousInput.Value;
_previousInput = input;
if (_index <= _period)
{
if (diff >= 0)
{
_totalGain += diff;
}
else
{
_totalLoss -= diff;
}
}
if (_index < _period)
{
return 0;
}
else if (_index == _period)
{
_averageGain = _totalGain / _period;
_averageLoss = _totalLoss / _period;
decimal rs = _averageGain / _averageLoss;
return 100 - (100 / (1 + rs));
}
else // if (_index >= _period + 1)
{
if (diff >= 0)
{
_averageGain = ((_averageGain * (_period - 1)) + diff) / _period;
_averageLoss = (_averageLoss * (_period - 1)) / _period;
}
else
{
_averageGain = (_averageGain * (_period - 1)) / _period;
_averageLoss = ((_averageLoss * (_period - 1)) - diff) / _period;
}
decimal rs = _averageGain / _averageLoss;
return 100 - (100 / (1 + rs));
}
}
_previousInput = input;
return 0;
}
public override void Reset()
{
_previousInput = null;
_index = 0;
_gain = 0;
_loss = 0;
_averageGain = 0;
_averageLoss = 0;
}
}
I'm developing a simple application which records data and then allows users to retrieve percentages based upon that data. Pass/Fail etc.
My Overall Calculations work just fine but when my 3,6,9 crate calculations take place they don't seem to change even though I've switched which user it should be pulling stats for.
I have changed my code to return a formatted string of the percent calculated in my calc_percent() method. I have also encapsulated my calculations in different methods to make it easier for me to read.
Here is a link to my github project. The project doesn't contain the dataset or tableadapters, I'm thinking my calculation errors could be related to my dataset queries but I'm not sure. I was under the impression that a Fill() method on a table adapter would fill the input dataset with the results of that query. This should allow me to preform further queries to narrow down my results correct? I may be using tableadapter queries improperly but I'm not sure.
#region Metrics Methods
private void generate_stats(User user)
{
int crate_total = 0;
try
{
crate_total = (int)this.CratesTableAdapter.count_crates_by_tech(user.Last_name);
generate_overall_stats(user);
// last 30 units stats
if (crate_total >= 3)
{
generate_3_crate_stats(user);
}
// last 60 units stats
if (crate_total >= 6)
{
generate_6_crate_stats(user);
}
// last 90 units stats
if (crate_total >= 9)
{
generate_9_crate_stats(user);
}
}
catch (NullReferenceException e)
{
MessageBox.Show(e.Message);
}
catch (OleDbException e)
{
MessageBox.Show(e.Message);
}
}
private string calc_percent(int total, int number)
{
double percentage = 0;
percentage = ((double)number / total) * 100;
string format_percent = string.Format("{0:0.00%}", percentage);
try
{
if (percentage == 0)
{
throw new NullReferenceException("Calculation Has Failed, Possible Data Inaccuracy");
}
}catch(NullReferenceException e)
{
MessageBox.Show(e.Message);
}
return format_percent;
}
private void generate_overall_stats(User user)
{
// Overall Stats
int total = (int)this.Audit_ResultsTableAdapter.count_units_by_user(user.Last_name);
int pass = (int)this.Audit_ResultsTableAdapter.count_pass_units_by_user(user.Last_name);
int fail = total - pass;
string ovr_pass_perc = calc_percent(total, pass);
string ovr_fail_perc = calc_percent(total, fail);
metrics_qc_overall_units_display.Text = total.ToString();
metrics_qc_overall_pass_display.Text = ovr_pass_perc;
metrics_qc_overall_fail_display.Text = ovr_fail_perc;
}
private void generate_3_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last30_group.Visible = true;
// Reset data set
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
// Get all crates by user in Desc order according to date (most recent dates at the top of the table)
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
// Get the 3 most recent crates
this.CratesTableAdapter.get_top_3_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_30 = calc_percent(tmp_total, crate_pass);
string fail_percent_30 = calc_percent(tmp_total, crate_fail);
metrics_qc_last30_pass_display.Text = pass_percent_30;
metrics_qc_last30_fail_display.Text = fail_percent_30;
}
private void generate_6_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last60_group.Visible = true;
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
this.CratesTableAdapter.get_top_6_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_60 = calc_percent(tmp_total, crate_pass);
string fail_percent_60 = calc_percent(tmp_total, crate_fail);
metrics_qc_last60_pass_display.Text = pass_percent_60;
metrics_qc_last60_fail_display.Text = fail_percent_60;
}
private void generate_9_crate_stats(User user)
{
int crate_pass = 0;
int crate_fail = 0;
metrics_qc_last90_group.Visible = true;
this.CratesTableAdapter.Fill(this.android_teamDataSet.Crates);
this.CratesTableAdapter.get_crates_by_tech(this.android_teamDataSet.Crates, user.Last_name);
this.CratesTableAdapter.get_top_9_crates(this.android_teamDataSet.Crates);
foreach (DataRow row in this.android_teamDataSet.Crates)
{
crate_pass = crate_pass + (int)row["passed_units"];
crate_fail = crate_fail + (int)row["failed_units"];
}
int tmp_total = crate_pass + crate_fail;
string pass_percent_90 = calc_percent(tmp_total, crate_pass);
string fail_percent_90 = calc_percent(tmp_total, crate_fail);
metrics_qc_last90_pass_display.Text = pass_percent_90;
metrics_qc_last90_fail_display.Text = fail_percent_90;
}
private void set_users_metrics_defaults()
{
metrics_qc_last30_group.Visible = false;
metrics_qc_last60_group.Visible = false;
metrics_qc_last90_group.Visible = false;
}
#endregion
#region Metrics Event Handlers
private void metrics_qc_display_panel_Paint(object sender, PaintEventArgs e)
{
}
private void metrics_auditor_combobox_SelectionChangeCommitted(object sender, EventArgs e)
{
}
private void metrics_qc_combobox_SelectionChangeCommitted(object sender, EventArgs e)
{
set_users_metrics_defaults();
User metrics_user = gen_user_for_metrics();
generate_stats(metrics_user);
}
#endregion
As it stands any crate_total >9 will also evaluate for > 3 and > 6.
if (crate_total >= 3)
if (crate_total >= 6)
if (crate_total >= 9)
You'll need to put upper and lower limits in your if statement.
// last 30 units stats
if (crate_total >= 3 && crate_total < 6)
// last 60 units stats
if (crate_total >= 6 && crate_total < 9)
// last 90 units stats
if (crate_total >= 9)
I changed how I was doing my calculations. The issue was when I would change users the overall stats would change but the 30/60/90 units stats wouldn't change it would always remain the same. I realized that the values weren't being cleared for some reason some way some how (popped into my head while driving). So I segregated everything.
#region Metrics Methods
private void generate_stats(User user)
{
int crate_total = 0;
try
{
crate_total = (int)this.CratesTableAdapter.count_crates_by_tech(user.Last_name);
generate_overall_stats(user);
if (crate_total >= 3)
{
generate_3_crate_stats(user, crate_total);
}
if (crate_total >= 6)
{
generate_6_crate_stats(user, crate_total);
}
//if (crate_total >= 9)
//{
// generate_9_crate_stats(user, crate_total);
//}
}
catch (NullReferenceException e)
{
MessageBox.Show(e.Message);
}
catch (OleDbException e)
{
MessageBox.Show(e.Message);
}
}
private string calc_percent(int total, int number)
{
double percentage = 0;
percentage = ((double)number / total) * 100;
string format_percent = string.Format("{0:0.00}%", percentage);
try
{
if (percentage == 0)
{
throw new NullReferenceException("Calculation Has Failed, Possible Data Inaccuracy");
}
}catch(NullReferenceException e)
{
MessageBox.Show(e.Message);
}
return format_percent;
}
private void generate_overall_stats(User user)
{
// Overall Stats
int total = (int)this.Audit_ResultsTableAdapter.count_units_by_user(user.Last_name);
int pass = (int)this.Audit_ResultsTableAdapter.count_pass_units_by_user(user.Last_name);
int fail = total - pass;
string ovr_pass_perc = calc_percent(total, pass);
string ovr_fail_perc = calc_percent(total, fail);
metrics_qc_overall_units_display.Text = total.ToString();
metrics_qc_overall_pass_display.Text = ovr_pass_perc;
metrics_qc_overall_fail_display.Text = ovr_fail_perc;
}
private void generate_3_crate_stats(User user, int crate_number)
{
metrics_qc_last30_group.Visible = true;
int[] crate_stats = crate_stats_count_3(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_30 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_30 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last30_pass_display.Text = pass_percent_30;
metrics_qc_last30_fail_display.Text = fail_percent_30;
}
private void generate_6_crate_stats(User user, int crate_number)
{
metrics_qc_last60_group.Visible = true;
int[] crate_stats = crate_stats_count_6(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_60 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_60 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last60_pass_display.Text = pass_percent_60;
metrics_qc_last60_fail_display.Text = fail_percent_60;
}
private void generate_9_crate_stats(User user, int crate_number)
{
metrics_qc_last90_group.Visible = true;
int[] crate_stats = crate_stats_count_9(user.Last_name, crate_number);
int tmp_total = crate_stats[0] + crate_stats[1];
string pass_percent_90 = calc_percent(tmp_total, crate_stats[0]);
string fail_percent_90 = calc_percent(tmp_total, crate_stats[1]);
metrics_qc_last90_pass_display.Text = pass_percent_90;
metrics_qc_last90_fail_display.Text = fail_percent_90;
}
private void set_users_metrics_defaults()
{
metrics_qc_last30_group.Visible = false;
metrics_qc_last60_group.Visible = false;
metrics_qc_last90_group.Visible = false;
}
private int[] crate_stats_count_3(string last_name, int crate_number)
{
int[] crate_numbers = new int[3];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 3; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
private int[] crate_stats_count_6(string last_name, int crate_number)
{
int[] crate_numbers = new int[6];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
crate_numbers[3] = crate_number -= 3;
crate_numbers[4] = crate_number -= 4;
crate_numbers[5] = crate_number -= 5;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 6; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
private int[] crate_stats_count_9(string last_name, int crate_number)
{
int[] crate_numbers = new int[9];
crate_numbers[0] = crate_number;
crate_numbers[1] = crate_number--;
crate_numbers[2] = crate_number -= 2;
crate_numbers[3] = crate_number -= 3;
crate_numbers[4] = crate_number -= 4;
crate_numbers[5] = crate_number -= 5;
crate_numbers[6] = crate_number -= 6;
crate_numbers[7] = crate_number -= 7;
crate_numbers[8] = crate_number -= 8;
int crate_pass = 0;
int crate_fail = 0;
for (int i = 0; i < 9; i++)
{
crate_pass = crate_pass + (int)this.Audit_ResultsTableAdapter.count_pass_units_by_crate_number_and_tech(crate_numbers[i], last_name);
crate_fail = crate_fail + (int)this.Audit_ResultsTableAdapter.count_fail_units_by_crate_number_and_tech(crate_numbers[i], last_name);
}
int[] crate_stats = new int[2];
crate_stats[0] = crate_pass;
crate_stats[1] = crate_fail;
return crate_stats;
}
#endregion
The code shown above calculates hopefully correct percentages based upon count() queries by crate_number / repair_technician. Now when the name is changed in the combo box stats update properly.
With one issue for some reason my 60 and 90 stats remain the same. I haven't looked past finding the bug yet, but I will address it this evening or tomorrow.
I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.
I am working on c# application and i want to accomplish following task:
I have 12 check boxes for 12 items and user can check any of the check boxes.
if check boxes 3,4,5,6,8,10,11,12 have been checked, I would like to display following output.
You have selected items 3-6,8,10-12.
Rules:
When consecutive number group count is 3 or more than 3,Show grouping like 3-6
else show individual number. 8
Firstly I suggest you to append value of all the checkbox in string like you have shown.
Function Calling :
string data = "3,5,6,7,8,10,12";
string res = GetResultString(data);
Functions :
string GetResultString(string data)
{
string[] arrData = data.Split(',').ToArray();
List<int> lstData = new List<int>();
foreach (string item in arrData)
{
lstData.Add(Convert.ToInt16(item));
}
lstData.Sort();
string finalStr = string.Empty;
if (lstData.Count > 0)
{
int start = lstData[0];
int end = start;
finalStr = string.Empty;
for (int index = 1; index < lstData.Count; index++)
{
if (end + 1 == lstData[index])
{
end = lstData[index];
}
else
{
finalStr += appendResult(start, end);
start = -1;
}
if (start == -1)
{
start = lstData[index];
end = lstData[index];
}
}
finalStr += appendResult(start, end);
}
finalStr = finalStr.Trim(',');
return finalStr;
}
string appendResult(int start,int end)
{
string res = string.Empty;
if (end - start > 1)
{
res += start + "-" + end.ToString() + ",";
start = -1;
}
else
{
while (start <= end)
{
res += start.ToString() + ",";
start++;
}
}
return res;
}
Hope this will done your job,
try this .. it will work i tested it
I have not created checkboxes so it is up to you to check which checkbox is selected get the string like from the selected checkboxes 3,4,5,6,8,10,11,12
string str1 = "3,4,5,6,8,10,11,12";
string[] strArr = str1.Split(',');
List<string> strFinal = new List<string>();
int[] myInts = Array.ConvertAll(strArr, s => int.Parse(s));
int arrLn = myInts.Length;
Array.Sort(myInts);
int intPrevVal = myInts[0];
int intPrevDiff = myInts[0];
int seriesCount = 1;
strFinal.Add(Convert.ToString(myInts[0]));
for (int j = 1; j < arrLn; j++)
{
int intCurr = myInts[j];
if (intCurr - intPrevVal == 1)
{
seriesCount++;
}
else
{
if (seriesCount >= 3)
{
strFinal[strFinal.Count - 1] = strFinal[strFinal.Count - 1] + "-" + intPrevVal;
seriesCount = 1;
}
else if (seriesCount == 2)
{
strFinal.Add(Convert.ToString(myInts[j - 1]));
seriesCount = 1;
//strFinal.Add(Convert.ToString(myInts[j]));
}
strFinal.Add(Convert.ToString(myInts[j]));
}
intPrevVal = intCurr;
}
if (seriesCount >= 3)
{
strFinal[strFinal.Count - 1] = strFinal[strFinal.Count - 1] + "-" + myInts[arrLn - 1];
}
else if (seriesCount == 2)
{
strFinal.Add(Convert.ToString(myInts[arrLn - 1]));
}
string FinalAns = string.Join(",", strFinal.ToArray());
Response.Write(FinalAns);
I suppose you did your checkbox with array (new...) if not do it maunally...
int min=13;
int max=0;
string s = "";
for (int i = 0; i<12; i++)
{
if (cb[i].checked && i<min)
min = i;
else if (cb[i].checked == false)
if (min != 13)
{
max = i-1;
s = s + min.ToString() + "-" + max.ToString() + " ";
min = 13;
}
}
if (cb[11].checked) s = s + min.ToString() + "-12"; // for case the last one is checked
// s contains your data
(I didn't check it but I think it need to be something like this.)
try this
var data = new List<int> { 3, 4, 5, 6, 8, 10, 11, 12 };
// data.Sort();
var groups = new List<string>();
var startIndex = 0;
for (var i = 1; i < data.Count; i++)
{
if (data[i - 1] == data[i] - 1)
{
continue;
}
groups.Add(startIndex == i - 1
? data[startIndex].ToString()
: data[startIndex] + "-" + data[i - 1] );
startIndex = i;
}
groups.Add(startIndex == data.Count - 1
? data[startIndex].ToString()
: data[startIndex] + "-" + data[data.Count - 1]);
var result = string.Join(",", groups);
version 2
[Fact]
public void Test()
{
var data = new List<int> { 3, 4, 5, 7, 8, 10, 11, 12 };
// data.Sort();
var groups = new List<string>();
var startIndex = 0;
for (var i = 1; i < data.Count; i++)
{
if (data[i - 1] == data[i] - 1)
{
continue;
}
AddToGroups(groups, startIndex, i, data);
startIndex = i;
}
AddToGroups(groups, startIndex, data.Count, data);
var result = string.Join(",", groups);
Assert.Equal("3-5,7,8,10-12", result);
}
private static void AddToGroups(List<string> groups, int startIndex, int actualIndex, List<int> data)
{
switch (actualIndex - startIndex)
{
case 1:
groups.Add(data[startIndex].ToString());
break;
case 2:
groups.Add(data[startIndex].ToString());
groups.Add(data[startIndex + 1].ToString());
break;
default:
groups.Add(data[startIndex] + "-" + data[actualIndex - 1]);
break;
}
}
You might have got the solution,but all the above solutions use string for appending data..You could use StringBuilder for optimized performance.
List<int> selectedCB = new List<int>() { 3, 4, 6, 7, 8, 9, 11, 12 };
string output = GetFormattedOutput(selectedCB);
The code for formatting data..
private string GetFormattedOutput(List<int> selectedCB)
{
// Can be changed if you want to increase
// groupby range
int rangeBy = 3;
int diffBy = 1;
int prevValue = 0;
List<int> tempList = new List<int>();
StringBuilder formattedOutput = new StringBuilder();
foreach (int currentValue in selectedCB)
{
var diff = currentValue - prevValue;
if(tempList.Count != 0 && diff > diffBy)
{
// Add the value in templist to formatted output
// If three are more numbers are in range
// Add the first and last
if (tempList.Count >= rangeBy)
{
formattedOutput.Append(tempList[0].ToString() + "-" +
tempList[tempList.Count - 1].ToString()+",");
}
else
{
AppendText(formattedOutput, tempList);
}
tempList.Clear();
}
tempList.Add(currentValue);
prevValue = currentValue;
}
if (tempList.Count != 0)
{
AppendText(formattedOutput, tempList);
}
formattedOutput.Remove(formattedOutput.Length - 1, 1);
return formattedOutput.ToString();
}
// To append the numbers in the list
string AppendText(StringBuilder output, List<int> tempList)
{
foreach (var temp in tempList)
{
output.Append(temp.ToString() + ",");
}
return output.ToString();
}